repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
saltstack/salt
salt/modules/panos.py
get_uncommitted_changes
python
def get_uncommitted_changes(): ''' Retrieve a list of all uncommitted changes on the device. Requires PANOS version 8.0.0 or greater. CLI Example: .. code-block:: bash salt '*' panos.get_uncommitted_changes ''' _required_version = '8.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) query = {'type': 'op', 'cmd': '<show><config><list><changes></changes></list></config></show>'} return __proxy__['panos.call'](query)
Retrieve a list of all uncommitted changes on the device. Requires PANOS version 8.0.0 or greater. CLI Example: .. code-block:: bash salt '*' panos.get_uncommitted_changes
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/panos.py#L1260-L1279
null
# -*- coding: utf-8 -*- ''' Module to provide Palo Alto compatibility to Salt :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix .. versionadded:: 2018.3.0 Configuration ============= This module accepts connection configuration details either as parameters, or as configuration settings in pillar as a Salt proxy. Options passed into opts will be ignored if options are passed into pillar. .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` About ===== This execution module was designed to handle connections to a Palo Alto based firewall. This module adds support to send connections directly to the device through the XML API or through a brokered connection to Panorama. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import Salt Libs from salt.exceptions import CommandExecutionError import salt.proxy.panos import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'panos' def __virtual__(): ''' Will load for the panos proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'panos': return __virtualname__ except KeyError: pass return False, 'The panos execution module can only be loaded for panos proxy minions.' def _get_job_results(query=None): ''' Executes a query that requires a job for completion. This function will wait for the job to complete and return the results. ''' if not query: raise CommandExecutionError("Query parameters cannot be empty.") response = __proxy__['panos.call'](query) # If the response contains a job, we will wait for the results if 'result' in response and 'job' in response['result']: jid = response['result']['job'] while get_job(jid)['result']['job']['status'] != 'FIN': time.sleep(5) return get_job(jid) else: return response def add_config_lock(): ''' Prevent other users from changing configuration until the lock is released. CLI Example: .. code-block:: bash salt '*' panos.add_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><add></add></config-lock></request>'} return __proxy__['panos.call'](query) def check_antivirus(): ''' Get anti-virus information from PaloAlto Networks server CLI Example: .. code-block:: bash salt '*' panos.check_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><check></check></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def check_software(): ''' Get software information from PaloAlto Networks server. CLI Example: .. code-block:: bash salt '*' panos.check_software ''' query = {'type': 'op', 'cmd': '<request><system><software><check></check></software></system></request>'} return __proxy__['panos.call'](query) def clear_commit_tasks(): ''' Clear all commit tasks. CLI Example: .. code-block:: bash salt '*' panos.clear_commit_tasks ''' query = {'type': 'op', 'cmd': '<request><clear-commit-tasks></clear-commit-tasks></request>'} return __proxy__['panos.call'](query) def commit(): ''' Commits the candidate configuration to the running configuration. CLI Example: .. code-block:: bash salt '*' panos.commit ''' query = {'type': 'commit', 'cmd': '<commit></commit>'} return _get_job_results(query) def deactivate_license(key_name=None): ''' Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<request><license><deactivate><key><features><member>{0}</member></features>' '</key></deactivate></license></request>'.format(key_name)} return __proxy__['panos.call'](query) def delete_license(key_name=None): ''' Remove license keys on disk. key_name(str): The file name of the license key to be deleted. CLI Example: .. code-block:: bash salt '*' panos.delete_license key_name=License_File_Name.key ''' if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<delete><license><key>{0}</key></license></delete>'.format(key_name)} return __proxy__['panos.call'](query) def download_antivirus(): ''' Download the most recent anti-virus package. CLI Example: .. code-block:: bash salt '*' panos.download_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><download>' '<latest></latest></download></upgrade></anti-virus></request>'} return _get_job_results(query) def download_software_file(filename=None, synch=False): ''' Download software packages by filename. Args: filename(str): The filename of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_file PanOS_5000-8.0.0 salt '*' panos.download_software_file PanOS_5000-8.0.0 True ''' if not filename: raise CommandExecutionError("Filename option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<file>{0}</file></download></software></system></request>'.format(filename)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<file>{0}</file></download></software></system></request>'.format(filename)} return _get_job_results(query) def download_software_version(version=None, synch=False): ''' Download software packages by version number. Args: version(str): The version of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_version 8.0.0 salt '*' panos.download_software_version 8.0.0 True ''' if not version: raise CommandExecutionError("Version option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<version>{0}</version></download></software></system></request>'.format(version)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<version>{0}</version></download></software></system></request>'.format(version)} return _get_job_results(query) def fetch_license(auth_code=None): ''' Get new license(s) using from the Palo Alto Network Server. auth_code The license authorization code. CLI Example: .. code-block:: bash salt '*' panos.fetch_license salt '*' panos.fetch_license auth_code=foobar ''' if not auth_code: query = {'type': 'op', 'cmd': '<request><license><fetch></fetch></license></request>'} else: query = {'type': 'op', 'cmd': '<request><license><fetch><auth-code>{0}</auth-code></fetch></license>' '</request>'.format(auth_code)} return __proxy__['panos.call'](query) def get_address(address=None, vsys='1'): ''' Get the candidate configuration for the specified get_address object. This will not return address objects that are marked as pre-defined objects. address(str): The name of the address object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address myhost salt '*' panos.get_address myhost 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address/entry[@name=\'{1}\']'.format(vsys, address)} return __proxy__['panos.call'](query) def get_address_group(addressgroup=None, vsys='1'): ''' Get the candidate configuration for the specified address group. This will not return address groups that are marked as pre-defined objects. addressgroup(str): The name of the address group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address_group foobar salt '*' panos.get_address_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address-group/entry[@name=\'{1}\']'.format(vsys, addressgroup)} return __proxy__['panos.call'](query) def get_admins_active(): ''' Show active administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_active ''' query = {'type': 'op', 'cmd': '<show><admins></admins></show>'} return __proxy__['panos.call'](query) def get_admins_all(): ''' Show all administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_all ''' query = {'type': 'op', 'cmd': '<show><admins><all></all></admins></show>'} return __proxy__['panos.call'](query) def get_antivirus_info(): ''' Show information about available anti-virus packages. CLI Example: .. code-block:: bash salt '*' panos.get_antivirus_info ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><info></info></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def get_arp(): ''' Show ARP information. CLI Example: .. code-block:: bash salt '*' panos.get_arp ''' query = {'type': 'op', 'cmd': '<show><arp><entry name = \'all\'/></arp></show>'} return __proxy__['panos.call'](query) def get_cli_idle_timeout(): ''' Show timeout information for this administrative session. CLI Example: .. code-block:: bash salt '*' panos.get_cli_idle_timeout ''' query = {'type': 'op', 'cmd': '<show><cli><idle-timeout></idle-timeout></cli></show>'} return __proxy__['panos.call'](query) def get_cli_permissions(): ''' Show cli administrative permissions. CLI Example: .. code-block:: bash salt '*' panos.get_cli_permissions ''' query = {'type': 'op', 'cmd': '<show><cli><permissions></permissions></cli></show>'} return __proxy__['panos.call'](query) def get_disk_usage(): ''' Report filesystem disk space usage. CLI Example: .. code-block:: bash salt '*' panos.get_disk_usage ''' query = {'type': 'op', 'cmd': '<show><system><disk-space></disk-space></system></show>'} return __proxy__['panos.call'](query) def get_dns_server_config(): ''' Get the DNS server configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_dns_server_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/dns-setting/servers'} return __proxy__['panos.call'](query) def get_domain_config(): ''' Get the domain name configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_domain_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/domain'} return __proxy__['panos.call'](query) def get_dos_blocks(): ''' Show the DoS block-ip table. CLI Example: .. code-block:: bash salt '*' panos.get_dos_blocks ''' query = {'type': 'op', 'cmd': '<show><dos-block-table><all></all></dos-block-table></show>'} return __proxy__['panos.call'](query) def get_fqdn_cache(): ''' Print FQDNs used in rules and their IPs. CLI Example: .. code-block:: bash salt '*' panos.get_fqdn_cache ''' query = {'type': 'op', 'cmd': '<request><system><fqdn><show></show></fqdn></system></request>'} return __proxy__['panos.call'](query) def get_ha_config(): ''' Get the high availability configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ha_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/high-availability'} return __proxy__['panos.call'](query) def get_ha_link(): ''' Show high-availability link-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_link ''' query = {'type': 'op', 'cmd': '<show><high-availability><link-monitoring></link-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_path(): ''' Show high-availability path-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_path ''' query = {'type': 'op', 'cmd': '<show><high-availability><path-monitoring></path-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_state(): ''' Show high-availability state information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_state ''' query = {'type': 'op', 'cmd': '<show><high-availability><state></state></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_transitions(): ''' Show high-availability transition statistic information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_transitions ''' query = {'type': 'op', 'cmd': '<show><high-availability><transitions></transitions></high-availability></show>'} return __proxy__['panos.call'](query) def get_hostname(): ''' Get the hostname of the device. CLI Example: .. code-block:: bash salt '*' panos.get_hostname ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/hostname'} return __proxy__['panos.call'](query) def get_interface_counters(name='all'): ''' Get the counter statistics for interfaces. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interface_counters salt '*' panos.get_interface_counters ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><counter><interface>{0}</interface></counter></show>'.format(name)} return __proxy__['panos.call'](query) def get_interfaces(name='all'): ''' Show interface information. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interfaces salt '*' panos.get_interfaces ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><interface>{0}</interface></show>'.format(name)} return __proxy__['panos.call'](query) def get_job(jid=None): ''' List all a single job by ID. jid The ID of the job to retrieve. CLI Example: .. code-block:: bash salt '*' panos.get_job jid=15 ''' if not jid: raise CommandExecutionError("ID option must not be none.") query = {'type': 'op', 'cmd': '<show><jobs><id>{0}</id></jobs></show>'.format(jid)} return __proxy__['panos.call'](query) def get_jobs(state='all'): ''' List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending ''' if state.lower() == 'all': query = {'type': 'op', 'cmd': '<show><jobs><all></all></jobs></show>'} elif state.lower() == 'pending': query = {'type': 'op', 'cmd': '<show><jobs><pending></pending></jobs></show>'} elif state.lower() == 'processed': query = {'type': 'op', 'cmd': '<show><jobs><processed></processed></jobs></show>'} else: raise CommandExecutionError("The state parameter must be all, pending, or processed.") return __proxy__['panos.call'](query) def get_lacp(): ''' Show LACP state. CLI Example: .. code-block:: bash salt '*' panos.get_lacp ''' query = {'type': 'op', 'cmd': '<show><lacp><aggregate-ethernet>all</aggregate-ethernet></lacp></show>'} return __proxy__['panos.call'](query) def get_license_info(): ''' Show information about owned license(s). CLI Example: .. code-block:: bash salt '*' panos.get_license_info ''' query = {'type': 'op', 'cmd': '<request><license><info></info></license></request>'} return __proxy__['panos.call'](query) def get_license_tokens(): ''' Show license token files for manual license deactivation. CLI Example: .. code-block:: bash salt '*' panos.get_license_tokens ''' query = {'type': 'op', 'cmd': '<show><license-token-files></license-token-files></show>'} return __proxy__['panos.call'](query) def get_lldp_config(): ''' Show lldp config for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_config ''' query = {'type': 'op', 'cmd': '<show><lldp><config>all</config></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_counters(): ''' Show lldp counters for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_counters ''' query = {'type': 'op', 'cmd': '<show><lldp><counters>all</counters></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_local(): ''' Show lldp local info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_local ''' query = {'type': 'op', 'cmd': '<show><lldp><local>all</local></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_neighbors(): ''' Show lldp neighbors info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_neighbors ''' query = {'type': 'op', 'cmd': '<show><lldp><neighbors>all</neighbors></lldp></show>'} return __proxy__['panos.call'](query) def get_local_admins(): ''' Show all local administrator accounts. CLI Example: .. code-block:: bash salt '*' panos.get_local_admins ''' admin_list = get_users_config() response = [] if 'users' not in admin_list['result']: return response if isinstance(admin_list['result']['users']['entry'], list): for entry in admin_list['result']['users']['entry']: response.append(entry['name']) else: response.append(admin_list['result']['users']['entry']['name']) return response def get_logdb_quota(): ''' Report the logdb quotas. CLI Example: .. code-block:: bash salt '*' panos.get_logdb_quota ''' query = {'type': 'op', 'cmd': '<show><system><logdb-quota></logdb-quota></system></show>'} return __proxy__['panos.call'](query) def get_master_key(): ''' Get the master key properties. CLI Example: .. code-block:: bash salt '*' panos.get_master_key ''' query = {'type': 'op', 'cmd': '<show><system><masterkey-properties></masterkey-properties></system></show>'} return __proxy__['panos.call'](query) def get_ntp_config(): ''' Get the NTP configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers'} return __proxy__['panos.call'](query) def get_ntp_servers(): ''' Get list of configured NTP servers. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_servers ''' query = {'type': 'op', 'cmd': '<show><ntp></ntp></show>'} return __proxy__['panos.call'](query) def get_operational_mode(): ''' Show device operational mode setting. CLI Example: .. code-block:: bash salt '*' panos.get_operational_mode ''' query = {'type': 'op', 'cmd': '<show><operational-mode></operational-mode></show>'} return __proxy__['panos.call'](query) def get_panorama_status(): ''' Show panorama connection status. CLI Example: .. code-block:: bash salt '*' panos.get_panorama_status ''' query = {'type': 'op', 'cmd': '<show><panorama-status></panorama-status></show>'} return __proxy__['panos.call'](query) def get_permitted_ips(): ''' Get the IP addresses that are permitted to establish management connections to the device. CLI Example: .. code-block:: bash salt '*' panos.get_permitted_ips ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip'} return __proxy__['panos.call'](query) def get_platform(): ''' Get the platform model information and limitations. CLI Example: .. code-block:: bash salt '*' panos.get_platform ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/platform'} return __proxy__['panos.call'](query) def get_predefined_application(application=None): ''' Get the configuration for the specified pre-defined application object. This will only return pre-defined application objects. application(str): The name of the pre-defined application object. CLI Example: .. code-block:: bash salt '*' panos.get_predefined_application saltstack ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/predefined/application/entry[@name=\'{0}\']'.format(application)} return __proxy__['panos.call'](query) def get_security_rule(rulename=None, vsys='1'): ''' Get the candidate configuration for the specified security rule. rulename(str): The name of the security rule. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_security_rule rule01 salt '*' panos.get_security_rule rule01 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'rulebase/security/rules/entry[@name=\'{1}\']'.format(vsys, rulename)} return __proxy__['panos.call'](query) def get_service(service=None, vsys='1'): ''' Get the candidate configuration for the specified service object. This will not return services that are marked as pre-defined objects. service(str): The name of the service object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service tcp-443 salt '*' panos.get_service tcp-443 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service/entry[@name=\'{1}\']'.format(vsys, service)} return __proxy__['panos.call'](query) def get_service_group(servicegroup=None, vsys='1'): ''' Get the candidate configuration for the specified service group. This will not return service groups that are marked as pre-defined objects. servicegroup(str): The name of the service group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service_group foobar salt '*' panos.get_service_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service-group/entry[@name=\'{1}\']'.format(vsys, servicegroup)} return __proxy__['panos.call'](query) def get_session_info(): ''' Show device session statistics. CLI Example: .. code-block:: bash salt '*' panos.get_session_info ''' query = {'type': 'op', 'cmd': '<show><session><info></info></session></show>'} return __proxy__['panos.call'](query) def get_snmp_config(): ''' Get the SNMP configuration from the device. CLI Example: .. code-block:: bash salt '*' panos.get_snmp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/snmp-setting'} return __proxy__['panos.call'](query) def get_software_info(): ''' Show information about available software packages. CLI Example: .. code-block:: bash salt '*' panos.get_software_info ''' query = {'type': 'op', 'cmd': '<request><system><software><info></info></software></system></request>'} return __proxy__['panos.call'](query) def get_system_date_time(): ''' Get the system date/time. CLI Example: .. code-block:: bash salt '*' panos.get_system_date_time ''' query = {'type': 'op', 'cmd': '<show><clock></clock></show>'} return __proxy__['panos.call'](query) def get_system_files(): ''' List important files in the system. CLI Example: .. code-block:: bash salt '*' panos.get_system_files ''' query = {'type': 'op', 'cmd': '<show><system><files></files></system></show>'} return __proxy__['panos.call'](query) def get_system_info(): ''' Get the system information. CLI Example: .. code-block:: bash salt '*' panos.get_system_info ''' query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'} return __proxy__['panos.call'](query) def get_system_services(): ''' Show system services. CLI Example: .. code-block:: bash salt '*' panos.get_system_services ''' query = {'type': 'op', 'cmd': '<show><system><services></services></system></show>'} return __proxy__['panos.call'](query) def get_system_state(mask=None): ''' Show the system state variables. mask Filters by a subtree or a wildcard. CLI Example: .. code-block:: bash salt '*' panos.get_system_state salt '*' panos.get_system_state mask=cfg.ha.config.enabled salt '*' panos.get_system_state mask=cfg.ha.* ''' if mask: query = {'type': 'op', 'cmd': '<show><system><state><filter>{0}</filter></state></system></show>'.format(mask)} else: query = {'type': 'op', 'cmd': '<show><system><state></state></system></show>'} return __proxy__['panos.call'](query) def get_users_config(): ''' Get the local administrative user account configuration. CLI Example: .. code-block:: bash salt '*' panos.get_users_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/mgt-config/users'} return __proxy__['panos.call'](query) def get_vlans(): ''' Show all VLAN information. CLI Example: .. code-block:: bash salt '*' panos.get_vlans ''' query = {'type': 'op', 'cmd': '<show><vlan>all</vlan></show>'} return __proxy__['panos.call'](query) def get_xpath(xpath=''): ''' Retrieve a specified xpath from the candidate configuration. xpath(str): The specified xpath in the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_xpath /config/shared/service ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} return __proxy__['panos.call'](query) def get_zone(zone='', vsys='1'): ''' Get the candidate configuration for the specified zone. zone(str): The name of the zone. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zone trust salt '*' panos.get_zone trust 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone/entry[@name=\'{1}\']'.format(vsys, zone)} return __proxy__['panos.call'](query) def get_zones(vsys='1'): ''' Get all the zones in the candidate configuration. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zones salt '*' panos.get_zones 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone'.format(vsys)} return __proxy__['panos.call'](query) def install_antivirus(version=None, latest=False, synch=False, skip_commit=False,): ''' Install anti-virus packages. Args: version(str): The version of the PANOS file to install. latest(bool): If true, the latest anti-virus file will be installed. The specified version option will be ignored. synch(bool): If true, the anti-virus will synch to the peer unit. skip_commit(bool): If true, the install will skip committing to the device. CLI Example: .. code-block:: bash salt '*' panos.install_antivirus 8.0.0 ''' if not version and latest is False: raise CommandExecutionError("Version option must not be none.") if synch is True: s = "yes" else: s = "no" if skip_commit is True: c = "yes" else: c = "no" if latest is True: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>latest</version></install></upgrade></anti-virus></request>'.format(c, s)} else: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>{2}</version></install></upgrade></anti-virus></request>'.format(c, s, version)} return _get_job_results(query) def install_license(): ''' Install the license key(s). CLI Example: .. code-block:: bash salt '*' panos.install_license ''' query = {'type': 'op', 'cmd': '<request><license><install></install></license></request>'} return __proxy__['panos.call'](query) def install_software(version=None): ''' Upgrade to a software package by version. Args: version(str): The version of the PANOS file to install. CLI Example: .. code-block:: bash salt '*' panos.install_license 8.0.0 ''' if not version: raise CommandExecutionError("Version option must not be none.") query = {'type': 'op', 'cmd': '<request><system><software><install>' '<version>{0}</version></install></software></system></request>'.format(version)} return _get_job_results(query) def reboot(): ''' Reboot a running system. CLI Example: .. code-block:: bash salt '*' panos.reboot ''' query = {'type': 'op', 'cmd': '<request><restart><system></system></restart></request>'} return __proxy__['panos.call'](query) def refresh_fqdn_cache(force=False): ''' Force refreshes all FQDNs used in rules. force Forces all fqdn refresh CLI Example: .. code-block:: bash salt '*' panos.refresh_fqdn_cache salt '*' panos.refresh_fqdn_cache force=True ''' if not isinstance(force, bool): raise CommandExecutionError("Force option must be boolean.") if force: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh><force>yes</force></refresh></fqdn></system></request>'} else: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh></refresh></fqdn></system></request>'} return __proxy__['panos.call'](query) def remove_config_lock(): ''' Release config lock previously held. CLI Example: .. code-block:: bash salt '*' panos.remove_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><remove></remove></config-lock></request>'} return __proxy__['panos.call'](query) def resolve_address(address=None, vsys=None): ''' Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com salt '*' panos.resolve_address foo.bar.com vsys=2 ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not address: raise CommandExecutionError("FQDN to resolve must be provided as address.") if not vsys: query = {'type': 'op', 'cmd': '<request><resolve><address>{0}</address></resolve></request>'.format(address)} else: query = {'type': 'op', 'cmd': '<request><resolve><vsys>{0}</vsys><address>{1}</address></resolve>' '</request>'.format(vsys, address)} return __proxy__['panos.call'](query) def save_device_config(filename=None): ''' Save device configuration to a named file. filename The filename to save the configuration to. CLI Example: .. code-block:: bash salt '*' panos.save_device_config foo.xml ''' if not filename: raise CommandExecutionError("Filename must not be empty.") query = {'type': 'op', 'cmd': '<save><config><to>{0}</to></config></save>'.format(filename)} return __proxy__['panos.call'](query) def save_device_state(): ''' Save files needed to restore device to local disk. CLI Example: .. code-block:: bash salt '*' panos.save_device_state ''' query = {'type': 'op', 'cmd': '<save><device-state></device-state></save>'} return __proxy__['panos.call'](query) def set_authentication_profile(profile=None, deploy=False): ''' Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_authentication_profile foo salt '*' panos.set_authentication_profile foo deploy=True ''' if not profile: raise CommandExecutionError("Profile name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/' 'authentication-profile', 'element': '<authentication-profile>{0}</authentication-profile>'.format(profile)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_hostname(hostname=None, deploy=False): ''' Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True ''' if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system', 'element': '<hostname>{0}</hostname>'.format(hostname)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_icmp(enabled=True, deploy=False): ''' Enables or disables the ICMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_icmp salt '*' panos.set_management_icmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-icmp>{0}</disable-icmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_http(enabled=True, deploy=False): ''' Enables or disables the HTTP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_http salt '*' panos.set_management_http enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http>{0}</disable-http>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_https(enabled=True, deploy=False): ''' Enables or disables the HTTPS management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_https salt '*' panos.set_management_https enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-https>{0}</disable-https>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ocsp(enabled=True, deploy=False): ''' Enables or disables the HTTP OCSP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ocsp salt '*' panos.set_management_ocsp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http-ocsp>{0}</disable-http-ocsp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_snmp(enabled=True, deploy=False): ''' Enables or disables the SNMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_snmp salt '*' panos.set_management_snmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-snmp>{0}</disable-snmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ssh(enabled=True, deploy=False): ''' Enables or disables the SSH management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ssh salt '*' panos.set_management_ssh enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-ssh>{0}</disable-ssh>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_telnet(enabled=True, deploy=False): ''' Enables or disables the Telnet management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_telnet salt '*' panos.set_management_telnet enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-telnet>{0}</disable-telnet>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_ntp_authentication(target=None, authentication_type=None, key_id=None, authentication_key=None, algorithm=None, deploy=False): ''' Set the NTP authentication of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: target(str): Determines the target of the authentication. Valid options are primary, secondary, or both. authentication_type(str): The authentication type to be used. Valid options are symmetric, autokey, and none. key_id(int): The NTP authentication key ID. authentication_key(str): The authentication key. algorithm(str): The algorithm type to be used for a symmetric key. Valid options are md5 and sha1. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_authentication target=both authentication_type=autokey salt '*' ntp.set_authentication target=primary authentication_type=none salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 deploy=True ''' ret = {} if target not in ['primary', 'secondary', 'both']: raise salt.exceptions.CommandExecutionError("Target option must be primary, secondary, or both.") if authentication_type not in ['symmetric', 'autokey', 'none']: raise salt.exceptions.CommandExecutionError("Type option must be symmetric, autokey, or both.") if authentication_type == "symmetric" and not authentication_key: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, authentication_key must be " "provided.") if authentication_type == "symmetric" and not key_id: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, key_id must be provided.") if authentication_type == "symmetric" and algorithm not in ['md5', 'sha1']: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, algorithm must be md5 or " "sha1.") if authentication_type == 'symmetric': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'autokey': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'none': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): ''' Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server(str): The secondary NTP server IP address or FQDN. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_servers 0.pool.ntp.org 1.pool.ntp.org salt '*' ntp.set_servers primary_server=0.pool.ntp.org secondary_server=1.pool.ntp.org salt '*' ntp.ser_servers 0.pool.ntp.org 1.pool.ntp.org deploy=True ''' ret = {} if primary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(primary_server)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if secondary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(secondary_server)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_permitted_ip(address=None, deploy=False): ''' Add an IPv4 address or network to the permitted IP list. CLI Example: Args: address (str): The IPv4 address or network to allow access to add to the Palo Alto device. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_permitted_ip 10.0.0.1 salt '*' panos.set_permitted_ip 10.0.0.0/24 salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True ''' if not address: raise CommandExecutionError("Address option must not be empty.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip', 'element': '<entry name=\'{0}\'></entry>'.format(address)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_timezone UTC salt '*' panos.set_timezone UTC deploy=True ''' if not tz: raise CommandExecutionError("Timezone name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/timezone', 'element': '<timezone>{0}</timezone>'.format(tz)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def shutdown(): ''' Shutdown a running system. CLI Example: .. code-block:: bash salt '*' panos.shutdown ''' query = {'type': 'op', 'cmd': '<request><shutdown><system></system></shutdown></request>'} return __proxy__['panos.call'](query) def test_fib_route(ip=None, vr='vr1'): ''' Perform a route lookup within active route table (fib). ip (str): The destination IP address to test. vr (str): The name of the virtual router to test. CLI Example: .. code-block:: bash salt '*' panos.test_fib_route 4.2.2.2 salt '*' panos.test_fib_route 4.2.2.2 my-vr ''' xpath = "<test><routing><fib-lookup>" if ip: xpath += "<ip>{0}</ip>".format(ip) if vr: xpath += "<virtual-router>{0}</virtual-router>".format(vr) xpath += "</fib-lookup></routing></test>" query = {'type': 'op', 'cmd': xpath} return __proxy__['panos.call'](query) def test_security_policy(sourcezone=None, destinationzone=None, source=None, destination=None, protocol=None, port=None, application=None, category=None, vsys='1', allrules=False): ''' Checks which security policy as connection will match on the device. sourcezone (str): The source zone matched against the connection. destinationzone (str): The destination zone matched against the connection. source (str): The source address. This must be a single IP address. destination (str): The destination address. This must be a single IP address. protocol (int): The protocol number for the connection. This is the numerical representation of the protocol. port (int): The port number for the connection. application (str): The application that should be matched. category (str): The category that should be matched. vsys (int): The numerical representation of the VSYS ID. allrules (bool): Show all potential match rules until first allow rule. CLI Example: .. code-block:: bash salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 vsys=2 ''' xpath = "<test><security-policy-match>" if sourcezone: xpath += "<from>{0}</from>".format(sourcezone) if destinationzone: xpath += "<to>{0}</to>".format(destinationzone) if source: xpath += "<source>{0}</source>".format(source) if destination: xpath += "<destination>{0}</destination>".format(destination) if protocol: xpath += "<protocol>{0}</protocol>".format(protocol) if port: xpath += "<destination-port>{0}</destination-port>".format(port) if application: xpath += "<application>{0}</application>".format(application) if category: xpath += "<category>{0}</category>".format(category) if allrules: xpath += "<show-all>yes</show-all>" xpath += "</security-policy-match></test>" query = {'type': 'op', 'vsys': "vsys{0}".format(vsys), 'cmd': xpath} return __proxy__['panos.call'](query) def unlock_admin(username=None): ''' Unlocks a locked administrator account. username Username of the administrator. CLI Example: .. code-block:: bash salt '*' panos.unlock_admin username=bob ''' if not username: raise CommandExecutionError("Username option must not be none.") query = {'type': 'op', 'cmd': '<set><management-server><unlock><admin>{0}</admin></unlock></management-server>' '</set>'.format(username)} return __proxy__['panos.call'](query)
saltstack/salt
salt/modules/panos.py
install_antivirus
python
def install_antivirus(version=None, latest=False, synch=False, skip_commit=False,): ''' Install anti-virus packages. Args: version(str): The version of the PANOS file to install. latest(bool): If true, the latest anti-virus file will be installed. The specified version option will be ignored. synch(bool): If true, the anti-virus will synch to the peer unit. skip_commit(bool): If true, the install will skip committing to the device. CLI Example: .. code-block:: bash salt '*' panos.install_antivirus 8.0.0 ''' if not version and latest is False: raise CommandExecutionError("Version option must not be none.") if synch is True: s = "yes" else: s = "no" if skip_commit is True: c = "yes" else: c = "no" if latest is True: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>latest</version></install></upgrade></anti-virus></request>'.format(c, s)} else: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>{2}</version></install></upgrade></anti-virus></request>'.format(c, s, version)} return _get_job_results(query)
Install anti-virus packages. Args: version(str): The version of the PANOS file to install. latest(bool): If true, the latest anti-virus file will be installed. The specified version option will be ignored. synch(bool): If true, the anti-virus will synch to the peer unit. skip_commit(bool): If true, the install will skip committing to the device. CLI Example: .. code-block:: bash salt '*' panos.install_antivirus 8.0.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/panos.py#L1382-L1427
[ "def _get_job_results(query=None):\n '''\n Executes a query that requires a job for completion. This function will wait for the job to complete\n and return the results.\n '''\n if not query:\n raise CommandExecutionError(\"Query parameters cannot be empty.\")\n\n response = __proxy__['panos.call'](query)\n\n # If the response contains a job, we will wait for the results\n if 'result' in response and 'job' in response['result']:\n jid = response['result']['job']\n\n while get_job(jid)['result']['job']['status'] != 'FIN':\n time.sleep(5)\n\n return get_job(jid)\n else:\n return response\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Palo Alto compatibility to Salt :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix .. versionadded:: 2018.3.0 Configuration ============= This module accepts connection configuration details either as parameters, or as configuration settings in pillar as a Salt proxy. Options passed into opts will be ignored if options are passed into pillar. .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` About ===== This execution module was designed to handle connections to a Palo Alto based firewall. This module adds support to send connections directly to the device through the XML API or through a brokered connection to Panorama. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import Salt Libs from salt.exceptions import CommandExecutionError import salt.proxy.panos import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'panos' def __virtual__(): ''' Will load for the panos proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'panos': return __virtualname__ except KeyError: pass return False, 'The panos execution module can only be loaded for panos proxy minions.' def _get_job_results(query=None): ''' Executes a query that requires a job for completion. This function will wait for the job to complete and return the results. ''' if not query: raise CommandExecutionError("Query parameters cannot be empty.") response = __proxy__['panos.call'](query) # If the response contains a job, we will wait for the results if 'result' in response and 'job' in response['result']: jid = response['result']['job'] while get_job(jid)['result']['job']['status'] != 'FIN': time.sleep(5) return get_job(jid) else: return response def add_config_lock(): ''' Prevent other users from changing configuration until the lock is released. CLI Example: .. code-block:: bash salt '*' panos.add_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><add></add></config-lock></request>'} return __proxy__['panos.call'](query) def check_antivirus(): ''' Get anti-virus information from PaloAlto Networks server CLI Example: .. code-block:: bash salt '*' panos.check_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><check></check></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def check_software(): ''' Get software information from PaloAlto Networks server. CLI Example: .. code-block:: bash salt '*' panos.check_software ''' query = {'type': 'op', 'cmd': '<request><system><software><check></check></software></system></request>'} return __proxy__['panos.call'](query) def clear_commit_tasks(): ''' Clear all commit tasks. CLI Example: .. code-block:: bash salt '*' panos.clear_commit_tasks ''' query = {'type': 'op', 'cmd': '<request><clear-commit-tasks></clear-commit-tasks></request>'} return __proxy__['panos.call'](query) def commit(): ''' Commits the candidate configuration to the running configuration. CLI Example: .. code-block:: bash salt '*' panos.commit ''' query = {'type': 'commit', 'cmd': '<commit></commit>'} return _get_job_results(query) def deactivate_license(key_name=None): ''' Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<request><license><deactivate><key><features><member>{0}</member></features>' '</key></deactivate></license></request>'.format(key_name)} return __proxy__['panos.call'](query) def delete_license(key_name=None): ''' Remove license keys on disk. key_name(str): The file name of the license key to be deleted. CLI Example: .. code-block:: bash salt '*' panos.delete_license key_name=License_File_Name.key ''' if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<delete><license><key>{0}</key></license></delete>'.format(key_name)} return __proxy__['panos.call'](query) def download_antivirus(): ''' Download the most recent anti-virus package. CLI Example: .. code-block:: bash salt '*' panos.download_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><download>' '<latest></latest></download></upgrade></anti-virus></request>'} return _get_job_results(query) def download_software_file(filename=None, synch=False): ''' Download software packages by filename. Args: filename(str): The filename of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_file PanOS_5000-8.0.0 salt '*' panos.download_software_file PanOS_5000-8.0.0 True ''' if not filename: raise CommandExecutionError("Filename option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<file>{0}</file></download></software></system></request>'.format(filename)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<file>{0}</file></download></software></system></request>'.format(filename)} return _get_job_results(query) def download_software_version(version=None, synch=False): ''' Download software packages by version number. Args: version(str): The version of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_version 8.0.0 salt '*' panos.download_software_version 8.0.0 True ''' if not version: raise CommandExecutionError("Version option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<version>{0}</version></download></software></system></request>'.format(version)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<version>{0}</version></download></software></system></request>'.format(version)} return _get_job_results(query) def fetch_license(auth_code=None): ''' Get new license(s) using from the Palo Alto Network Server. auth_code The license authorization code. CLI Example: .. code-block:: bash salt '*' panos.fetch_license salt '*' panos.fetch_license auth_code=foobar ''' if not auth_code: query = {'type': 'op', 'cmd': '<request><license><fetch></fetch></license></request>'} else: query = {'type': 'op', 'cmd': '<request><license><fetch><auth-code>{0}</auth-code></fetch></license>' '</request>'.format(auth_code)} return __proxy__['panos.call'](query) def get_address(address=None, vsys='1'): ''' Get the candidate configuration for the specified get_address object. This will not return address objects that are marked as pre-defined objects. address(str): The name of the address object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address myhost salt '*' panos.get_address myhost 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address/entry[@name=\'{1}\']'.format(vsys, address)} return __proxy__['panos.call'](query) def get_address_group(addressgroup=None, vsys='1'): ''' Get the candidate configuration for the specified address group. This will not return address groups that are marked as pre-defined objects. addressgroup(str): The name of the address group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address_group foobar salt '*' panos.get_address_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address-group/entry[@name=\'{1}\']'.format(vsys, addressgroup)} return __proxy__['panos.call'](query) def get_admins_active(): ''' Show active administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_active ''' query = {'type': 'op', 'cmd': '<show><admins></admins></show>'} return __proxy__['panos.call'](query) def get_admins_all(): ''' Show all administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_all ''' query = {'type': 'op', 'cmd': '<show><admins><all></all></admins></show>'} return __proxy__['panos.call'](query) def get_antivirus_info(): ''' Show information about available anti-virus packages. CLI Example: .. code-block:: bash salt '*' panos.get_antivirus_info ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><info></info></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def get_arp(): ''' Show ARP information. CLI Example: .. code-block:: bash salt '*' panos.get_arp ''' query = {'type': 'op', 'cmd': '<show><arp><entry name = \'all\'/></arp></show>'} return __proxy__['panos.call'](query) def get_cli_idle_timeout(): ''' Show timeout information for this administrative session. CLI Example: .. code-block:: bash salt '*' panos.get_cli_idle_timeout ''' query = {'type': 'op', 'cmd': '<show><cli><idle-timeout></idle-timeout></cli></show>'} return __proxy__['panos.call'](query) def get_cli_permissions(): ''' Show cli administrative permissions. CLI Example: .. code-block:: bash salt '*' panos.get_cli_permissions ''' query = {'type': 'op', 'cmd': '<show><cli><permissions></permissions></cli></show>'} return __proxy__['panos.call'](query) def get_disk_usage(): ''' Report filesystem disk space usage. CLI Example: .. code-block:: bash salt '*' panos.get_disk_usage ''' query = {'type': 'op', 'cmd': '<show><system><disk-space></disk-space></system></show>'} return __proxy__['panos.call'](query) def get_dns_server_config(): ''' Get the DNS server configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_dns_server_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/dns-setting/servers'} return __proxy__['panos.call'](query) def get_domain_config(): ''' Get the domain name configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_domain_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/domain'} return __proxy__['panos.call'](query) def get_dos_blocks(): ''' Show the DoS block-ip table. CLI Example: .. code-block:: bash salt '*' panos.get_dos_blocks ''' query = {'type': 'op', 'cmd': '<show><dos-block-table><all></all></dos-block-table></show>'} return __proxy__['panos.call'](query) def get_fqdn_cache(): ''' Print FQDNs used in rules and their IPs. CLI Example: .. code-block:: bash salt '*' panos.get_fqdn_cache ''' query = {'type': 'op', 'cmd': '<request><system><fqdn><show></show></fqdn></system></request>'} return __proxy__['panos.call'](query) def get_ha_config(): ''' Get the high availability configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ha_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/high-availability'} return __proxy__['panos.call'](query) def get_ha_link(): ''' Show high-availability link-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_link ''' query = {'type': 'op', 'cmd': '<show><high-availability><link-monitoring></link-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_path(): ''' Show high-availability path-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_path ''' query = {'type': 'op', 'cmd': '<show><high-availability><path-monitoring></path-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_state(): ''' Show high-availability state information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_state ''' query = {'type': 'op', 'cmd': '<show><high-availability><state></state></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_transitions(): ''' Show high-availability transition statistic information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_transitions ''' query = {'type': 'op', 'cmd': '<show><high-availability><transitions></transitions></high-availability></show>'} return __proxy__['panos.call'](query) def get_hostname(): ''' Get the hostname of the device. CLI Example: .. code-block:: bash salt '*' panos.get_hostname ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/hostname'} return __proxy__['panos.call'](query) def get_interface_counters(name='all'): ''' Get the counter statistics for interfaces. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interface_counters salt '*' panos.get_interface_counters ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><counter><interface>{0}</interface></counter></show>'.format(name)} return __proxy__['panos.call'](query) def get_interfaces(name='all'): ''' Show interface information. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interfaces salt '*' panos.get_interfaces ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><interface>{0}</interface></show>'.format(name)} return __proxy__['panos.call'](query) def get_job(jid=None): ''' List all a single job by ID. jid The ID of the job to retrieve. CLI Example: .. code-block:: bash salt '*' panos.get_job jid=15 ''' if not jid: raise CommandExecutionError("ID option must not be none.") query = {'type': 'op', 'cmd': '<show><jobs><id>{0}</id></jobs></show>'.format(jid)} return __proxy__['panos.call'](query) def get_jobs(state='all'): ''' List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending ''' if state.lower() == 'all': query = {'type': 'op', 'cmd': '<show><jobs><all></all></jobs></show>'} elif state.lower() == 'pending': query = {'type': 'op', 'cmd': '<show><jobs><pending></pending></jobs></show>'} elif state.lower() == 'processed': query = {'type': 'op', 'cmd': '<show><jobs><processed></processed></jobs></show>'} else: raise CommandExecutionError("The state parameter must be all, pending, or processed.") return __proxy__['panos.call'](query) def get_lacp(): ''' Show LACP state. CLI Example: .. code-block:: bash salt '*' panos.get_lacp ''' query = {'type': 'op', 'cmd': '<show><lacp><aggregate-ethernet>all</aggregate-ethernet></lacp></show>'} return __proxy__['panos.call'](query) def get_license_info(): ''' Show information about owned license(s). CLI Example: .. code-block:: bash salt '*' panos.get_license_info ''' query = {'type': 'op', 'cmd': '<request><license><info></info></license></request>'} return __proxy__['panos.call'](query) def get_license_tokens(): ''' Show license token files for manual license deactivation. CLI Example: .. code-block:: bash salt '*' panos.get_license_tokens ''' query = {'type': 'op', 'cmd': '<show><license-token-files></license-token-files></show>'} return __proxy__['panos.call'](query) def get_lldp_config(): ''' Show lldp config for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_config ''' query = {'type': 'op', 'cmd': '<show><lldp><config>all</config></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_counters(): ''' Show lldp counters for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_counters ''' query = {'type': 'op', 'cmd': '<show><lldp><counters>all</counters></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_local(): ''' Show lldp local info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_local ''' query = {'type': 'op', 'cmd': '<show><lldp><local>all</local></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_neighbors(): ''' Show lldp neighbors info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_neighbors ''' query = {'type': 'op', 'cmd': '<show><lldp><neighbors>all</neighbors></lldp></show>'} return __proxy__['panos.call'](query) def get_local_admins(): ''' Show all local administrator accounts. CLI Example: .. code-block:: bash salt '*' panos.get_local_admins ''' admin_list = get_users_config() response = [] if 'users' not in admin_list['result']: return response if isinstance(admin_list['result']['users']['entry'], list): for entry in admin_list['result']['users']['entry']: response.append(entry['name']) else: response.append(admin_list['result']['users']['entry']['name']) return response def get_logdb_quota(): ''' Report the logdb quotas. CLI Example: .. code-block:: bash salt '*' panos.get_logdb_quota ''' query = {'type': 'op', 'cmd': '<show><system><logdb-quota></logdb-quota></system></show>'} return __proxy__['panos.call'](query) def get_master_key(): ''' Get the master key properties. CLI Example: .. code-block:: bash salt '*' panos.get_master_key ''' query = {'type': 'op', 'cmd': '<show><system><masterkey-properties></masterkey-properties></system></show>'} return __proxy__['panos.call'](query) def get_ntp_config(): ''' Get the NTP configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers'} return __proxy__['panos.call'](query) def get_ntp_servers(): ''' Get list of configured NTP servers. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_servers ''' query = {'type': 'op', 'cmd': '<show><ntp></ntp></show>'} return __proxy__['panos.call'](query) def get_operational_mode(): ''' Show device operational mode setting. CLI Example: .. code-block:: bash salt '*' panos.get_operational_mode ''' query = {'type': 'op', 'cmd': '<show><operational-mode></operational-mode></show>'} return __proxy__['panos.call'](query) def get_panorama_status(): ''' Show panorama connection status. CLI Example: .. code-block:: bash salt '*' panos.get_panorama_status ''' query = {'type': 'op', 'cmd': '<show><panorama-status></panorama-status></show>'} return __proxy__['panos.call'](query) def get_permitted_ips(): ''' Get the IP addresses that are permitted to establish management connections to the device. CLI Example: .. code-block:: bash salt '*' panos.get_permitted_ips ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip'} return __proxy__['panos.call'](query) def get_platform(): ''' Get the platform model information and limitations. CLI Example: .. code-block:: bash salt '*' panos.get_platform ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/platform'} return __proxy__['panos.call'](query) def get_predefined_application(application=None): ''' Get the configuration for the specified pre-defined application object. This will only return pre-defined application objects. application(str): The name of the pre-defined application object. CLI Example: .. code-block:: bash salt '*' panos.get_predefined_application saltstack ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/predefined/application/entry[@name=\'{0}\']'.format(application)} return __proxy__['panos.call'](query) def get_security_rule(rulename=None, vsys='1'): ''' Get the candidate configuration for the specified security rule. rulename(str): The name of the security rule. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_security_rule rule01 salt '*' panos.get_security_rule rule01 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'rulebase/security/rules/entry[@name=\'{1}\']'.format(vsys, rulename)} return __proxy__['panos.call'](query) def get_service(service=None, vsys='1'): ''' Get the candidate configuration for the specified service object. This will not return services that are marked as pre-defined objects. service(str): The name of the service object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service tcp-443 salt '*' panos.get_service tcp-443 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service/entry[@name=\'{1}\']'.format(vsys, service)} return __proxy__['panos.call'](query) def get_service_group(servicegroup=None, vsys='1'): ''' Get the candidate configuration for the specified service group. This will not return service groups that are marked as pre-defined objects. servicegroup(str): The name of the service group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service_group foobar salt '*' panos.get_service_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service-group/entry[@name=\'{1}\']'.format(vsys, servicegroup)} return __proxy__['panos.call'](query) def get_session_info(): ''' Show device session statistics. CLI Example: .. code-block:: bash salt '*' panos.get_session_info ''' query = {'type': 'op', 'cmd': '<show><session><info></info></session></show>'} return __proxy__['panos.call'](query) def get_snmp_config(): ''' Get the SNMP configuration from the device. CLI Example: .. code-block:: bash salt '*' panos.get_snmp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/snmp-setting'} return __proxy__['panos.call'](query) def get_software_info(): ''' Show information about available software packages. CLI Example: .. code-block:: bash salt '*' panos.get_software_info ''' query = {'type': 'op', 'cmd': '<request><system><software><info></info></software></system></request>'} return __proxy__['panos.call'](query) def get_system_date_time(): ''' Get the system date/time. CLI Example: .. code-block:: bash salt '*' panos.get_system_date_time ''' query = {'type': 'op', 'cmd': '<show><clock></clock></show>'} return __proxy__['panos.call'](query) def get_system_files(): ''' List important files in the system. CLI Example: .. code-block:: bash salt '*' panos.get_system_files ''' query = {'type': 'op', 'cmd': '<show><system><files></files></system></show>'} return __proxy__['panos.call'](query) def get_system_info(): ''' Get the system information. CLI Example: .. code-block:: bash salt '*' panos.get_system_info ''' query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'} return __proxy__['panos.call'](query) def get_system_services(): ''' Show system services. CLI Example: .. code-block:: bash salt '*' panos.get_system_services ''' query = {'type': 'op', 'cmd': '<show><system><services></services></system></show>'} return __proxy__['panos.call'](query) def get_system_state(mask=None): ''' Show the system state variables. mask Filters by a subtree or a wildcard. CLI Example: .. code-block:: bash salt '*' panos.get_system_state salt '*' panos.get_system_state mask=cfg.ha.config.enabled salt '*' panos.get_system_state mask=cfg.ha.* ''' if mask: query = {'type': 'op', 'cmd': '<show><system><state><filter>{0}</filter></state></system></show>'.format(mask)} else: query = {'type': 'op', 'cmd': '<show><system><state></state></system></show>'} return __proxy__['panos.call'](query) def get_uncommitted_changes(): ''' Retrieve a list of all uncommitted changes on the device. Requires PANOS version 8.0.0 or greater. CLI Example: .. code-block:: bash salt '*' panos.get_uncommitted_changes ''' _required_version = '8.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) query = {'type': 'op', 'cmd': '<show><config><list><changes></changes></list></config></show>'} return __proxy__['panos.call'](query) def get_users_config(): ''' Get the local administrative user account configuration. CLI Example: .. code-block:: bash salt '*' panos.get_users_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/mgt-config/users'} return __proxy__['panos.call'](query) def get_vlans(): ''' Show all VLAN information. CLI Example: .. code-block:: bash salt '*' panos.get_vlans ''' query = {'type': 'op', 'cmd': '<show><vlan>all</vlan></show>'} return __proxy__['panos.call'](query) def get_xpath(xpath=''): ''' Retrieve a specified xpath from the candidate configuration. xpath(str): The specified xpath in the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_xpath /config/shared/service ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} return __proxy__['panos.call'](query) def get_zone(zone='', vsys='1'): ''' Get the candidate configuration for the specified zone. zone(str): The name of the zone. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zone trust salt '*' panos.get_zone trust 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone/entry[@name=\'{1}\']'.format(vsys, zone)} return __proxy__['panos.call'](query) def get_zones(vsys='1'): ''' Get all the zones in the candidate configuration. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zones salt '*' panos.get_zones 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone'.format(vsys)} return __proxy__['panos.call'](query) def install_license(): ''' Install the license key(s). CLI Example: .. code-block:: bash salt '*' panos.install_license ''' query = {'type': 'op', 'cmd': '<request><license><install></install></license></request>'} return __proxy__['panos.call'](query) def install_software(version=None): ''' Upgrade to a software package by version. Args: version(str): The version of the PANOS file to install. CLI Example: .. code-block:: bash salt '*' panos.install_license 8.0.0 ''' if not version: raise CommandExecutionError("Version option must not be none.") query = {'type': 'op', 'cmd': '<request><system><software><install>' '<version>{0}</version></install></software></system></request>'.format(version)} return _get_job_results(query) def reboot(): ''' Reboot a running system. CLI Example: .. code-block:: bash salt '*' panos.reboot ''' query = {'type': 'op', 'cmd': '<request><restart><system></system></restart></request>'} return __proxy__['panos.call'](query) def refresh_fqdn_cache(force=False): ''' Force refreshes all FQDNs used in rules. force Forces all fqdn refresh CLI Example: .. code-block:: bash salt '*' panos.refresh_fqdn_cache salt '*' panos.refresh_fqdn_cache force=True ''' if not isinstance(force, bool): raise CommandExecutionError("Force option must be boolean.") if force: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh><force>yes</force></refresh></fqdn></system></request>'} else: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh></refresh></fqdn></system></request>'} return __proxy__['panos.call'](query) def remove_config_lock(): ''' Release config lock previously held. CLI Example: .. code-block:: bash salt '*' panos.remove_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><remove></remove></config-lock></request>'} return __proxy__['panos.call'](query) def resolve_address(address=None, vsys=None): ''' Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com salt '*' panos.resolve_address foo.bar.com vsys=2 ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not address: raise CommandExecutionError("FQDN to resolve must be provided as address.") if not vsys: query = {'type': 'op', 'cmd': '<request><resolve><address>{0}</address></resolve></request>'.format(address)} else: query = {'type': 'op', 'cmd': '<request><resolve><vsys>{0}</vsys><address>{1}</address></resolve>' '</request>'.format(vsys, address)} return __proxy__['panos.call'](query) def save_device_config(filename=None): ''' Save device configuration to a named file. filename The filename to save the configuration to. CLI Example: .. code-block:: bash salt '*' panos.save_device_config foo.xml ''' if not filename: raise CommandExecutionError("Filename must not be empty.") query = {'type': 'op', 'cmd': '<save><config><to>{0}</to></config></save>'.format(filename)} return __proxy__['panos.call'](query) def save_device_state(): ''' Save files needed to restore device to local disk. CLI Example: .. code-block:: bash salt '*' panos.save_device_state ''' query = {'type': 'op', 'cmd': '<save><device-state></device-state></save>'} return __proxy__['panos.call'](query) def set_authentication_profile(profile=None, deploy=False): ''' Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_authentication_profile foo salt '*' panos.set_authentication_profile foo deploy=True ''' if not profile: raise CommandExecutionError("Profile name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/' 'authentication-profile', 'element': '<authentication-profile>{0}</authentication-profile>'.format(profile)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_hostname(hostname=None, deploy=False): ''' Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True ''' if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system', 'element': '<hostname>{0}</hostname>'.format(hostname)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_icmp(enabled=True, deploy=False): ''' Enables or disables the ICMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_icmp salt '*' panos.set_management_icmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-icmp>{0}</disable-icmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_http(enabled=True, deploy=False): ''' Enables or disables the HTTP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_http salt '*' panos.set_management_http enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http>{0}</disable-http>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_https(enabled=True, deploy=False): ''' Enables or disables the HTTPS management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_https salt '*' panos.set_management_https enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-https>{0}</disable-https>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ocsp(enabled=True, deploy=False): ''' Enables or disables the HTTP OCSP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ocsp salt '*' panos.set_management_ocsp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http-ocsp>{0}</disable-http-ocsp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_snmp(enabled=True, deploy=False): ''' Enables or disables the SNMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_snmp salt '*' panos.set_management_snmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-snmp>{0}</disable-snmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ssh(enabled=True, deploy=False): ''' Enables or disables the SSH management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ssh salt '*' panos.set_management_ssh enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-ssh>{0}</disable-ssh>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_telnet(enabled=True, deploy=False): ''' Enables or disables the Telnet management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_telnet salt '*' panos.set_management_telnet enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-telnet>{0}</disable-telnet>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_ntp_authentication(target=None, authentication_type=None, key_id=None, authentication_key=None, algorithm=None, deploy=False): ''' Set the NTP authentication of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: target(str): Determines the target of the authentication. Valid options are primary, secondary, or both. authentication_type(str): The authentication type to be used. Valid options are symmetric, autokey, and none. key_id(int): The NTP authentication key ID. authentication_key(str): The authentication key. algorithm(str): The algorithm type to be used for a symmetric key. Valid options are md5 and sha1. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_authentication target=both authentication_type=autokey salt '*' ntp.set_authentication target=primary authentication_type=none salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 deploy=True ''' ret = {} if target not in ['primary', 'secondary', 'both']: raise salt.exceptions.CommandExecutionError("Target option must be primary, secondary, or both.") if authentication_type not in ['symmetric', 'autokey', 'none']: raise salt.exceptions.CommandExecutionError("Type option must be symmetric, autokey, or both.") if authentication_type == "symmetric" and not authentication_key: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, authentication_key must be " "provided.") if authentication_type == "symmetric" and not key_id: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, key_id must be provided.") if authentication_type == "symmetric" and algorithm not in ['md5', 'sha1']: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, algorithm must be md5 or " "sha1.") if authentication_type == 'symmetric': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'autokey': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'none': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): ''' Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server(str): The secondary NTP server IP address or FQDN. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_servers 0.pool.ntp.org 1.pool.ntp.org salt '*' ntp.set_servers primary_server=0.pool.ntp.org secondary_server=1.pool.ntp.org salt '*' ntp.ser_servers 0.pool.ntp.org 1.pool.ntp.org deploy=True ''' ret = {} if primary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(primary_server)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if secondary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(secondary_server)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_permitted_ip(address=None, deploy=False): ''' Add an IPv4 address or network to the permitted IP list. CLI Example: Args: address (str): The IPv4 address or network to allow access to add to the Palo Alto device. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_permitted_ip 10.0.0.1 salt '*' panos.set_permitted_ip 10.0.0.0/24 salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True ''' if not address: raise CommandExecutionError("Address option must not be empty.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip', 'element': '<entry name=\'{0}\'></entry>'.format(address)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_timezone UTC salt '*' panos.set_timezone UTC deploy=True ''' if not tz: raise CommandExecutionError("Timezone name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/timezone', 'element': '<timezone>{0}</timezone>'.format(tz)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def shutdown(): ''' Shutdown a running system. CLI Example: .. code-block:: bash salt '*' panos.shutdown ''' query = {'type': 'op', 'cmd': '<request><shutdown><system></system></shutdown></request>'} return __proxy__['panos.call'](query) def test_fib_route(ip=None, vr='vr1'): ''' Perform a route lookup within active route table (fib). ip (str): The destination IP address to test. vr (str): The name of the virtual router to test. CLI Example: .. code-block:: bash salt '*' panos.test_fib_route 4.2.2.2 salt '*' panos.test_fib_route 4.2.2.2 my-vr ''' xpath = "<test><routing><fib-lookup>" if ip: xpath += "<ip>{0}</ip>".format(ip) if vr: xpath += "<virtual-router>{0}</virtual-router>".format(vr) xpath += "</fib-lookup></routing></test>" query = {'type': 'op', 'cmd': xpath} return __proxy__['panos.call'](query) def test_security_policy(sourcezone=None, destinationzone=None, source=None, destination=None, protocol=None, port=None, application=None, category=None, vsys='1', allrules=False): ''' Checks which security policy as connection will match on the device. sourcezone (str): The source zone matched against the connection. destinationzone (str): The destination zone matched against the connection. source (str): The source address. This must be a single IP address. destination (str): The destination address. This must be a single IP address. protocol (int): The protocol number for the connection. This is the numerical representation of the protocol. port (int): The port number for the connection. application (str): The application that should be matched. category (str): The category that should be matched. vsys (int): The numerical representation of the VSYS ID. allrules (bool): Show all potential match rules until first allow rule. CLI Example: .. code-block:: bash salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 vsys=2 ''' xpath = "<test><security-policy-match>" if sourcezone: xpath += "<from>{0}</from>".format(sourcezone) if destinationzone: xpath += "<to>{0}</to>".format(destinationzone) if source: xpath += "<source>{0}</source>".format(source) if destination: xpath += "<destination>{0}</destination>".format(destination) if protocol: xpath += "<protocol>{0}</protocol>".format(protocol) if port: xpath += "<destination-port>{0}</destination-port>".format(port) if application: xpath += "<application>{0}</application>".format(application) if category: xpath += "<category>{0}</category>".format(category) if allrules: xpath += "<show-all>yes</show-all>" xpath += "</security-policy-match></test>" query = {'type': 'op', 'vsys': "vsys{0}".format(vsys), 'cmd': xpath} return __proxy__['panos.call'](query) def unlock_admin(username=None): ''' Unlocks a locked administrator account. username Username of the administrator. CLI Example: .. code-block:: bash salt '*' panos.unlock_admin username=bob ''' if not username: raise CommandExecutionError("Username option must not be none.") query = {'type': 'op', 'cmd': '<set><management-server><unlock><admin>{0}</admin></unlock></management-server>' '</set>'.format(username)} return __proxy__['panos.call'](query)
saltstack/salt
salt/modules/panos.py
refresh_fqdn_cache
python
def refresh_fqdn_cache(force=False): ''' Force refreshes all FQDNs used in rules. force Forces all fqdn refresh CLI Example: .. code-block:: bash salt '*' panos.refresh_fqdn_cache salt '*' panos.refresh_fqdn_cache force=True ''' if not isinstance(force, bool): raise CommandExecutionError("Force option must be boolean.") if force: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh><force>yes</force></refresh></fqdn></system></request>'} else: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh></refresh></fqdn></system></request>'} return __proxy__['panos.call'](query)
Force refreshes all FQDNs used in rules. force Forces all fqdn refresh CLI Example: .. code-block:: bash salt '*' panos.refresh_fqdn_cache salt '*' panos.refresh_fqdn_cache force=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/panos.py#L1486-L1510
null
# -*- coding: utf-8 -*- ''' Module to provide Palo Alto compatibility to Salt :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix .. versionadded:: 2018.3.0 Configuration ============= This module accepts connection configuration details either as parameters, or as configuration settings in pillar as a Salt proxy. Options passed into opts will be ignored if options are passed into pillar. .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` About ===== This execution module was designed to handle connections to a Palo Alto based firewall. This module adds support to send connections directly to the device through the XML API or through a brokered connection to Panorama. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import Salt Libs from salt.exceptions import CommandExecutionError import salt.proxy.panos import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'panos' def __virtual__(): ''' Will load for the panos proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'panos': return __virtualname__ except KeyError: pass return False, 'The panos execution module can only be loaded for panos proxy minions.' def _get_job_results(query=None): ''' Executes a query that requires a job for completion. This function will wait for the job to complete and return the results. ''' if not query: raise CommandExecutionError("Query parameters cannot be empty.") response = __proxy__['panos.call'](query) # If the response contains a job, we will wait for the results if 'result' in response and 'job' in response['result']: jid = response['result']['job'] while get_job(jid)['result']['job']['status'] != 'FIN': time.sleep(5) return get_job(jid) else: return response def add_config_lock(): ''' Prevent other users from changing configuration until the lock is released. CLI Example: .. code-block:: bash salt '*' panos.add_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><add></add></config-lock></request>'} return __proxy__['panos.call'](query) def check_antivirus(): ''' Get anti-virus information from PaloAlto Networks server CLI Example: .. code-block:: bash salt '*' panos.check_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><check></check></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def check_software(): ''' Get software information from PaloAlto Networks server. CLI Example: .. code-block:: bash salt '*' panos.check_software ''' query = {'type': 'op', 'cmd': '<request><system><software><check></check></software></system></request>'} return __proxy__['panos.call'](query) def clear_commit_tasks(): ''' Clear all commit tasks. CLI Example: .. code-block:: bash salt '*' panos.clear_commit_tasks ''' query = {'type': 'op', 'cmd': '<request><clear-commit-tasks></clear-commit-tasks></request>'} return __proxy__['panos.call'](query) def commit(): ''' Commits the candidate configuration to the running configuration. CLI Example: .. code-block:: bash salt '*' panos.commit ''' query = {'type': 'commit', 'cmd': '<commit></commit>'} return _get_job_results(query) def deactivate_license(key_name=None): ''' Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<request><license><deactivate><key><features><member>{0}</member></features>' '</key></deactivate></license></request>'.format(key_name)} return __proxy__['panos.call'](query) def delete_license(key_name=None): ''' Remove license keys on disk. key_name(str): The file name of the license key to be deleted. CLI Example: .. code-block:: bash salt '*' panos.delete_license key_name=License_File_Name.key ''' if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<delete><license><key>{0}</key></license></delete>'.format(key_name)} return __proxy__['panos.call'](query) def download_antivirus(): ''' Download the most recent anti-virus package. CLI Example: .. code-block:: bash salt '*' panos.download_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><download>' '<latest></latest></download></upgrade></anti-virus></request>'} return _get_job_results(query) def download_software_file(filename=None, synch=False): ''' Download software packages by filename. Args: filename(str): The filename of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_file PanOS_5000-8.0.0 salt '*' panos.download_software_file PanOS_5000-8.0.0 True ''' if not filename: raise CommandExecutionError("Filename option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<file>{0}</file></download></software></system></request>'.format(filename)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<file>{0}</file></download></software></system></request>'.format(filename)} return _get_job_results(query) def download_software_version(version=None, synch=False): ''' Download software packages by version number. Args: version(str): The version of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_version 8.0.0 salt '*' panos.download_software_version 8.0.0 True ''' if not version: raise CommandExecutionError("Version option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<version>{0}</version></download></software></system></request>'.format(version)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<version>{0}</version></download></software></system></request>'.format(version)} return _get_job_results(query) def fetch_license(auth_code=None): ''' Get new license(s) using from the Palo Alto Network Server. auth_code The license authorization code. CLI Example: .. code-block:: bash salt '*' panos.fetch_license salt '*' panos.fetch_license auth_code=foobar ''' if not auth_code: query = {'type': 'op', 'cmd': '<request><license><fetch></fetch></license></request>'} else: query = {'type': 'op', 'cmd': '<request><license><fetch><auth-code>{0}</auth-code></fetch></license>' '</request>'.format(auth_code)} return __proxy__['panos.call'](query) def get_address(address=None, vsys='1'): ''' Get the candidate configuration for the specified get_address object. This will not return address objects that are marked as pre-defined objects. address(str): The name of the address object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address myhost salt '*' panos.get_address myhost 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address/entry[@name=\'{1}\']'.format(vsys, address)} return __proxy__['panos.call'](query) def get_address_group(addressgroup=None, vsys='1'): ''' Get the candidate configuration for the specified address group. This will not return address groups that are marked as pre-defined objects. addressgroup(str): The name of the address group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address_group foobar salt '*' panos.get_address_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address-group/entry[@name=\'{1}\']'.format(vsys, addressgroup)} return __proxy__['panos.call'](query) def get_admins_active(): ''' Show active administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_active ''' query = {'type': 'op', 'cmd': '<show><admins></admins></show>'} return __proxy__['panos.call'](query) def get_admins_all(): ''' Show all administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_all ''' query = {'type': 'op', 'cmd': '<show><admins><all></all></admins></show>'} return __proxy__['panos.call'](query) def get_antivirus_info(): ''' Show information about available anti-virus packages. CLI Example: .. code-block:: bash salt '*' panos.get_antivirus_info ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><info></info></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def get_arp(): ''' Show ARP information. CLI Example: .. code-block:: bash salt '*' panos.get_arp ''' query = {'type': 'op', 'cmd': '<show><arp><entry name = \'all\'/></arp></show>'} return __proxy__['panos.call'](query) def get_cli_idle_timeout(): ''' Show timeout information for this administrative session. CLI Example: .. code-block:: bash salt '*' panos.get_cli_idle_timeout ''' query = {'type': 'op', 'cmd': '<show><cli><idle-timeout></idle-timeout></cli></show>'} return __proxy__['panos.call'](query) def get_cli_permissions(): ''' Show cli administrative permissions. CLI Example: .. code-block:: bash salt '*' panos.get_cli_permissions ''' query = {'type': 'op', 'cmd': '<show><cli><permissions></permissions></cli></show>'} return __proxy__['panos.call'](query) def get_disk_usage(): ''' Report filesystem disk space usage. CLI Example: .. code-block:: bash salt '*' panos.get_disk_usage ''' query = {'type': 'op', 'cmd': '<show><system><disk-space></disk-space></system></show>'} return __proxy__['panos.call'](query) def get_dns_server_config(): ''' Get the DNS server configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_dns_server_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/dns-setting/servers'} return __proxy__['panos.call'](query) def get_domain_config(): ''' Get the domain name configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_domain_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/domain'} return __proxy__['panos.call'](query) def get_dos_blocks(): ''' Show the DoS block-ip table. CLI Example: .. code-block:: bash salt '*' panos.get_dos_blocks ''' query = {'type': 'op', 'cmd': '<show><dos-block-table><all></all></dos-block-table></show>'} return __proxy__['panos.call'](query) def get_fqdn_cache(): ''' Print FQDNs used in rules and their IPs. CLI Example: .. code-block:: bash salt '*' panos.get_fqdn_cache ''' query = {'type': 'op', 'cmd': '<request><system><fqdn><show></show></fqdn></system></request>'} return __proxy__['panos.call'](query) def get_ha_config(): ''' Get the high availability configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ha_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/high-availability'} return __proxy__['panos.call'](query) def get_ha_link(): ''' Show high-availability link-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_link ''' query = {'type': 'op', 'cmd': '<show><high-availability><link-monitoring></link-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_path(): ''' Show high-availability path-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_path ''' query = {'type': 'op', 'cmd': '<show><high-availability><path-monitoring></path-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_state(): ''' Show high-availability state information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_state ''' query = {'type': 'op', 'cmd': '<show><high-availability><state></state></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_transitions(): ''' Show high-availability transition statistic information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_transitions ''' query = {'type': 'op', 'cmd': '<show><high-availability><transitions></transitions></high-availability></show>'} return __proxy__['panos.call'](query) def get_hostname(): ''' Get the hostname of the device. CLI Example: .. code-block:: bash salt '*' panos.get_hostname ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/hostname'} return __proxy__['panos.call'](query) def get_interface_counters(name='all'): ''' Get the counter statistics for interfaces. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interface_counters salt '*' panos.get_interface_counters ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><counter><interface>{0}</interface></counter></show>'.format(name)} return __proxy__['panos.call'](query) def get_interfaces(name='all'): ''' Show interface information. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interfaces salt '*' panos.get_interfaces ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><interface>{0}</interface></show>'.format(name)} return __proxy__['panos.call'](query) def get_job(jid=None): ''' List all a single job by ID. jid The ID of the job to retrieve. CLI Example: .. code-block:: bash salt '*' panos.get_job jid=15 ''' if not jid: raise CommandExecutionError("ID option must not be none.") query = {'type': 'op', 'cmd': '<show><jobs><id>{0}</id></jobs></show>'.format(jid)} return __proxy__['panos.call'](query) def get_jobs(state='all'): ''' List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending ''' if state.lower() == 'all': query = {'type': 'op', 'cmd': '<show><jobs><all></all></jobs></show>'} elif state.lower() == 'pending': query = {'type': 'op', 'cmd': '<show><jobs><pending></pending></jobs></show>'} elif state.lower() == 'processed': query = {'type': 'op', 'cmd': '<show><jobs><processed></processed></jobs></show>'} else: raise CommandExecutionError("The state parameter must be all, pending, or processed.") return __proxy__['panos.call'](query) def get_lacp(): ''' Show LACP state. CLI Example: .. code-block:: bash salt '*' panos.get_lacp ''' query = {'type': 'op', 'cmd': '<show><lacp><aggregate-ethernet>all</aggregate-ethernet></lacp></show>'} return __proxy__['panos.call'](query) def get_license_info(): ''' Show information about owned license(s). CLI Example: .. code-block:: bash salt '*' panos.get_license_info ''' query = {'type': 'op', 'cmd': '<request><license><info></info></license></request>'} return __proxy__['panos.call'](query) def get_license_tokens(): ''' Show license token files for manual license deactivation. CLI Example: .. code-block:: bash salt '*' panos.get_license_tokens ''' query = {'type': 'op', 'cmd': '<show><license-token-files></license-token-files></show>'} return __proxy__['panos.call'](query) def get_lldp_config(): ''' Show lldp config for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_config ''' query = {'type': 'op', 'cmd': '<show><lldp><config>all</config></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_counters(): ''' Show lldp counters for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_counters ''' query = {'type': 'op', 'cmd': '<show><lldp><counters>all</counters></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_local(): ''' Show lldp local info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_local ''' query = {'type': 'op', 'cmd': '<show><lldp><local>all</local></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_neighbors(): ''' Show lldp neighbors info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_neighbors ''' query = {'type': 'op', 'cmd': '<show><lldp><neighbors>all</neighbors></lldp></show>'} return __proxy__['panos.call'](query) def get_local_admins(): ''' Show all local administrator accounts. CLI Example: .. code-block:: bash salt '*' panos.get_local_admins ''' admin_list = get_users_config() response = [] if 'users' not in admin_list['result']: return response if isinstance(admin_list['result']['users']['entry'], list): for entry in admin_list['result']['users']['entry']: response.append(entry['name']) else: response.append(admin_list['result']['users']['entry']['name']) return response def get_logdb_quota(): ''' Report the logdb quotas. CLI Example: .. code-block:: bash salt '*' panos.get_logdb_quota ''' query = {'type': 'op', 'cmd': '<show><system><logdb-quota></logdb-quota></system></show>'} return __proxy__['panos.call'](query) def get_master_key(): ''' Get the master key properties. CLI Example: .. code-block:: bash salt '*' panos.get_master_key ''' query = {'type': 'op', 'cmd': '<show><system><masterkey-properties></masterkey-properties></system></show>'} return __proxy__['panos.call'](query) def get_ntp_config(): ''' Get the NTP configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers'} return __proxy__['panos.call'](query) def get_ntp_servers(): ''' Get list of configured NTP servers. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_servers ''' query = {'type': 'op', 'cmd': '<show><ntp></ntp></show>'} return __proxy__['panos.call'](query) def get_operational_mode(): ''' Show device operational mode setting. CLI Example: .. code-block:: bash salt '*' panos.get_operational_mode ''' query = {'type': 'op', 'cmd': '<show><operational-mode></operational-mode></show>'} return __proxy__['panos.call'](query) def get_panorama_status(): ''' Show panorama connection status. CLI Example: .. code-block:: bash salt '*' panos.get_panorama_status ''' query = {'type': 'op', 'cmd': '<show><panorama-status></panorama-status></show>'} return __proxy__['panos.call'](query) def get_permitted_ips(): ''' Get the IP addresses that are permitted to establish management connections to the device. CLI Example: .. code-block:: bash salt '*' panos.get_permitted_ips ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip'} return __proxy__['panos.call'](query) def get_platform(): ''' Get the platform model information and limitations. CLI Example: .. code-block:: bash salt '*' panos.get_platform ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/platform'} return __proxy__['panos.call'](query) def get_predefined_application(application=None): ''' Get the configuration for the specified pre-defined application object. This will only return pre-defined application objects. application(str): The name of the pre-defined application object. CLI Example: .. code-block:: bash salt '*' panos.get_predefined_application saltstack ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/predefined/application/entry[@name=\'{0}\']'.format(application)} return __proxy__['panos.call'](query) def get_security_rule(rulename=None, vsys='1'): ''' Get the candidate configuration for the specified security rule. rulename(str): The name of the security rule. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_security_rule rule01 salt '*' panos.get_security_rule rule01 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'rulebase/security/rules/entry[@name=\'{1}\']'.format(vsys, rulename)} return __proxy__['panos.call'](query) def get_service(service=None, vsys='1'): ''' Get the candidate configuration for the specified service object. This will not return services that are marked as pre-defined objects. service(str): The name of the service object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service tcp-443 salt '*' panos.get_service tcp-443 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service/entry[@name=\'{1}\']'.format(vsys, service)} return __proxy__['panos.call'](query) def get_service_group(servicegroup=None, vsys='1'): ''' Get the candidate configuration for the specified service group. This will not return service groups that are marked as pre-defined objects. servicegroup(str): The name of the service group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service_group foobar salt '*' panos.get_service_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service-group/entry[@name=\'{1}\']'.format(vsys, servicegroup)} return __proxy__['panos.call'](query) def get_session_info(): ''' Show device session statistics. CLI Example: .. code-block:: bash salt '*' panos.get_session_info ''' query = {'type': 'op', 'cmd': '<show><session><info></info></session></show>'} return __proxy__['panos.call'](query) def get_snmp_config(): ''' Get the SNMP configuration from the device. CLI Example: .. code-block:: bash salt '*' panos.get_snmp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/snmp-setting'} return __proxy__['panos.call'](query) def get_software_info(): ''' Show information about available software packages. CLI Example: .. code-block:: bash salt '*' panos.get_software_info ''' query = {'type': 'op', 'cmd': '<request><system><software><info></info></software></system></request>'} return __proxy__['panos.call'](query) def get_system_date_time(): ''' Get the system date/time. CLI Example: .. code-block:: bash salt '*' panos.get_system_date_time ''' query = {'type': 'op', 'cmd': '<show><clock></clock></show>'} return __proxy__['panos.call'](query) def get_system_files(): ''' List important files in the system. CLI Example: .. code-block:: bash salt '*' panos.get_system_files ''' query = {'type': 'op', 'cmd': '<show><system><files></files></system></show>'} return __proxy__['panos.call'](query) def get_system_info(): ''' Get the system information. CLI Example: .. code-block:: bash salt '*' panos.get_system_info ''' query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'} return __proxy__['panos.call'](query) def get_system_services(): ''' Show system services. CLI Example: .. code-block:: bash salt '*' panos.get_system_services ''' query = {'type': 'op', 'cmd': '<show><system><services></services></system></show>'} return __proxy__['panos.call'](query) def get_system_state(mask=None): ''' Show the system state variables. mask Filters by a subtree or a wildcard. CLI Example: .. code-block:: bash salt '*' panos.get_system_state salt '*' panos.get_system_state mask=cfg.ha.config.enabled salt '*' panos.get_system_state mask=cfg.ha.* ''' if mask: query = {'type': 'op', 'cmd': '<show><system><state><filter>{0}</filter></state></system></show>'.format(mask)} else: query = {'type': 'op', 'cmd': '<show><system><state></state></system></show>'} return __proxy__['panos.call'](query) def get_uncommitted_changes(): ''' Retrieve a list of all uncommitted changes on the device. Requires PANOS version 8.0.0 or greater. CLI Example: .. code-block:: bash salt '*' panos.get_uncommitted_changes ''' _required_version = '8.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) query = {'type': 'op', 'cmd': '<show><config><list><changes></changes></list></config></show>'} return __proxy__['panos.call'](query) def get_users_config(): ''' Get the local administrative user account configuration. CLI Example: .. code-block:: bash salt '*' panos.get_users_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/mgt-config/users'} return __proxy__['panos.call'](query) def get_vlans(): ''' Show all VLAN information. CLI Example: .. code-block:: bash salt '*' panos.get_vlans ''' query = {'type': 'op', 'cmd': '<show><vlan>all</vlan></show>'} return __proxy__['panos.call'](query) def get_xpath(xpath=''): ''' Retrieve a specified xpath from the candidate configuration. xpath(str): The specified xpath in the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_xpath /config/shared/service ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} return __proxy__['panos.call'](query) def get_zone(zone='', vsys='1'): ''' Get the candidate configuration for the specified zone. zone(str): The name of the zone. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zone trust salt '*' panos.get_zone trust 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone/entry[@name=\'{1}\']'.format(vsys, zone)} return __proxy__['panos.call'](query) def get_zones(vsys='1'): ''' Get all the zones in the candidate configuration. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zones salt '*' panos.get_zones 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone'.format(vsys)} return __proxy__['panos.call'](query) def install_antivirus(version=None, latest=False, synch=False, skip_commit=False,): ''' Install anti-virus packages. Args: version(str): The version of the PANOS file to install. latest(bool): If true, the latest anti-virus file will be installed. The specified version option will be ignored. synch(bool): If true, the anti-virus will synch to the peer unit. skip_commit(bool): If true, the install will skip committing to the device. CLI Example: .. code-block:: bash salt '*' panos.install_antivirus 8.0.0 ''' if not version and latest is False: raise CommandExecutionError("Version option must not be none.") if synch is True: s = "yes" else: s = "no" if skip_commit is True: c = "yes" else: c = "no" if latest is True: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>latest</version></install></upgrade></anti-virus></request>'.format(c, s)} else: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>{2}</version></install></upgrade></anti-virus></request>'.format(c, s, version)} return _get_job_results(query) def install_license(): ''' Install the license key(s). CLI Example: .. code-block:: bash salt '*' panos.install_license ''' query = {'type': 'op', 'cmd': '<request><license><install></install></license></request>'} return __proxy__['panos.call'](query) def install_software(version=None): ''' Upgrade to a software package by version. Args: version(str): The version of the PANOS file to install. CLI Example: .. code-block:: bash salt '*' panos.install_license 8.0.0 ''' if not version: raise CommandExecutionError("Version option must not be none.") query = {'type': 'op', 'cmd': '<request><system><software><install>' '<version>{0}</version></install></software></system></request>'.format(version)} return _get_job_results(query) def reboot(): ''' Reboot a running system. CLI Example: .. code-block:: bash salt '*' panos.reboot ''' query = {'type': 'op', 'cmd': '<request><restart><system></system></restart></request>'} return __proxy__['panos.call'](query) def remove_config_lock(): ''' Release config lock previously held. CLI Example: .. code-block:: bash salt '*' panos.remove_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><remove></remove></config-lock></request>'} return __proxy__['panos.call'](query) def resolve_address(address=None, vsys=None): ''' Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com salt '*' panos.resolve_address foo.bar.com vsys=2 ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not address: raise CommandExecutionError("FQDN to resolve must be provided as address.") if not vsys: query = {'type': 'op', 'cmd': '<request><resolve><address>{0}</address></resolve></request>'.format(address)} else: query = {'type': 'op', 'cmd': '<request><resolve><vsys>{0}</vsys><address>{1}</address></resolve>' '</request>'.format(vsys, address)} return __proxy__['panos.call'](query) def save_device_config(filename=None): ''' Save device configuration to a named file. filename The filename to save the configuration to. CLI Example: .. code-block:: bash salt '*' panos.save_device_config foo.xml ''' if not filename: raise CommandExecutionError("Filename must not be empty.") query = {'type': 'op', 'cmd': '<save><config><to>{0}</to></config></save>'.format(filename)} return __proxy__['panos.call'](query) def save_device_state(): ''' Save files needed to restore device to local disk. CLI Example: .. code-block:: bash salt '*' panos.save_device_state ''' query = {'type': 'op', 'cmd': '<save><device-state></device-state></save>'} return __proxy__['panos.call'](query) def set_authentication_profile(profile=None, deploy=False): ''' Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_authentication_profile foo salt '*' panos.set_authentication_profile foo deploy=True ''' if not profile: raise CommandExecutionError("Profile name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/' 'authentication-profile', 'element': '<authentication-profile>{0}</authentication-profile>'.format(profile)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_hostname(hostname=None, deploy=False): ''' Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True ''' if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system', 'element': '<hostname>{0}</hostname>'.format(hostname)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_icmp(enabled=True, deploy=False): ''' Enables or disables the ICMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_icmp salt '*' panos.set_management_icmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-icmp>{0}</disable-icmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_http(enabled=True, deploy=False): ''' Enables or disables the HTTP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_http salt '*' panos.set_management_http enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http>{0}</disable-http>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_https(enabled=True, deploy=False): ''' Enables or disables the HTTPS management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_https salt '*' panos.set_management_https enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-https>{0}</disable-https>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ocsp(enabled=True, deploy=False): ''' Enables or disables the HTTP OCSP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ocsp salt '*' panos.set_management_ocsp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http-ocsp>{0}</disable-http-ocsp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_snmp(enabled=True, deploy=False): ''' Enables or disables the SNMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_snmp salt '*' panos.set_management_snmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-snmp>{0}</disable-snmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ssh(enabled=True, deploy=False): ''' Enables or disables the SSH management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ssh salt '*' panos.set_management_ssh enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-ssh>{0}</disable-ssh>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_telnet(enabled=True, deploy=False): ''' Enables or disables the Telnet management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_telnet salt '*' panos.set_management_telnet enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-telnet>{0}</disable-telnet>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_ntp_authentication(target=None, authentication_type=None, key_id=None, authentication_key=None, algorithm=None, deploy=False): ''' Set the NTP authentication of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: target(str): Determines the target of the authentication. Valid options are primary, secondary, or both. authentication_type(str): The authentication type to be used. Valid options are symmetric, autokey, and none. key_id(int): The NTP authentication key ID. authentication_key(str): The authentication key. algorithm(str): The algorithm type to be used for a symmetric key. Valid options are md5 and sha1. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_authentication target=both authentication_type=autokey salt '*' ntp.set_authentication target=primary authentication_type=none salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 deploy=True ''' ret = {} if target not in ['primary', 'secondary', 'both']: raise salt.exceptions.CommandExecutionError("Target option must be primary, secondary, or both.") if authentication_type not in ['symmetric', 'autokey', 'none']: raise salt.exceptions.CommandExecutionError("Type option must be symmetric, autokey, or both.") if authentication_type == "symmetric" and not authentication_key: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, authentication_key must be " "provided.") if authentication_type == "symmetric" and not key_id: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, key_id must be provided.") if authentication_type == "symmetric" and algorithm not in ['md5', 'sha1']: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, algorithm must be md5 or " "sha1.") if authentication_type == 'symmetric': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'autokey': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'none': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): ''' Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server(str): The secondary NTP server IP address or FQDN. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_servers 0.pool.ntp.org 1.pool.ntp.org salt '*' ntp.set_servers primary_server=0.pool.ntp.org secondary_server=1.pool.ntp.org salt '*' ntp.ser_servers 0.pool.ntp.org 1.pool.ntp.org deploy=True ''' ret = {} if primary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(primary_server)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if secondary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(secondary_server)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_permitted_ip(address=None, deploy=False): ''' Add an IPv4 address or network to the permitted IP list. CLI Example: Args: address (str): The IPv4 address or network to allow access to add to the Palo Alto device. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_permitted_ip 10.0.0.1 salt '*' panos.set_permitted_ip 10.0.0.0/24 salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True ''' if not address: raise CommandExecutionError("Address option must not be empty.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip', 'element': '<entry name=\'{0}\'></entry>'.format(address)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_timezone UTC salt '*' panos.set_timezone UTC deploy=True ''' if not tz: raise CommandExecutionError("Timezone name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/timezone', 'element': '<timezone>{0}</timezone>'.format(tz)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def shutdown(): ''' Shutdown a running system. CLI Example: .. code-block:: bash salt '*' panos.shutdown ''' query = {'type': 'op', 'cmd': '<request><shutdown><system></system></shutdown></request>'} return __proxy__['panos.call'](query) def test_fib_route(ip=None, vr='vr1'): ''' Perform a route lookup within active route table (fib). ip (str): The destination IP address to test. vr (str): The name of the virtual router to test. CLI Example: .. code-block:: bash salt '*' panos.test_fib_route 4.2.2.2 salt '*' panos.test_fib_route 4.2.2.2 my-vr ''' xpath = "<test><routing><fib-lookup>" if ip: xpath += "<ip>{0}</ip>".format(ip) if vr: xpath += "<virtual-router>{0}</virtual-router>".format(vr) xpath += "</fib-lookup></routing></test>" query = {'type': 'op', 'cmd': xpath} return __proxy__['panos.call'](query) def test_security_policy(sourcezone=None, destinationzone=None, source=None, destination=None, protocol=None, port=None, application=None, category=None, vsys='1', allrules=False): ''' Checks which security policy as connection will match on the device. sourcezone (str): The source zone matched against the connection. destinationzone (str): The destination zone matched against the connection. source (str): The source address. This must be a single IP address. destination (str): The destination address. This must be a single IP address. protocol (int): The protocol number for the connection. This is the numerical representation of the protocol. port (int): The port number for the connection. application (str): The application that should be matched. category (str): The category that should be matched. vsys (int): The numerical representation of the VSYS ID. allrules (bool): Show all potential match rules until first allow rule. CLI Example: .. code-block:: bash salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 vsys=2 ''' xpath = "<test><security-policy-match>" if sourcezone: xpath += "<from>{0}</from>".format(sourcezone) if destinationzone: xpath += "<to>{0}</to>".format(destinationzone) if source: xpath += "<source>{0}</source>".format(source) if destination: xpath += "<destination>{0}</destination>".format(destination) if protocol: xpath += "<protocol>{0}</protocol>".format(protocol) if port: xpath += "<destination-port>{0}</destination-port>".format(port) if application: xpath += "<application>{0}</application>".format(application) if category: xpath += "<category>{0}</category>".format(category) if allrules: xpath += "<show-all>yes</show-all>" xpath += "</security-policy-match></test>" query = {'type': 'op', 'vsys': "vsys{0}".format(vsys), 'cmd': xpath} return __proxy__['panos.call'](query) def unlock_admin(username=None): ''' Unlocks a locked administrator account. username Username of the administrator. CLI Example: .. code-block:: bash salt '*' panos.unlock_admin username=bob ''' if not username: raise CommandExecutionError("Username option must not be none.") query = {'type': 'op', 'cmd': '<set><management-server><unlock><admin>{0}</admin></unlock></management-server>' '</set>'.format(username)} return __proxy__['panos.call'](query)
saltstack/salt
salt/modules/panos.py
resolve_address
python
def resolve_address(address=None, vsys=None): ''' Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com salt '*' panos.resolve_address foo.bar.com vsys=2 ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not address: raise CommandExecutionError("FQDN to resolve must be provided as address.") if not vsys: query = {'type': 'op', 'cmd': '<request><resolve><address>{0}</address></resolve></request>'.format(address)} else: query = {'type': 'op', 'cmd': '<request><resolve><vsys>{0}</vsys><address>{1}</address></resolve>' '</request>'.format(vsys, address)} return __proxy__['panos.call'](query)
Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com salt '*' panos.resolve_address foo.bar.com vsys=2
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/panos.py#L1529-L1563
null
# -*- coding: utf-8 -*- ''' Module to provide Palo Alto compatibility to Salt :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix .. versionadded:: 2018.3.0 Configuration ============= This module accepts connection configuration details either as parameters, or as configuration settings in pillar as a Salt proxy. Options passed into opts will be ignored if options are passed into pillar. .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` About ===== This execution module was designed to handle connections to a Palo Alto based firewall. This module adds support to send connections directly to the device through the XML API or through a brokered connection to Panorama. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import Salt Libs from salt.exceptions import CommandExecutionError import salt.proxy.panos import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'panos' def __virtual__(): ''' Will load for the panos proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'panos': return __virtualname__ except KeyError: pass return False, 'The panos execution module can only be loaded for panos proxy minions.' def _get_job_results(query=None): ''' Executes a query that requires a job for completion. This function will wait for the job to complete and return the results. ''' if not query: raise CommandExecutionError("Query parameters cannot be empty.") response = __proxy__['panos.call'](query) # If the response contains a job, we will wait for the results if 'result' in response and 'job' in response['result']: jid = response['result']['job'] while get_job(jid)['result']['job']['status'] != 'FIN': time.sleep(5) return get_job(jid) else: return response def add_config_lock(): ''' Prevent other users from changing configuration until the lock is released. CLI Example: .. code-block:: bash salt '*' panos.add_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><add></add></config-lock></request>'} return __proxy__['panos.call'](query) def check_antivirus(): ''' Get anti-virus information from PaloAlto Networks server CLI Example: .. code-block:: bash salt '*' panos.check_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><check></check></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def check_software(): ''' Get software information from PaloAlto Networks server. CLI Example: .. code-block:: bash salt '*' panos.check_software ''' query = {'type': 'op', 'cmd': '<request><system><software><check></check></software></system></request>'} return __proxy__['panos.call'](query) def clear_commit_tasks(): ''' Clear all commit tasks. CLI Example: .. code-block:: bash salt '*' panos.clear_commit_tasks ''' query = {'type': 'op', 'cmd': '<request><clear-commit-tasks></clear-commit-tasks></request>'} return __proxy__['panos.call'](query) def commit(): ''' Commits the candidate configuration to the running configuration. CLI Example: .. code-block:: bash salt '*' panos.commit ''' query = {'type': 'commit', 'cmd': '<commit></commit>'} return _get_job_results(query) def deactivate_license(key_name=None): ''' Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<request><license><deactivate><key><features><member>{0}</member></features>' '</key></deactivate></license></request>'.format(key_name)} return __proxy__['panos.call'](query) def delete_license(key_name=None): ''' Remove license keys on disk. key_name(str): The file name of the license key to be deleted. CLI Example: .. code-block:: bash salt '*' panos.delete_license key_name=License_File_Name.key ''' if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<delete><license><key>{0}</key></license></delete>'.format(key_name)} return __proxy__['panos.call'](query) def download_antivirus(): ''' Download the most recent anti-virus package. CLI Example: .. code-block:: bash salt '*' panos.download_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><download>' '<latest></latest></download></upgrade></anti-virus></request>'} return _get_job_results(query) def download_software_file(filename=None, synch=False): ''' Download software packages by filename. Args: filename(str): The filename of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_file PanOS_5000-8.0.0 salt '*' panos.download_software_file PanOS_5000-8.0.0 True ''' if not filename: raise CommandExecutionError("Filename option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<file>{0}</file></download></software></system></request>'.format(filename)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<file>{0}</file></download></software></system></request>'.format(filename)} return _get_job_results(query) def download_software_version(version=None, synch=False): ''' Download software packages by version number. Args: version(str): The version of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_version 8.0.0 salt '*' panos.download_software_version 8.0.0 True ''' if not version: raise CommandExecutionError("Version option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<version>{0}</version></download></software></system></request>'.format(version)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<version>{0}</version></download></software></system></request>'.format(version)} return _get_job_results(query) def fetch_license(auth_code=None): ''' Get new license(s) using from the Palo Alto Network Server. auth_code The license authorization code. CLI Example: .. code-block:: bash salt '*' panos.fetch_license salt '*' panos.fetch_license auth_code=foobar ''' if not auth_code: query = {'type': 'op', 'cmd': '<request><license><fetch></fetch></license></request>'} else: query = {'type': 'op', 'cmd': '<request><license><fetch><auth-code>{0}</auth-code></fetch></license>' '</request>'.format(auth_code)} return __proxy__['panos.call'](query) def get_address(address=None, vsys='1'): ''' Get the candidate configuration for the specified get_address object. This will not return address objects that are marked as pre-defined objects. address(str): The name of the address object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address myhost salt '*' panos.get_address myhost 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address/entry[@name=\'{1}\']'.format(vsys, address)} return __proxy__['panos.call'](query) def get_address_group(addressgroup=None, vsys='1'): ''' Get the candidate configuration for the specified address group. This will not return address groups that are marked as pre-defined objects. addressgroup(str): The name of the address group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address_group foobar salt '*' panos.get_address_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address-group/entry[@name=\'{1}\']'.format(vsys, addressgroup)} return __proxy__['panos.call'](query) def get_admins_active(): ''' Show active administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_active ''' query = {'type': 'op', 'cmd': '<show><admins></admins></show>'} return __proxy__['panos.call'](query) def get_admins_all(): ''' Show all administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_all ''' query = {'type': 'op', 'cmd': '<show><admins><all></all></admins></show>'} return __proxy__['panos.call'](query) def get_antivirus_info(): ''' Show information about available anti-virus packages. CLI Example: .. code-block:: bash salt '*' panos.get_antivirus_info ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><info></info></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def get_arp(): ''' Show ARP information. CLI Example: .. code-block:: bash salt '*' panos.get_arp ''' query = {'type': 'op', 'cmd': '<show><arp><entry name = \'all\'/></arp></show>'} return __proxy__['panos.call'](query) def get_cli_idle_timeout(): ''' Show timeout information for this administrative session. CLI Example: .. code-block:: bash salt '*' panos.get_cli_idle_timeout ''' query = {'type': 'op', 'cmd': '<show><cli><idle-timeout></idle-timeout></cli></show>'} return __proxy__['panos.call'](query) def get_cli_permissions(): ''' Show cli administrative permissions. CLI Example: .. code-block:: bash salt '*' panos.get_cli_permissions ''' query = {'type': 'op', 'cmd': '<show><cli><permissions></permissions></cli></show>'} return __proxy__['panos.call'](query) def get_disk_usage(): ''' Report filesystem disk space usage. CLI Example: .. code-block:: bash salt '*' panos.get_disk_usage ''' query = {'type': 'op', 'cmd': '<show><system><disk-space></disk-space></system></show>'} return __proxy__['panos.call'](query) def get_dns_server_config(): ''' Get the DNS server configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_dns_server_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/dns-setting/servers'} return __proxy__['panos.call'](query) def get_domain_config(): ''' Get the domain name configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_domain_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/domain'} return __proxy__['panos.call'](query) def get_dos_blocks(): ''' Show the DoS block-ip table. CLI Example: .. code-block:: bash salt '*' panos.get_dos_blocks ''' query = {'type': 'op', 'cmd': '<show><dos-block-table><all></all></dos-block-table></show>'} return __proxy__['panos.call'](query) def get_fqdn_cache(): ''' Print FQDNs used in rules and their IPs. CLI Example: .. code-block:: bash salt '*' panos.get_fqdn_cache ''' query = {'type': 'op', 'cmd': '<request><system><fqdn><show></show></fqdn></system></request>'} return __proxy__['panos.call'](query) def get_ha_config(): ''' Get the high availability configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ha_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/high-availability'} return __proxy__['panos.call'](query) def get_ha_link(): ''' Show high-availability link-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_link ''' query = {'type': 'op', 'cmd': '<show><high-availability><link-monitoring></link-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_path(): ''' Show high-availability path-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_path ''' query = {'type': 'op', 'cmd': '<show><high-availability><path-monitoring></path-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_state(): ''' Show high-availability state information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_state ''' query = {'type': 'op', 'cmd': '<show><high-availability><state></state></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_transitions(): ''' Show high-availability transition statistic information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_transitions ''' query = {'type': 'op', 'cmd': '<show><high-availability><transitions></transitions></high-availability></show>'} return __proxy__['panos.call'](query) def get_hostname(): ''' Get the hostname of the device. CLI Example: .. code-block:: bash salt '*' panos.get_hostname ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/hostname'} return __proxy__['panos.call'](query) def get_interface_counters(name='all'): ''' Get the counter statistics for interfaces. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interface_counters salt '*' panos.get_interface_counters ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><counter><interface>{0}</interface></counter></show>'.format(name)} return __proxy__['panos.call'](query) def get_interfaces(name='all'): ''' Show interface information. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interfaces salt '*' panos.get_interfaces ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><interface>{0}</interface></show>'.format(name)} return __proxy__['panos.call'](query) def get_job(jid=None): ''' List all a single job by ID. jid The ID of the job to retrieve. CLI Example: .. code-block:: bash salt '*' panos.get_job jid=15 ''' if not jid: raise CommandExecutionError("ID option must not be none.") query = {'type': 'op', 'cmd': '<show><jobs><id>{0}</id></jobs></show>'.format(jid)} return __proxy__['panos.call'](query) def get_jobs(state='all'): ''' List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending ''' if state.lower() == 'all': query = {'type': 'op', 'cmd': '<show><jobs><all></all></jobs></show>'} elif state.lower() == 'pending': query = {'type': 'op', 'cmd': '<show><jobs><pending></pending></jobs></show>'} elif state.lower() == 'processed': query = {'type': 'op', 'cmd': '<show><jobs><processed></processed></jobs></show>'} else: raise CommandExecutionError("The state parameter must be all, pending, or processed.") return __proxy__['panos.call'](query) def get_lacp(): ''' Show LACP state. CLI Example: .. code-block:: bash salt '*' panos.get_lacp ''' query = {'type': 'op', 'cmd': '<show><lacp><aggregate-ethernet>all</aggregate-ethernet></lacp></show>'} return __proxy__['panos.call'](query) def get_license_info(): ''' Show information about owned license(s). CLI Example: .. code-block:: bash salt '*' panos.get_license_info ''' query = {'type': 'op', 'cmd': '<request><license><info></info></license></request>'} return __proxy__['panos.call'](query) def get_license_tokens(): ''' Show license token files for manual license deactivation. CLI Example: .. code-block:: bash salt '*' panos.get_license_tokens ''' query = {'type': 'op', 'cmd': '<show><license-token-files></license-token-files></show>'} return __proxy__['panos.call'](query) def get_lldp_config(): ''' Show lldp config for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_config ''' query = {'type': 'op', 'cmd': '<show><lldp><config>all</config></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_counters(): ''' Show lldp counters for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_counters ''' query = {'type': 'op', 'cmd': '<show><lldp><counters>all</counters></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_local(): ''' Show lldp local info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_local ''' query = {'type': 'op', 'cmd': '<show><lldp><local>all</local></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_neighbors(): ''' Show lldp neighbors info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_neighbors ''' query = {'type': 'op', 'cmd': '<show><lldp><neighbors>all</neighbors></lldp></show>'} return __proxy__['panos.call'](query) def get_local_admins(): ''' Show all local administrator accounts. CLI Example: .. code-block:: bash salt '*' panos.get_local_admins ''' admin_list = get_users_config() response = [] if 'users' not in admin_list['result']: return response if isinstance(admin_list['result']['users']['entry'], list): for entry in admin_list['result']['users']['entry']: response.append(entry['name']) else: response.append(admin_list['result']['users']['entry']['name']) return response def get_logdb_quota(): ''' Report the logdb quotas. CLI Example: .. code-block:: bash salt '*' panos.get_logdb_quota ''' query = {'type': 'op', 'cmd': '<show><system><logdb-quota></logdb-quota></system></show>'} return __proxy__['panos.call'](query) def get_master_key(): ''' Get the master key properties. CLI Example: .. code-block:: bash salt '*' panos.get_master_key ''' query = {'type': 'op', 'cmd': '<show><system><masterkey-properties></masterkey-properties></system></show>'} return __proxy__['panos.call'](query) def get_ntp_config(): ''' Get the NTP configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers'} return __proxy__['panos.call'](query) def get_ntp_servers(): ''' Get list of configured NTP servers. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_servers ''' query = {'type': 'op', 'cmd': '<show><ntp></ntp></show>'} return __proxy__['panos.call'](query) def get_operational_mode(): ''' Show device operational mode setting. CLI Example: .. code-block:: bash salt '*' panos.get_operational_mode ''' query = {'type': 'op', 'cmd': '<show><operational-mode></operational-mode></show>'} return __proxy__['panos.call'](query) def get_panorama_status(): ''' Show panorama connection status. CLI Example: .. code-block:: bash salt '*' panos.get_panorama_status ''' query = {'type': 'op', 'cmd': '<show><panorama-status></panorama-status></show>'} return __proxy__['panos.call'](query) def get_permitted_ips(): ''' Get the IP addresses that are permitted to establish management connections to the device. CLI Example: .. code-block:: bash salt '*' panos.get_permitted_ips ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip'} return __proxy__['panos.call'](query) def get_platform(): ''' Get the platform model information and limitations. CLI Example: .. code-block:: bash salt '*' panos.get_platform ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/platform'} return __proxy__['panos.call'](query) def get_predefined_application(application=None): ''' Get the configuration for the specified pre-defined application object. This will only return pre-defined application objects. application(str): The name of the pre-defined application object. CLI Example: .. code-block:: bash salt '*' panos.get_predefined_application saltstack ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/predefined/application/entry[@name=\'{0}\']'.format(application)} return __proxy__['panos.call'](query) def get_security_rule(rulename=None, vsys='1'): ''' Get the candidate configuration for the specified security rule. rulename(str): The name of the security rule. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_security_rule rule01 salt '*' panos.get_security_rule rule01 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'rulebase/security/rules/entry[@name=\'{1}\']'.format(vsys, rulename)} return __proxy__['panos.call'](query) def get_service(service=None, vsys='1'): ''' Get the candidate configuration for the specified service object. This will not return services that are marked as pre-defined objects. service(str): The name of the service object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service tcp-443 salt '*' panos.get_service tcp-443 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service/entry[@name=\'{1}\']'.format(vsys, service)} return __proxy__['panos.call'](query) def get_service_group(servicegroup=None, vsys='1'): ''' Get the candidate configuration for the specified service group. This will not return service groups that are marked as pre-defined objects. servicegroup(str): The name of the service group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service_group foobar salt '*' panos.get_service_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service-group/entry[@name=\'{1}\']'.format(vsys, servicegroup)} return __proxy__['panos.call'](query) def get_session_info(): ''' Show device session statistics. CLI Example: .. code-block:: bash salt '*' panos.get_session_info ''' query = {'type': 'op', 'cmd': '<show><session><info></info></session></show>'} return __proxy__['panos.call'](query) def get_snmp_config(): ''' Get the SNMP configuration from the device. CLI Example: .. code-block:: bash salt '*' panos.get_snmp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/snmp-setting'} return __proxy__['panos.call'](query) def get_software_info(): ''' Show information about available software packages. CLI Example: .. code-block:: bash salt '*' panos.get_software_info ''' query = {'type': 'op', 'cmd': '<request><system><software><info></info></software></system></request>'} return __proxy__['panos.call'](query) def get_system_date_time(): ''' Get the system date/time. CLI Example: .. code-block:: bash salt '*' panos.get_system_date_time ''' query = {'type': 'op', 'cmd': '<show><clock></clock></show>'} return __proxy__['panos.call'](query) def get_system_files(): ''' List important files in the system. CLI Example: .. code-block:: bash salt '*' panos.get_system_files ''' query = {'type': 'op', 'cmd': '<show><system><files></files></system></show>'} return __proxy__['panos.call'](query) def get_system_info(): ''' Get the system information. CLI Example: .. code-block:: bash salt '*' panos.get_system_info ''' query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'} return __proxy__['panos.call'](query) def get_system_services(): ''' Show system services. CLI Example: .. code-block:: bash salt '*' panos.get_system_services ''' query = {'type': 'op', 'cmd': '<show><system><services></services></system></show>'} return __proxy__['panos.call'](query) def get_system_state(mask=None): ''' Show the system state variables. mask Filters by a subtree or a wildcard. CLI Example: .. code-block:: bash salt '*' panos.get_system_state salt '*' panos.get_system_state mask=cfg.ha.config.enabled salt '*' panos.get_system_state mask=cfg.ha.* ''' if mask: query = {'type': 'op', 'cmd': '<show><system><state><filter>{0}</filter></state></system></show>'.format(mask)} else: query = {'type': 'op', 'cmd': '<show><system><state></state></system></show>'} return __proxy__['panos.call'](query) def get_uncommitted_changes(): ''' Retrieve a list of all uncommitted changes on the device. Requires PANOS version 8.0.0 or greater. CLI Example: .. code-block:: bash salt '*' panos.get_uncommitted_changes ''' _required_version = '8.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) query = {'type': 'op', 'cmd': '<show><config><list><changes></changes></list></config></show>'} return __proxy__['panos.call'](query) def get_users_config(): ''' Get the local administrative user account configuration. CLI Example: .. code-block:: bash salt '*' panos.get_users_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/mgt-config/users'} return __proxy__['panos.call'](query) def get_vlans(): ''' Show all VLAN information. CLI Example: .. code-block:: bash salt '*' panos.get_vlans ''' query = {'type': 'op', 'cmd': '<show><vlan>all</vlan></show>'} return __proxy__['panos.call'](query) def get_xpath(xpath=''): ''' Retrieve a specified xpath from the candidate configuration. xpath(str): The specified xpath in the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_xpath /config/shared/service ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} return __proxy__['panos.call'](query) def get_zone(zone='', vsys='1'): ''' Get the candidate configuration for the specified zone. zone(str): The name of the zone. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zone trust salt '*' panos.get_zone trust 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone/entry[@name=\'{1}\']'.format(vsys, zone)} return __proxy__['panos.call'](query) def get_zones(vsys='1'): ''' Get all the zones in the candidate configuration. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zones salt '*' panos.get_zones 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone'.format(vsys)} return __proxy__['panos.call'](query) def install_antivirus(version=None, latest=False, synch=False, skip_commit=False,): ''' Install anti-virus packages. Args: version(str): The version of the PANOS file to install. latest(bool): If true, the latest anti-virus file will be installed. The specified version option will be ignored. synch(bool): If true, the anti-virus will synch to the peer unit. skip_commit(bool): If true, the install will skip committing to the device. CLI Example: .. code-block:: bash salt '*' panos.install_antivirus 8.0.0 ''' if not version and latest is False: raise CommandExecutionError("Version option must not be none.") if synch is True: s = "yes" else: s = "no" if skip_commit is True: c = "yes" else: c = "no" if latest is True: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>latest</version></install></upgrade></anti-virus></request>'.format(c, s)} else: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>{2}</version></install></upgrade></anti-virus></request>'.format(c, s, version)} return _get_job_results(query) def install_license(): ''' Install the license key(s). CLI Example: .. code-block:: bash salt '*' panos.install_license ''' query = {'type': 'op', 'cmd': '<request><license><install></install></license></request>'} return __proxy__['panos.call'](query) def install_software(version=None): ''' Upgrade to a software package by version. Args: version(str): The version of the PANOS file to install. CLI Example: .. code-block:: bash salt '*' panos.install_license 8.0.0 ''' if not version: raise CommandExecutionError("Version option must not be none.") query = {'type': 'op', 'cmd': '<request><system><software><install>' '<version>{0}</version></install></software></system></request>'.format(version)} return _get_job_results(query) def reboot(): ''' Reboot a running system. CLI Example: .. code-block:: bash salt '*' panos.reboot ''' query = {'type': 'op', 'cmd': '<request><restart><system></system></restart></request>'} return __proxy__['panos.call'](query) def refresh_fqdn_cache(force=False): ''' Force refreshes all FQDNs used in rules. force Forces all fqdn refresh CLI Example: .. code-block:: bash salt '*' panos.refresh_fqdn_cache salt '*' panos.refresh_fqdn_cache force=True ''' if not isinstance(force, bool): raise CommandExecutionError("Force option must be boolean.") if force: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh><force>yes</force></refresh></fqdn></system></request>'} else: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh></refresh></fqdn></system></request>'} return __proxy__['panos.call'](query) def remove_config_lock(): ''' Release config lock previously held. CLI Example: .. code-block:: bash salt '*' panos.remove_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><remove></remove></config-lock></request>'} return __proxy__['panos.call'](query) def save_device_config(filename=None): ''' Save device configuration to a named file. filename The filename to save the configuration to. CLI Example: .. code-block:: bash salt '*' panos.save_device_config foo.xml ''' if not filename: raise CommandExecutionError("Filename must not be empty.") query = {'type': 'op', 'cmd': '<save><config><to>{0}</to></config></save>'.format(filename)} return __proxy__['panos.call'](query) def save_device_state(): ''' Save files needed to restore device to local disk. CLI Example: .. code-block:: bash salt '*' panos.save_device_state ''' query = {'type': 'op', 'cmd': '<save><device-state></device-state></save>'} return __proxy__['panos.call'](query) def set_authentication_profile(profile=None, deploy=False): ''' Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_authentication_profile foo salt '*' panos.set_authentication_profile foo deploy=True ''' if not profile: raise CommandExecutionError("Profile name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/' 'authentication-profile', 'element': '<authentication-profile>{0}</authentication-profile>'.format(profile)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_hostname(hostname=None, deploy=False): ''' Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True ''' if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system', 'element': '<hostname>{0}</hostname>'.format(hostname)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_icmp(enabled=True, deploy=False): ''' Enables or disables the ICMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_icmp salt '*' panos.set_management_icmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-icmp>{0}</disable-icmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_http(enabled=True, deploy=False): ''' Enables or disables the HTTP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_http salt '*' panos.set_management_http enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http>{0}</disable-http>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_https(enabled=True, deploy=False): ''' Enables or disables the HTTPS management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_https salt '*' panos.set_management_https enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-https>{0}</disable-https>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ocsp(enabled=True, deploy=False): ''' Enables or disables the HTTP OCSP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ocsp salt '*' panos.set_management_ocsp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http-ocsp>{0}</disable-http-ocsp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_snmp(enabled=True, deploy=False): ''' Enables or disables the SNMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_snmp salt '*' panos.set_management_snmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-snmp>{0}</disable-snmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ssh(enabled=True, deploy=False): ''' Enables or disables the SSH management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ssh salt '*' panos.set_management_ssh enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-ssh>{0}</disable-ssh>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_telnet(enabled=True, deploy=False): ''' Enables or disables the Telnet management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_telnet salt '*' panos.set_management_telnet enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-telnet>{0}</disable-telnet>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_ntp_authentication(target=None, authentication_type=None, key_id=None, authentication_key=None, algorithm=None, deploy=False): ''' Set the NTP authentication of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: target(str): Determines the target of the authentication. Valid options are primary, secondary, or both. authentication_type(str): The authentication type to be used. Valid options are symmetric, autokey, and none. key_id(int): The NTP authentication key ID. authentication_key(str): The authentication key. algorithm(str): The algorithm type to be used for a symmetric key. Valid options are md5 and sha1. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_authentication target=both authentication_type=autokey salt '*' ntp.set_authentication target=primary authentication_type=none salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 deploy=True ''' ret = {} if target not in ['primary', 'secondary', 'both']: raise salt.exceptions.CommandExecutionError("Target option must be primary, secondary, or both.") if authentication_type not in ['symmetric', 'autokey', 'none']: raise salt.exceptions.CommandExecutionError("Type option must be symmetric, autokey, or both.") if authentication_type == "symmetric" and not authentication_key: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, authentication_key must be " "provided.") if authentication_type == "symmetric" and not key_id: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, key_id must be provided.") if authentication_type == "symmetric" and algorithm not in ['md5', 'sha1']: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, algorithm must be md5 or " "sha1.") if authentication_type == 'symmetric': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'autokey': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'none': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): ''' Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server(str): The secondary NTP server IP address or FQDN. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_servers 0.pool.ntp.org 1.pool.ntp.org salt '*' ntp.set_servers primary_server=0.pool.ntp.org secondary_server=1.pool.ntp.org salt '*' ntp.ser_servers 0.pool.ntp.org 1.pool.ntp.org deploy=True ''' ret = {} if primary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(primary_server)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if secondary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(secondary_server)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_permitted_ip(address=None, deploy=False): ''' Add an IPv4 address or network to the permitted IP list. CLI Example: Args: address (str): The IPv4 address or network to allow access to add to the Palo Alto device. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_permitted_ip 10.0.0.1 salt '*' panos.set_permitted_ip 10.0.0.0/24 salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True ''' if not address: raise CommandExecutionError("Address option must not be empty.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip', 'element': '<entry name=\'{0}\'></entry>'.format(address)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_timezone UTC salt '*' panos.set_timezone UTC deploy=True ''' if not tz: raise CommandExecutionError("Timezone name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/timezone', 'element': '<timezone>{0}</timezone>'.format(tz)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def shutdown(): ''' Shutdown a running system. CLI Example: .. code-block:: bash salt '*' panos.shutdown ''' query = {'type': 'op', 'cmd': '<request><shutdown><system></system></shutdown></request>'} return __proxy__['panos.call'](query) def test_fib_route(ip=None, vr='vr1'): ''' Perform a route lookup within active route table (fib). ip (str): The destination IP address to test. vr (str): The name of the virtual router to test. CLI Example: .. code-block:: bash salt '*' panos.test_fib_route 4.2.2.2 salt '*' panos.test_fib_route 4.2.2.2 my-vr ''' xpath = "<test><routing><fib-lookup>" if ip: xpath += "<ip>{0}</ip>".format(ip) if vr: xpath += "<virtual-router>{0}</virtual-router>".format(vr) xpath += "</fib-lookup></routing></test>" query = {'type': 'op', 'cmd': xpath} return __proxy__['panos.call'](query) def test_security_policy(sourcezone=None, destinationzone=None, source=None, destination=None, protocol=None, port=None, application=None, category=None, vsys='1', allrules=False): ''' Checks which security policy as connection will match on the device. sourcezone (str): The source zone matched against the connection. destinationzone (str): The destination zone matched against the connection. source (str): The source address. This must be a single IP address. destination (str): The destination address. This must be a single IP address. protocol (int): The protocol number for the connection. This is the numerical representation of the protocol. port (int): The port number for the connection. application (str): The application that should be matched. category (str): The category that should be matched. vsys (int): The numerical representation of the VSYS ID. allrules (bool): Show all potential match rules until first allow rule. CLI Example: .. code-block:: bash salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 vsys=2 ''' xpath = "<test><security-policy-match>" if sourcezone: xpath += "<from>{0}</from>".format(sourcezone) if destinationzone: xpath += "<to>{0}</to>".format(destinationzone) if source: xpath += "<source>{0}</source>".format(source) if destination: xpath += "<destination>{0}</destination>".format(destination) if protocol: xpath += "<protocol>{0}</protocol>".format(protocol) if port: xpath += "<destination-port>{0}</destination-port>".format(port) if application: xpath += "<application>{0}</application>".format(application) if category: xpath += "<category>{0}</category>".format(category) if allrules: xpath += "<show-all>yes</show-all>" xpath += "</security-policy-match></test>" query = {'type': 'op', 'vsys': "vsys{0}".format(vsys), 'cmd': xpath} return __proxy__['panos.call'](query) def unlock_admin(username=None): ''' Unlocks a locked administrator account. username Username of the administrator. CLI Example: .. code-block:: bash salt '*' panos.unlock_admin username=bob ''' if not username: raise CommandExecutionError("Username option must not be none.") query = {'type': 'op', 'cmd': '<set><management-server><unlock><admin>{0}</admin></unlock></management-server>' '</set>'.format(username)} return __proxy__['panos.call'](query)
saltstack/salt
salt/modules/panos.py
set_authentication_profile
python
def set_authentication_profile(profile=None, deploy=False): ''' Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_authentication_profile foo salt '*' panos.set_authentication_profile foo deploy=True ''' if not profile: raise CommandExecutionError("Profile name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/' 'authentication-profile', 'element': '<authentication-profile>{0}</authentication-profile>'.format(profile)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret
Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_authentication_profile foo salt '*' panos.set_authentication_profile foo deploy=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/panos.py#L1604-L1638
[ "def commit():\n '''\n Commits the candidate configuration to the running configuration.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' panos.commit\n\n '''\n query = {'type': 'commit', 'cmd': '<commit></commit>'}\n\n return _get_job_results(query)\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Palo Alto compatibility to Salt :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix .. versionadded:: 2018.3.0 Configuration ============= This module accepts connection configuration details either as parameters, or as configuration settings in pillar as a Salt proxy. Options passed into opts will be ignored if options are passed into pillar. .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` About ===== This execution module was designed to handle connections to a Palo Alto based firewall. This module adds support to send connections directly to the device through the XML API or through a brokered connection to Panorama. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import Salt Libs from salt.exceptions import CommandExecutionError import salt.proxy.panos import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'panos' def __virtual__(): ''' Will load for the panos proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'panos': return __virtualname__ except KeyError: pass return False, 'The panos execution module can only be loaded for panos proxy minions.' def _get_job_results(query=None): ''' Executes a query that requires a job for completion. This function will wait for the job to complete and return the results. ''' if not query: raise CommandExecutionError("Query parameters cannot be empty.") response = __proxy__['panos.call'](query) # If the response contains a job, we will wait for the results if 'result' in response and 'job' in response['result']: jid = response['result']['job'] while get_job(jid)['result']['job']['status'] != 'FIN': time.sleep(5) return get_job(jid) else: return response def add_config_lock(): ''' Prevent other users from changing configuration until the lock is released. CLI Example: .. code-block:: bash salt '*' panos.add_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><add></add></config-lock></request>'} return __proxy__['panos.call'](query) def check_antivirus(): ''' Get anti-virus information from PaloAlto Networks server CLI Example: .. code-block:: bash salt '*' panos.check_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><check></check></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def check_software(): ''' Get software information from PaloAlto Networks server. CLI Example: .. code-block:: bash salt '*' panos.check_software ''' query = {'type': 'op', 'cmd': '<request><system><software><check></check></software></system></request>'} return __proxy__['panos.call'](query) def clear_commit_tasks(): ''' Clear all commit tasks. CLI Example: .. code-block:: bash salt '*' panos.clear_commit_tasks ''' query = {'type': 'op', 'cmd': '<request><clear-commit-tasks></clear-commit-tasks></request>'} return __proxy__['panos.call'](query) def commit(): ''' Commits the candidate configuration to the running configuration. CLI Example: .. code-block:: bash salt '*' panos.commit ''' query = {'type': 'commit', 'cmd': '<commit></commit>'} return _get_job_results(query) def deactivate_license(key_name=None): ''' Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<request><license><deactivate><key><features><member>{0}</member></features>' '</key></deactivate></license></request>'.format(key_name)} return __proxy__['panos.call'](query) def delete_license(key_name=None): ''' Remove license keys on disk. key_name(str): The file name of the license key to be deleted. CLI Example: .. code-block:: bash salt '*' panos.delete_license key_name=License_File_Name.key ''' if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<delete><license><key>{0}</key></license></delete>'.format(key_name)} return __proxy__['panos.call'](query) def download_antivirus(): ''' Download the most recent anti-virus package. CLI Example: .. code-block:: bash salt '*' panos.download_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><download>' '<latest></latest></download></upgrade></anti-virus></request>'} return _get_job_results(query) def download_software_file(filename=None, synch=False): ''' Download software packages by filename. Args: filename(str): The filename of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_file PanOS_5000-8.0.0 salt '*' panos.download_software_file PanOS_5000-8.0.0 True ''' if not filename: raise CommandExecutionError("Filename option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<file>{0}</file></download></software></system></request>'.format(filename)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<file>{0}</file></download></software></system></request>'.format(filename)} return _get_job_results(query) def download_software_version(version=None, synch=False): ''' Download software packages by version number. Args: version(str): The version of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_version 8.0.0 salt '*' panos.download_software_version 8.0.0 True ''' if not version: raise CommandExecutionError("Version option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<version>{0}</version></download></software></system></request>'.format(version)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<version>{0}</version></download></software></system></request>'.format(version)} return _get_job_results(query) def fetch_license(auth_code=None): ''' Get new license(s) using from the Palo Alto Network Server. auth_code The license authorization code. CLI Example: .. code-block:: bash salt '*' panos.fetch_license salt '*' panos.fetch_license auth_code=foobar ''' if not auth_code: query = {'type': 'op', 'cmd': '<request><license><fetch></fetch></license></request>'} else: query = {'type': 'op', 'cmd': '<request><license><fetch><auth-code>{0}</auth-code></fetch></license>' '</request>'.format(auth_code)} return __proxy__['panos.call'](query) def get_address(address=None, vsys='1'): ''' Get the candidate configuration for the specified get_address object. This will not return address objects that are marked as pre-defined objects. address(str): The name of the address object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address myhost salt '*' panos.get_address myhost 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address/entry[@name=\'{1}\']'.format(vsys, address)} return __proxy__['panos.call'](query) def get_address_group(addressgroup=None, vsys='1'): ''' Get the candidate configuration for the specified address group. This will not return address groups that are marked as pre-defined objects. addressgroup(str): The name of the address group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address_group foobar salt '*' panos.get_address_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address-group/entry[@name=\'{1}\']'.format(vsys, addressgroup)} return __proxy__['panos.call'](query) def get_admins_active(): ''' Show active administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_active ''' query = {'type': 'op', 'cmd': '<show><admins></admins></show>'} return __proxy__['panos.call'](query) def get_admins_all(): ''' Show all administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_all ''' query = {'type': 'op', 'cmd': '<show><admins><all></all></admins></show>'} return __proxy__['panos.call'](query) def get_antivirus_info(): ''' Show information about available anti-virus packages. CLI Example: .. code-block:: bash salt '*' panos.get_antivirus_info ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><info></info></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def get_arp(): ''' Show ARP information. CLI Example: .. code-block:: bash salt '*' panos.get_arp ''' query = {'type': 'op', 'cmd': '<show><arp><entry name = \'all\'/></arp></show>'} return __proxy__['panos.call'](query) def get_cli_idle_timeout(): ''' Show timeout information for this administrative session. CLI Example: .. code-block:: bash salt '*' panos.get_cli_idle_timeout ''' query = {'type': 'op', 'cmd': '<show><cli><idle-timeout></idle-timeout></cli></show>'} return __proxy__['panos.call'](query) def get_cli_permissions(): ''' Show cli administrative permissions. CLI Example: .. code-block:: bash salt '*' panos.get_cli_permissions ''' query = {'type': 'op', 'cmd': '<show><cli><permissions></permissions></cli></show>'} return __proxy__['panos.call'](query) def get_disk_usage(): ''' Report filesystem disk space usage. CLI Example: .. code-block:: bash salt '*' panos.get_disk_usage ''' query = {'type': 'op', 'cmd': '<show><system><disk-space></disk-space></system></show>'} return __proxy__['panos.call'](query) def get_dns_server_config(): ''' Get the DNS server configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_dns_server_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/dns-setting/servers'} return __proxy__['panos.call'](query) def get_domain_config(): ''' Get the domain name configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_domain_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/domain'} return __proxy__['panos.call'](query) def get_dos_blocks(): ''' Show the DoS block-ip table. CLI Example: .. code-block:: bash salt '*' panos.get_dos_blocks ''' query = {'type': 'op', 'cmd': '<show><dos-block-table><all></all></dos-block-table></show>'} return __proxy__['panos.call'](query) def get_fqdn_cache(): ''' Print FQDNs used in rules and their IPs. CLI Example: .. code-block:: bash salt '*' panos.get_fqdn_cache ''' query = {'type': 'op', 'cmd': '<request><system><fqdn><show></show></fqdn></system></request>'} return __proxy__['panos.call'](query) def get_ha_config(): ''' Get the high availability configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ha_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/high-availability'} return __proxy__['panos.call'](query) def get_ha_link(): ''' Show high-availability link-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_link ''' query = {'type': 'op', 'cmd': '<show><high-availability><link-monitoring></link-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_path(): ''' Show high-availability path-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_path ''' query = {'type': 'op', 'cmd': '<show><high-availability><path-monitoring></path-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_state(): ''' Show high-availability state information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_state ''' query = {'type': 'op', 'cmd': '<show><high-availability><state></state></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_transitions(): ''' Show high-availability transition statistic information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_transitions ''' query = {'type': 'op', 'cmd': '<show><high-availability><transitions></transitions></high-availability></show>'} return __proxy__['panos.call'](query) def get_hostname(): ''' Get the hostname of the device. CLI Example: .. code-block:: bash salt '*' panos.get_hostname ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/hostname'} return __proxy__['panos.call'](query) def get_interface_counters(name='all'): ''' Get the counter statistics for interfaces. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interface_counters salt '*' panos.get_interface_counters ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><counter><interface>{0}</interface></counter></show>'.format(name)} return __proxy__['panos.call'](query) def get_interfaces(name='all'): ''' Show interface information. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interfaces salt '*' panos.get_interfaces ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><interface>{0}</interface></show>'.format(name)} return __proxy__['panos.call'](query) def get_job(jid=None): ''' List all a single job by ID. jid The ID of the job to retrieve. CLI Example: .. code-block:: bash salt '*' panos.get_job jid=15 ''' if not jid: raise CommandExecutionError("ID option must not be none.") query = {'type': 'op', 'cmd': '<show><jobs><id>{0}</id></jobs></show>'.format(jid)} return __proxy__['panos.call'](query) def get_jobs(state='all'): ''' List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending ''' if state.lower() == 'all': query = {'type': 'op', 'cmd': '<show><jobs><all></all></jobs></show>'} elif state.lower() == 'pending': query = {'type': 'op', 'cmd': '<show><jobs><pending></pending></jobs></show>'} elif state.lower() == 'processed': query = {'type': 'op', 'cmd': '<show><jobs><processed></processed></jobs></show>'} else: raise CommandExecutionError("The state parameter must be all, pending, or processed.") return __proxy__['panos.call'](query) def get_lacp(): ''' Show LACP state. CLI Example: .. code-block:: bash salt '*' panos.get_lacp ''' query = {'type': 'op', 'cmd': '<show><lacp><aggregate-ethernet>all</aggregate-ethernet></lacp></show>'} return __proxy__['panos.call'](query) def get_license_info(): ''' Show information about owned license(s). CLI Example: .. code-block:: bash salt '*' panos.get_license_info ''' query = {'type': 'op', 'cmd': '<request><license><info></info></license></request>'} return __proxy__['panos.call'](query) def get_license_tokens(): ''' Show license token files for manual license deactivation. CLI Example: .. code-block:: bash salt '*' panos.get_license_tokens ''' query = {'type': 'op', 'cmd': '<show><license-token-files></license-token-files></show>'} return __proxy__['panos.call'](query) def get_lldp_config(): ''' Show lldp config for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_config ''' query = {'type': 'op', 'cmd': '<show><lldp><config>all</config></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_counters(): ''' Show lldp counters for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_counters ''' query = {'type': 'op', 'cmd': '<show><lldp><counters>all</counters></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_local(): ''' Show lldp local info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_local ''' query = {'type': 'op', 'cmd': '<show><lldp><local>all</local></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_neighbors(): ''' Show lldp neighbors info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_neighbors ''' query = {'type': 'op', 'cmd': '<show><lldp><neighbors>all</neighbors></lldp></show>'} return __proxy__['panos.call'](query) def get_local_admins(): ''' Show all local administrator accounts. CLI Example: .. code-block:: bash salt '*' panos.get_local_admins ''' admin_list = get_users_config() response = [] if 'users' not in admin_list['result']: return response if isinstance(admin_list['result']['users']['entry'], list): for entry in admin_list['result']['users']['entry']: response.append(entry['name']) else: response.append(admin_list['result']['users']['entry']['name']) return response def get_logdb_quota(): ''' Report the logdb quotas. CLI Example: .. code-block:: bash salt '*' panos.get_logdb_quota ''' query = {'type': 'op', 'cmd': '<show><system><logdb-quota></logdb-quota></system></show>'} return __proxy__['panos.call'](query) def get_master_key(): ''' Get the master key properties. CLI Example: .. code-block:: bash salt '*' panos.get_master_key ''' query = {'type': 'op', 'cmd': '<show><system><masterkey-properties></masterkey-properties></system></show>'} return __proxy__['panos.call'](query) def get_ntp_config(): ''' Get the NTP configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers'} return __proxy__['panos.call'](query) def get_ntp_servers(): ''' Get list of configured NTP servers. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_servers ''' query = {'type': 'op', 'cmd': '<show><ntp></ntp></show>'} return __proxy__['panos.call'](query) def get_operational_mode(): ''' Show device operational mode setting. CLI Example: .. code-block:: bash salt '*' panos.get_operational_mode ''' query = {'type': 'op', 'cmd': '<show><operational-mode></operational-mode></show>'} return __proxy__['panos.call'](query) def get_panorama_status(): ''' Show panorama connection status. CLI Example: .. code-block:: bash salt '*' panos.get_panorama_status ''' query = {'type': 'op', 'cmd': '<show><panorama-status></panorama-status></show>'} return __proxy__['panos.call'](query) def get_permitted_ips(): ''' Get the IP addresses that are permitted to establish management connections to the device. CLI Example: .. code-block:: bash salt '*' panos.get_permitted_ips ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip'} return __proxy__['panos.call'](query) def get_platform(): ''' Get the platform model information and limitations. CLI Example: .. code-block:: bash salt '*' panos.get_platform ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/platform'} return __proxy__['panos.call'](query) def get_predefined_application(application=None): ''' Get the configuration for the specified pre-defined application object. This will only return pre-defined application objects. application(str): The name of the pre-defined application object. CLI Example: .. code-block:: bash salt '*' panos.get_predefined_application saltstack ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/predefined/application/entry[@name=\'{0}\']'.format(application)} return __proxy__['panos.call'](query) def get_security_rule(rulename=None, vsys='1'): ''' Get the candidate configuration for the specified security rule. rulename(str): The name of the security rule. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_security_rule rule01 salt '*' panos.get_security_rule rule01 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'rulebase/security/rules/entry[@name=\'{1}\']'.format(vsys, rulename)} return __proxy__['panos.call'](query) def get_service(service=None, vsys='1'): ''' Get the candidate configuration for the specified service object. This will not return services that are marked as pre-defined objects. service(str): The name of the service object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service tcp-443 salt '*' panos.get_service tcp-443 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service/entry[@name=\'{1}\']'.format(vsys, service)} return __proxy__['panos.call'](query) def get_service_group(servicegroup=None, vsys='1'): ''' Get the candidate configuration for the specified service group. This will not return service groups that are marked as pre-defined objects. servicegroup(str): The name of the service group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service_group foobar salt '*' panos.get_service_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service-group/entry[@name=\'{1}\']'.format(vsys, servicegroup)} return __proxy__['panos.call'](query) def get_session_info(): ''' Show device session statistics. CLI Example: .. code-block:: bash salt '*' panos.get_session_info ''' query = {'type': 'op', 'cmd': '<show><session><info></info></session></show>'} return __proxy__['panos.call'](query) def get_snmp_config(): ''' Get the SNMP configuration from the device. CLI Example: .. code-block:: bash salt '*' panos.get_snmp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/snmp-setting'} return __proxy__['panos.call'](query) def get_software_info(): ''' Show information about available software packages. CLI Example: .. code-block:: bash salt '*' panos.get_software_info ''' query = {'type': 'op', 'cmd': '<request><system><software><info></info></software></system></request>'} return __proxy__['panos.call'](query) def get_system_date_time(): ''' Get the system date/time. CLI Example: .. code-block:: bash salt '*' panos.get_system_date_time ''' query = {'type': 'op', 'cmd': '<show><clock></clock></show>'} return __proxy__['panos.call'](query) def get_system_files(): ''' List important files in the system. CLI Example: .. code-block:: bash salt '*' panos.get_system_files ''' query = {'type': 'op', 'cmd': '<show><system><files></files></system></show>'} return __proxy__['panos.call'](query) def get_system_info(): ''' Get the system information. CLI Example: .. code-block:: bash salt '*' panos.get_system_info ''' query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'} return __proxy__['panos.call'](query) def get_system_services(): ''' Show system services. CLI Example: .. code-block:: bash salt '*' panos.get_system_services ''' query = {'type': 'op', 'cmd': '<show><system><services></services></system></show>'} return __proxy__['panos.call'](query) def get_system_state(mask=None): ''' Show the system state variables. mask Filters by a subtree or a wildcard. CLI Example: .. code-block:: bash salt '*' panos.get_system_state salt '*' panos.get_system_state mask=cfg.ha.config.enabled salt '*' panos.get_system_state mask=cfg.ha.* ''' if mask: query = {'type': 'op', 'cmd': '<show><system><state><filter>{0}</filter></state></system></show>'.format(mask)} else: query = {'type': 'op', 'cmd': '<show><system><state></state></system></show>'} return __proxy__['panos.call'](query) def get_uncommitted_changes(): ''' Retrieve a list of all uncommitted changes on the device. Requires PANOS version 8.0.0 or greater. CLI Example: .. code-block:: bash salt '*' panos.get_uncommitted_changes ''' _required_version = '8.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) query = {'type': 'op', 'cmd': '<show><config><list><changes></changes></list></config></show>'} return __proxy__['panos.call'](query) def get_users_config(): ''' Get the local administrative user account configuration. CLI Example: .. code-block:: bash salt '*' panos.get_users_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/mgt-config/users'} return __proxy__['panos.call'](query) def get_vlans(): ''' Show all VLAN information. CLI Example: .. code-block:: bash salt '*' panos.get_vlans ''' query = {'type': 'op', 'cmd': '<show><vlan>all</vlan></show>'} return __proxy__['panos.call'](query) def get_xpath(xpath=''): ''' Retrieve a specified xpath from the candidate configuration. xpath(str): The specified xpath in the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_xpath /config/shared/service ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} return __proxy__['panos.call'](query) def get_zone(zone='', vsys='1'): ''' Get the candidate configuration for the specified zone. zone(str): The name of the zone. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zone trust salt '*' panos.get_zone trust 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone/entry[@name=\'{1}\']'.format(vsys, zone)} return __proxy__['panos.call'](query) def get_zones(vsys='1'): ''' Get all the zones in the candidate configuration. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zones salt '*' panos.get_zones 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone'.format(vsys)} return __proxy__['panos.call'](query) def install_antivirus(version=None, latest=False, synch=False, skip_commit=False,): ''' Install anti-virus packages. Args: version(str): The version of the PANOS file to install. latest(bool): If true, the latest anti-virus file will be installed. The specified version option will be ignored. synch(bool): If true, the anti-virus will synch to the peer unit. skip_commit(bool): If true, the install will skip committing to the device. CLI Example: .. code-block:: bash salt '*' panos.install_antivirus 8.0.0 ''' if not version and latest is False: raise CommandExecutionError("Version option must not be none.") if synch is True: s = "yes" else: s = "no" if skip_commit is True: c = "yes" else: c = "no" if latest is True: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>latest</version></install></upgrade></anti-virus></request>'.format(c, s)} else: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>{2}</version></install></upgrade></anti-virus></request>'.format(c, s, version)} return _get_job_results(query) def install_license(): ''' Install the license key(s). CLI Example: .. code-block:: bash salt '*' panos.install_license ''' query = {'type': 'op', 'cmd': '<request><license><install></install></license></request>'} return __proxy__['panos.call'](query) def install_software(version=None): ''' Upgrade to a software package by version. Args: version(str): The version of the PANOS file to install. CLI Example: .. code-block:: bash salt '*' panos.install_license 8.0.0 ''' if not version: raise CommandExecutionError("Version option must not be none.") query = {'type': 'op', 'cmd': '<request><system><software><install>' '<version>{0}</version></install></software></system></request>'.format(version)} return _get_job_results(query) def reboot(): ''' Reboot a running system. CLI Example: .. code-block:: bash salt '*' panos.reboot ''' query = {'type': 'op', 'cmd': '<request><restart><system></system></restart></request>'} return __proxy__['panos.call'](query) def refresh_fqdn_cache(force=False): ''' Force refreshes all FQDNs used in rules. force Forces all fqdn refresh CLI Example: .. code-block:: bash salt '*' panos.refresh_fqdn_cache salt '*' panos.refresh_fqdn_cache force=True ''' if not isinstance(force, bool): raise CommandExecutionError("Force option must be boolean.") if force: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh><force>yes</force></refresh></fqdn></system></request>'} else: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh></refresh></fqdn></system></request>'} return __proxy__['panos.call'](query) def remove_config_lock(): ''' Release config lock previously held. CLI Example: .. code-block:: bash salt '*' panos.remove_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><remove></remove></config-lock></request>'} return __proxy__['panos.call'](query) def resolve_address(address=None, vsys=None): ''' Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com salt '*' panos.resolve_address foo.bar.com vsys=2 ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not address: raise CommandExecutionError("FQDN to resolve must be provided as address.") if not vsys: query = {'type': 'op', 'cmd': '<request><resolve><address>{0}</address></resolve></request>'.format(address)} else: query = {'type': 'op', 'cmd': '<request><resolve><vsys>{0}</vsys><address>{1}</address></resolve>' '</request>'.format(vsys, address)} return __proxy__['panos.call'](query) def save_device_config(filename=None): ''' Save device configuration to a named file. filename The filename to save the configuration to. CLI Example: .. code-block:: bash salt '*' panos.save_device_config foo.xml ''' if not filename: raise CommandExecutionError("Filename must not be empty.") query = {'type': 'op', 'cmd': '<save><config><to>{0}</to></config></save>'.format(filename)} return __proxy__['panos.call'](query) def save_device_state(): ''' Save files needed to restore device to local disk. CLI Example: .. code-block:: bash salt '*' panos.save_device_state ''' query = {'type': 'op', 'cmd': '<save><device-state></device-state></save>'} return __proxy__['panos.call'](query) def set_hostname(hostname=None, deploy=False): ''' Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True ''' if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system', 'element': '<hostname>{0}</hostname>'.format(hostname)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_icmp(enabled=True, deploy=False): ''' Enables or disables the ICMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_icmp salt '*' panos.set_management_icmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-icmp>{0}</disable-icmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_http(enabled=True, deploy=False): ''' Enables or disables the HTTP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_http salt '*' panos.set_management_http enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http>{0}</disable-http>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_https(enabled=True, deploy=False): ''' Enables or disables the HTTPS management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_https salt '*' panos.set_management_https enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-https>{0}</disable-https>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ocsp(enabled=True, deploy=False): ''' Enables or disables the HTTP OCSP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ocsp salt '*' panos.set_management_ocsp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http-ocsp>{0}</disable-http-ocsp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_snmp(enabled=True, deploy=False): ''' Enables or disables the SNMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_snmp salt '*' panos.set_management_snmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-snmp>{0}</disable-snmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ssh(enabled=True, deploy=False): ''' Enables or disables the SSH management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ssh salt '*' panos.set_management_ssh enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-ssh>{0}</disable-ssh>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_telnet(enabled=True, deploy=False): ''' Enables or disables the Telnet management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_telnet salt '*' panos.set_management_telnet enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-telnet>{0}</disable-telnet>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_ntp_authentication(target=None, authentication_type=None, key_id=None, authentication_key=None, algorithm=None, deploy=False): ''' Set the NTP authentication of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: target(str): Determines the target of the authentication. Valid options are primary, secondary, or both. authentication_type(str): The authentication type to be used. Valid options are symmetric, autokey, and none. key_id(int): The NTP authentication key ID. authentication_key(str): The authentication key. algorithm(str): The algorithm type to be used for a symmetric key. Valid options are md5 and sha1. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_authentication target=both authentication_type=autokey salt '*' ntp.set_authentication target=primary authentication_type=none salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 deploy=True ''' ret = {} if target not in ['primary', 'secondary', 'both']: raise salt.exceptions.CommandExecutionError("Target option must be primary, secondary, or both.") if authentication_type not in ['symmetric', 'autokey', 'none']: raise salt.exceptions.CommandExecutionError("Type option must be symmetric, autokey, or both.") if authentication_type == "symmetric" and not authentication_key: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, authentication_key must be " "provided.") if authentication_type == "symmetric" and not key_id: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, key_id must be provided.") if authentication_type == "symmetric" and algorithm not in ['md5', 'sha1']: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, algorithm must be md5 or " "sha1.") if authentication_type == 'symmetric': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'autokey': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'none': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): ''' Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server(str): The secondary NTP server IP address or FQDN. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_servers 0.pool.ntp.org 1.pool.ntp.org salt '*' ntp.set_servers primary_server=0.pool.ntp.org secondary_server=1.pool.ntp.org salt '*' ntp.ser_servers 0.pool.ntp.org 1.pool.ntp.org deploy=True ''' ret = {} if primary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(primary_server)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if secondary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(secondary_server)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_permitted_ip(address=None, deploy=False): ''' Add an IPv4 address or network to the permitted IP list. CLI Example: Args: address (str): The IPv4 address or network to allow access to add to the Palo Alto device. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_permitted_ip 10.0.0.1 salt '*' panos.set_permitted_ip 10.0.0.0/24 salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True ''' if not address: raise CommandExecutionError("Address option must not be empty.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip', 'element': '<entry name=\'{0}\'></entry>'.format(address)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_timezone UTC salt '*' panos.set_timezone UTC deploy=True ''' if not tz: raise CommandExecutionError("Timezone name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/timezone', 'element': '<timezone>{0}</timezone>'.format(tz)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def shutdown(): ''' Shutdown a running system. CLI Example: .. code-block:: bash salt '*' panos.shutdown ''' query = {'type': 'op', 'cmd': '<request><shutdown><system></system></shutdown></request>'} return __proxy__['panos.call'](query) def test_fib_route(ip=None, vr='vr1'): ''' Perform a route lookup within active route table (fib). ip (str): The destination IP address to test. vr (str): The name of the virtual router to test. CLI Example: .. code-block:: bash salt '*' panos.test_fib_route 4.2.2.2 salt '*' panos.test_fib_route 4.2.2.2 my-vr ''' xpath = "<test><routing><fib-lookup>" if ip: xpath += "<ip>{0}</ip>".format(ip) if vr: xpath += "<virtual-router>{0}</virtual-router>".format(vr) xpath += "</fib-lookup></routing></test>" query = {'type': 'op', 'cmd': xpath} return __proxy__['panos.call'](query) def test_security_policy(sourcezone=None, destinationzone=None, source=None, destination=None, protocol=None, port=None, application=None, category=None, vsys='1', allrules=False): ''' Checks which security policy as connection will match on the device. sourcezone (str): The source zone matched against the connection. destinationzone (str): The destination zone matched against the connection. source (str): The source address. This must be a single IP address. destination (str): The destination address. This must be a single IP address. protocol (int): The protocol number for the connection. This is the numerical representation of the protocol. port (int): The port number for the connection. application (str): The application that should be matched. category (str): The category that should be matched. vsys (int): The numerical representation of the VSYS ID. allrules (bool): Show all potential match rules until first allow rule. CLI Example: .. code-block:: bash salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 vsys=2 ''' xpath = "<test><security-policy-match>" if sourcezone: xpath += "<from>{0}</from>".format(sourcezone) if destinationzone: xpath += "<to>{0}</to>".format(destinationzone) if source: xpath += "<source>{0}</source>".format(source) if destination: xpath += "<destination>{0}</destination>".format(destination) if protocol: xpath += "<protocol>{0}</protocol>".format(protocol) if port: xpath += "<destination-port>{0}</destination-port>".format(port) if application: xpath += "<application>{0}</application>".format(application) if category: xpath += "<category>{0}</category>".format(category) if allrules: xpath += "<show-all>yes</show-all>" xpath += "</security-policy-match></test>" query = {'type': 'op', 'vsys': "vsys{0}".format(vsys), 'cmd': xpath} return __proxy__['panos.call'](query) def unlock_admin(username=None): ''' Unlocks a locked administrator account. username Username of the administrator. CLI Example: .. code-block:: bash salt '*' panos.unlock_admin username=bob ''' if not username: raise CommandExecutionError("Username option must not be none.") query = {'type': 'op', 'cmd': '<set><management-server><unlock><admin>{0}</admin></unlock></management-server>' '</set>'.format(username)} return __proxy__['panos.call'](query)
saltstack/salt
salt/modules/panos.py
set_hostname
python
def set_hostname(hostname=None, deploy=False): ''' Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True ''' if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system', 'element': '<hostname>{0}</hostname>'.format(hostname)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret
Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/panos.py#L1641-L1674
[ "def commit():\n '''\n Commits the candidate configuration to the running configuration.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' panos.commit\n\n '''\n query = {'type': 'commit', 'cmd': '<commit></commit>'}\n\n return _get_job_results(query)\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Palo Alto compatibility to Salt :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix .. versionadded:: 2018.3.0 Configuration ============= This module accepts connection configuration details either as parameters, or as configuration settings in pillar as a Salt proxy. Options passed into opts will be ignored if options are passed into pillar. .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` About ===== This execution module was designed to handle connections to a Palo Alto based firewall. This module adds support to send connections directly to the device through the XML API or through a brokered connection to Panorama. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import Salt Libs from salt.exceptions import CommandExecutionError import salt.proxy.panos import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'panos' def __virtual__(): ''' Will load for the panos proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'panos': return __virtualname__ except KeyError: pass return False, 'The panos execution module can only be loaded for panos proxy minions.' def _get_job_results(query=None): ''' Executes a query that requires a job for completion. This function will wait for the job to complete and return the results. ''' if not query: raise CommandExecutionError("Query parameters cannot be empty.") response = __proxy__['panos.call'](query) # If the response contains a job, we will wait for the results if 'result' in response and 'job' in response['result']: jid = response['result']['job'] while get_job(jid)['result']['job']['status'] != 'FIN': time.sleep(5) return get_job(jid) else: return response def add_config_lock(): ''' Prevent other users from changing configuration until the lock is released. CLI Example: .. code-block:: bash salt '*' panos.add_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><add></add></config-lock></request>'} return __proxy__['panos.call'](query) def check_antivirus(): ''' Get anti-virus information from PaloAlto Networks server CLI Example: .. code-block:: bash salt '*' panos.check_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><check></check></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def check_software(): ''' Get software information from PaloAlto Networks server. CLI Example: .. code-block:: bash salt '*' panos.check_software ''' query = {'type': 'op', 'cmd': '<request><system><software><check></check></software></system></request>'} return __proxy__['panos.call'](query) def clear_commit_tasks(): ''' Clear all commit tasks. CLI Example: .. code-block:: bash salt '*' panos.clear_commit_tasks ''' query = {'type': 'op', 'cmd': '<request><clear-commit-tasks></clear-commit-tasks></request>'} return __proxy__['panos.call'](query) def commit(): ''' Commits the candidate configuration to the running configuration. CLI Example: .. code-block:: bash salt '*' panos.commit ''' query = {'type': 'commit', 'cmd': '<commit></commit>'} return _get_job_results(query) def deactivate_license(key_name=None): ''' Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<request><license><deactivate><key><features><member>{0}</member></features>' '</key></deactivate></license></request>'.format(key_name)} return __proxy__['panos.call'](query) def delete_license(key_name=None): ''' Remove license keys on disk. key_name(str): The file name of the license key to be deleted. CLI Example: .. code-block:: bash salt '*' panos.delete_license key_name=License_File_Name.key ''' if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<delete><license><key>{0}</key></license></delete>'.format(key_name)} return __proxy__['panos.call'](query) def download_antivirus(): ''' Download the most recent anti-virus package. CLI Example: .. code-block:: bash salt '*' panos.download_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><download>' '<latest></latest></download></upgrade></anti-virus></request>'} return _get_job_results(query) def download_software_file(filename=None, synch=False): ''' Download software packages by filename. Args: filename(str): The filename of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_file PanOS_5000-8.0.0 salt '*' panos.download_software_file PanOS_5000-8.0.0 True ''' if not filename: raise CommandExecutionError("Filename option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<file>{0}</file></download></software></system></request>'.format(filename)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<file>{0}</file></download></software></system></request>'.format(filename)} return _get_job_results(query) def download_software_version(version=None, synch=False): ''' Download software packages by version number. Args: version(str): The version of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_version 8.0.0 salt '*' panos.download_software_version 8.0.0 True ''' if not version: raise CommandExecutionError("Version option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<version>{0}</version></download></software></system></request>'.format(version)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<version>{0}</version></download></software></system></request>'.format(version)} return _get_job_results(query) def fetch_license(auth_code=None): ''' Get new license(s) using from the Palo Alto Network Server. auth_code The license authorization code. CLI Example: .. code-block:: bash salt '*' panos.fetch_license salt '*' panos.fetch_license auth_code=foobar ''' if not auth_code: query = {'type': 'op', 'cmd': '<request><license><fetch></fetch></license></request>'} else: query = {'type': 'op', 'cmd': '<request><license><fetch><auth-code>{0}</auth-code></fetch></license>' '</request>'.format(auth_code)} return __proxy__['panos.call'](query) def get_address(address=None, vsys='1'): ''' Get the candidate configuration for the specified get_address object. This will not return address objects that are marked as pre-defined objects. address(str): The name of the address object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address myhost salt '*' panos.get_address myhost 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address/entry[@name=\'{1}\']'.format(vsys, address)} return __proxy__['panos.call'](query) def get_address_group(addressgroup=None, vsys='1'): ''' Get the candidate configuration for the specified address group. This will not return address groups that are marked as pre-defined objects. addressgroup(str): The name of the address group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address_group foobar salt '*' panos.get_address_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address-group/entry[@name=\'{1}\']'.format(vsys, addressgroup)} return __proxy__['panos.call'](query) def get_admins_active(): ''' Show active administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_active ''' query = {'type': 'op', 'cmd': '<show><admins></admins></show>'} return __proxy__['panos.call'](query) def get_admins_all(): ''' Show all administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_all ''' query = {'type': 'op', 'cmd': '<show><admins><all></all></admins></show>'} return __proxy__['panos.call'](query) def get_antivirus_info(): ''' Show information about available anti-virus packages. CLI Example: .. code-block:: bash salt '*' panos.get_antivirus_info ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><info></info></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def get_arp(): ''' Show ARP information. CLI Example: .. code-block:: bash salt '*' panos.get_arp ''' query = {'type': 'op', 'cmd': '<show><arp><entry name = \'all\'/></arp></show>'} return __proxy__['panos.call'](query) def get_cli_idle_timeout(): ''' Show timeout information for this administrative session. CLI Example: .. code-block:: bash salt '*' panos.get_cli_idle_timeout ''' query = {'type': 'op', 'cmd': '<show><cli><idle-timeout></idle-timeout></cli></show>'} return __proxy__['panos.call'](query) def get_cli_permissions(): ''' Show cli administrative permissions. CLI Example: .. code-block:: bash salt '*' panos.get_cli_permissions ''' query = {'type': 'op', 'cmd': '<show><cli><permissions></permissions></cli></show>'} return __proxy__['panos.call'](query) def get_disk_usage(): ''' Report filesystem disk space usage. CLI Example: .. code-block:: bash salt '*' panos.get_disk_usage ''' query = {'type': 'op', 'cmd': '<show><system><disk-space></disk-space></system></show>'} return __proxy__['panos.call'](query) def get_dns_server_config(): ''' Get the DNS server configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_dns_server_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/dns-setting/servers'} return __proxy__['panos.call'](query) def get_domain_config(): ''' Get the domain name configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_domain_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/domain'} return __proxy__['panos.call'](query) def get_dos_blocks(): ''' Show the DoS block-ip table. CLI Example: .. code-block:: bash salt '*' panos.get_dos_blocks ''' query = {'type': 'op', 'cmd': '<show><dos-block-table><all></all></dos-block-table></show>'} return __proxy__['panos.call'](query) def get_fqdn_cache(): ''' Print FQDNs used in rules and their IPs. CLI Example: .. code-block:: bash salt '*' panos.get_fqdn_cache ''' query = {'type': 'op', 'cmd': '<request><system><fqdn><show></show></fqdn></system></request>'} return __proxy__['panos.call'](query) def get_ha_config(): ''' Get the high availability configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ha_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/high-availability'} return __proxy__['panos.call'](query) def get_ha_link(): ''' Show high-availability link-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_link ''' query = {'type': 'op', 'cmd': '<show><high-availability><link-monitoring></link-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_path(): ''' Show high-availability path-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_path ''' query = {'type': 'op', 'cmd': '<show><high-availability><path-monitoring></path-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_state(): ''' Show high-availability state information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_state ''' query = {'type': 'op', 'cmd': '<show><high-availability><state></state></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_transitions(): ''' Show high-availability transition statistic information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_transitions ''' query = {'type': 'op', 'cmd': '<show><high-availability><transitions></transitions></high-availability></show>'} return __proxy__['panos.call'](query) def get_hostname(): ''' Get the hostname of the device. CLI Example: .. code-block:: bash salt '*' panos.get_hostname ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/hostname'} return __proxy__['panos.call'](query) def get_interface_counters(name='all'): ''' Get the counter statistics for interfaces. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interface_counters salt '*' panos.get_interface_counters ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><counter><interface>{0}</interface></counter></show>'.format(name)} return __proxy__['panos.call'](query) def get_interfaces(name='all'): ''' Show interface information. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interfaces salt '*' panos.get_interfaces ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><interface>{0}</interface></show>'.format(name)} return __proxy__['panos.call'](query) def get_job(jid=None): ''' List all a single job by ID. jid The ID of the job to retrieve. CLI Example: .. code-block:: bash salt '*' panos.get_job jid=15 ''' if not jid: raise CommandExecutionError("ID option must not be none.") query = {'type': 'op', 'cmd': '<show><jobs><id>{0}</id></jobs></show>'.format(jid)} return __proxy__['panos.call'](query) def get_jobs(state='all'): ''' List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending ''' if state.lower() == 'all': query = {'type': 'op', 'cmd': '<show><jobs><all></all></jobs></show>'} elif state.lower() == 'pending': query = {'type': 'op', 'cmd': '<show><jobs><pending></pending></jobs></show>'} elif state.lower() == 'processed': query = {'type': 'op', 'cmd': '<show><jobs><processed></processed></jobs></show>'} else: raise CommandExecutionError("The state parameter must be all, pending, or processed.") return __proxy__['panos.call'](query) def get_lacp(): ''' Show LACP state. CLI Example: .. code-block:: bash salt '*' panos.get_lacp ''' query = {'type': 'op', 'cmd': '<show><lacp><aggregate-ethernet>all</aggregate-ethernet></lacp></show>'} return __proxy__['panos.call'](query) def get_license_info(): ''' Show information about owned license(s). CLI Example: .. code-block:: bash salt '*' panos.get_license_info ''' query = {'type': 'op', 'cmd': '<request><license><info></info></license></request>'} return __proxy__['panos.call'](query) def get_license_tokens(): ''' Show license token files for manual license deactivation. CLI Example: .. code-block:: bash salt '*' panos.get_license_tokens ''' query = {'type': 'op', 'cmd': '<show><license-token-files></license-token-files></show>'} return __proxy__['panos.call'](query) def get_lldp_config(): ''' Show lldp config for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_config ''' query = {'type': 'op', 'cmd': '<show><lldp><config>all</config></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_counters(): ''' Show lldp counters for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_counters ''' query = {'type': 'op', 'cmd': '<show><lldp><counters>all</counters></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_local(): ''' Show lldp local info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_local ''' query = {'type': 'op', 'cmd': '<show><lldp><local>all</local></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_neighbors(): ''' Show lldp neighbors info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_neighbors ''' query = {'type': 'op', 'cmd': '<show><lldp><neighbors>all</neighbors></lldp></show>'} return __proxy__['panos.call'](query) def get_local_admins(): ''' Show all local administrator accounts. CLI Example: .. code-block:: bash salt '*' panos.get_local_admins ''' admin_list = get_users_config() response = [] if 'users' not in admin_list['result']: return response if isinstance(admin_list['result']['users']['entry'], list): for entry in admin_list['result']['users']['entry']: response.append(entry['name']) else: response.append(admin_list['result']['users']['entry']['name']) return response def get_logdb_quota(): ''' Report the logdb quotas. CLI Example: .. code-block:: bash salt '*' panos.get_logdb_quota ''' query = {'type': 'op', 'cmd': '<show><system><logdb-quota></logdb-quota></system></show>'} return __proxy__['panos.call'](query) def get_master_key(): ''' Get the master key properties. CLI Example: .. code-block:: bash salt '*' panos.get_master_key ''' query = {'type': 'op', 'cmd': '<show><system><masterkey-properties></masterkey-properties></system></show>'} return __proxy__['panos.call'](query) def get_ntp_config(): ''' Get the NTP configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers'} return __proxy__['panos.call'](query) def get_ntp_servers(): ''' Get list of configured NTP servers. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_servers ''' query = {'type': 'op', 'cmd': '<show><ntp></ntp></show>'} return __proxy__['panos.call'](query) def get_operational_mode(): ''' Show device operational mode setting. CLI Example: .. code-block:: bash salt '*' panos.get_operational_mode ''' query = {'type': 'op', 'cmd': '<show><operational-mode></operational-mode></show>'} return __proxy__['panos.call'](query) def get_panorama_status(): ''' Show panorama connection status. CLI Example: .. code-block:: bash salt '*' panos.get_panorama_status ''' query = {'type': 'op', 'cmd': '<show><panorama-status></panorama-status></show>'} return __proxy__['panos.call'](query) def get_permitted_ips(): ''' Get the IP addresses that are permitted to establish management connections to the device. CLI Example: .. code-block:: bash salt '*' panos.get_permitted_ips ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip'} return __proxy__['panos.call'](query) def get_platform(): ''' Get the platform model information and limitations. CLI Example: .. code-block:: bash salt '*' panos.get_platform ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/platform'} return __proxy__['panos.call'](query) def get_predefined_application(application=None): ''' Get the configuration for the specified pre-defined application object. This will only return pre-defined application objects. application(str): The name of the pre-defined application object. CLI Example: .. code-block:: bash salt '*' panos.get_predefined_application saltstack ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/predefined/application/entry[@name=\'{0}\']'.format(application)} return __proxy__['panos.call'](query) def get_security_rule(rulename=None, vsys='1'): ''' Get the candidate configuration for the specified security rule. rulename(str): The name of the security rule. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_security_rule rule01 salt '*' panos.get_security_rule rule01 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'rulebase/security/rules/entry[@name=\'{1}\']'.format(vsys, rulename)} return __proxy__['panos.call'](query) def get_service(service=None, vsys='1'): ''' Get the candidate configuration for the specified service object. This will not return services that are marked as pre-defined objects. service(str): The name of the service object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service tcp-443 salt '*' panos.get_service tcp-443 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service/entry[@name=\'{1}\']'.format(vsys, service)} return __proxy__['panos.call'](query) def get_service_group(servicegroup=None, vsys='1'): ''' Get the candidate configuration for the specified service group. This will not return service groups that are marked as pre-defined objects. servicegroup(str): The name of the service group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service_group foobar salt '*' panos.get_service_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service-group/entry[@name=\'{1}\']'.format(vsys, servicegroup)} return __proxy__['panos.call'](query) def get_session_info(): ''' Show device session statistics. CLI Example: .. code-block:: bash salt '*' panos.get_session_info ''' query = {'type': 'op', 'cmd': '<show><session><info></info></session></show>'} return __proxy__['panos.call'](query) def get_snmp_config(): ''' Get the SNMP configuration from the device. CLI Example: .. code-block:: bash salt '*' panos.get_snmp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/snmp-setting'} return __proxy__['panos.call'](query) def get_software_info(): ''' Show information about available software packages. CLI Example: .. code-block:: bash salt '*' panos.get_software_info ''' query = {'type': 'op', 'cmd': '<request><system><software><info></info></software></system></request>'} return __proxy__['panos.call'](query) def get_system_date_time(): ''' Get the system date/time. CLI Example: .. code-block:: bash salt '*' panos.get_system_date_time ''' query = {'type': 'op', 'cmd': '<show><clock></clock></show>'} return __proxy__['panos.call'](query) def get_system_files(): ''' List important files in the system. CLI Example: .. code-block:: bash salt '*' panos.get_system_files ''' query = {'type': 'op', 'cmd': '<show><system><files></files></system></show>'} return __proxy__['panos.call'](query) def get_system_info(): ''' Get the system information. CLI Example: .. code-block:: bash salt '*' panos.get_system_info ''' query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'} return __proxy__['panos.call'](query) def get_system_services(): ''' Show system services. CLI Example: .. code-block:: bash salt '*' panos.get_system_services ''' query = {'type': 'op', 'cmd': '<show><system><services></services></system></show>'} return __proxy__['panos.call'](query) def get_system_state(mask=None): ''' Show the system state variables. mask Filters by a subtree or a wildcard. CLI Example: .. code-block:: bash salt '*' panos.get_system_state salt '*' panos.get_system_state mask=cfg.ha.config.enabled salt '*' panos.get_system_state mask=cfg.ha.* ''' if mask: query = {'type': 'op', 'cmd': '<show><system><state><filter>{0}</filter></state></system></show>'.format(mask)} else: query = {'type': 'op', 'cmd': '<show><system><state></state></system></show>'} return __proxy__['panos.call'](query) def get_uncommitted_changes(): ''' Retrieve a list of all uncommitted changes on the device. Requires PANOS version 8.0.0 or greater. CLI Example: .. code-block:: bash salt '*' panos.get_uncommitted_changes ''' _required_version = '8.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) query = {'type': 'op', 'cmd': '<show><config><list><changes></changes></list></config></show>'} return __proxy__['panos.call'](query) def get_users_config(): ''' Get the local administrative user account configuration. CLI Example: .. code-block:: bash salt '*' panos.get_users_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/mgt-config/users'} return __proxy__['panos.call'](query) def get_vlans(): ''' Show all VLAN information. CLI Example: .. code-block:: bash salt '*' panos.get_vlans ''' query = {'type': 'op', 'cmd': '<show><vlan>all</vlan></show>'} return __proxy__['panos.call'](query) def get_xpath(xpath=''): ''' Retrieve a specified xpath from the candidate configuration. xpath(str): The specified xpath in the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_xpath /config/shared/service ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} return __proxy__['panos.call'](query) def get_zone(zone='', vsys='1'): ''' Get the candidate configuration for the specified zone. zone(str): The name of the zone. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zone trust salt '*' panos.get_zone trust 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone/entry[@name=\'{1}\']'.format(vsys, zone)} return __proxy__['panos.call'](query) def get_zones(vsys='1'): ''' Get all the zones in the candidate configuration. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zones salt '*' panos.get_zones 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone'.format(vsys)} return __proxy__['panos.call'](query) def install_antivirus(version=None, latest=False, synch=False, skip_commit=False,): ''' Install anti-virus packages. Args: version(str): The version of the PANOS file to install. latest(bool): If true, the latest anti-virus file will be installed. The specified version option will be ignored. synch(bool): If true, the anti-virus will synch to the peer unit. skip_commit(bool): If true, the install will skip committing to the device. CLI Example: .. code-block:: bash salt '*' panos.install_antivirus 8.0.0 ''' if not version and latest is False: raise CommandExecutionError("Version option must not be none.") if synch is True: s = "yes" else: s = "no" if skip_commit is True: c = "yes" else: c = "no" if latest is True: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>latest</version></install></upgrade></anti-virus></request>'.format(c, s)} else: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>{2}</version></install></upgrade></anti-virus></request>'.format(c, s, version)} return _get_job_results(query) def install_license(): ''' Install the license key(s). CLI Example: .. code-block:: bash salt '*' panos.install_license ''' query = {'type': 'op', 'cmd': '<request><license><install></install></license></request>'} return __proxy__['panos.call'](query) def install_software(version=None): ''' Upgrade to a software package by version. Args: version(str): The version of the PANOS file to install. CLI Example: .. code-block:: bash salt '*' panos.install_license 8.0.0 ''' if not version: raise CommandExecutionError("Version option must not be none.") query = {'type': 'op', 'cmd': '<request><system><software><install>' '<version>{0}</version></install></software></system></request>'.format(version)} return _get_job_results(query) def reboot(): ''' Reboot a running system. CLI Example: .. code-block:: bash salt '*' panos.reboot ''' query = {'type': 'op', 'cmd': '<request><restart><system></system></restart></request>'} return __proxy__['panos.call'](query) def refresh_fqdn_cache(force=False): ''' Force refreshes all FQDNs used in rules. force Forces all fqdn refresh CLI Example: .. code-block:: bash salt '*' panos.refresh_fqdn_cache salt '*' panos.refresh_fqdn_cache force=True ''' if not isinstance(force, bool): raise CommandExecutionError("Force option must be boolean.") if force: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh><force>yes</force></refresh></fqdn></system></request>'} else: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh></refresh></fqdn></system></request>'} return __proxy__['panos.call'](query) def remove_config_lock(): ''' Release config lock previously held. CLI Example: .. code-block:: bash salt '*' panos.remove_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><remove></remove></config-lock></request>'} return __proxy__['panos.call'](query) def resolve_address(address=None, vsys=None): ''' Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com salt '*' panos.resolve_address foo.bar.com vsys=2 ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not address: raise CommandExecutionError("FQDN to resolve must be provided as address.") if not vsys: query = {'type': 'op', 'cmd': '<request><resolve><address>{0}</address></resolve></request>'.format(address)} else: query = {'type': 'op', 'cmd': '<request><resolve><vsys>{0}</vsys><address>{1}</address></resolve>' '</request>'.format(vsys, address)} return __proxy__['panos.call'](query) def save_device_config(filename=None): ''' Save device configuration to a named file. filename The filename to save the configuration to. CLI Example: .. code-block:: bash salt '*' panos.save_device_config foo.xml ''' if not filename: raise CommandExecutionError("Filename must not be empty.") query = {'type': 'op', 'cmd': '<save><config><to>{0}</to></config></save>'.format(filename)} return __proxy__['panos.call'](query) def save_device_state(): ''' Save files needed to restore device to local disk. CLI Example: .. code-block:: bash salt '*' panos.save_device_state ''' query = {'type': 'op', 'cmd': '<save><device-state></device-state></save>'} return __proxy__['panos.call'](query) def set_authentication_profile(profile=None, deploy=False): ''' Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_authentication_profile foo salt '*' panos.set_authentication_profile foo deploy=True ''' if not profile: raise CommandExecutionError("Profile name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/' 'authentication-profile', 'element': '<authentication-profile>{0}</authentication-profile>'.format(profile)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_icmp(enabled=True, deploy=False): ''' Enables or disables the ICMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_icmp salt '*' panos.set_management_icmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-icmp>{0}</disable-icmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_http(enabled=True, deploy=False): ''' Enables or disables the HTTP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_http salt '*' panos.set_management_http enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http>{0}</disable-http>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_https(enabled=True, deploy=False): ''' Enables or disables the HTTPS management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_https salt '*' panos.set_management_https enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-https>{0}</disable-https>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ocsp(enabled=True, deploy=False): ''' Enables or disables the HTTP OCSP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ocsp salt '*' panos.set_management_ocsp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http-ocsp>{0}</disable-http-ocsp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_snmp(enabled=True, deploy=False): ''' Enables or disables the SNMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_snmp salt '*' panos.set_management_snmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-snmp>{0}</disable-snmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ssh(enabled=True, deploy=False): ''' Enables or disables the SSH management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ssh salt '*' panos.set_management_ssh enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-ssh>{0}</disable-ssh>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_telnet(enabled=True, deploy=False): ''' Enables or disables the Telnet management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_telnet salt '*' panos.set_management_telnet enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-telnet>{0}</disable-telnet>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_ntp_authentication(target=None, authentication_type=None, key_id=None, authentication_key=None, algorithm=None, deploy=False): ''' Set the NTP authentication of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: target(str): Determines the target of the authentication. Valid options are primary, secondary, or both. authentication_type(str): The authentication type to be used. Valid options are symmetric, autokey, and none. key_id(int): The NTP authentication key ID. authentication_key(str): The authentication key. algorithm(str): The algorithm type to be used for a symmetric key. Valid options are md5 and sha1. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_authentication target=both authentication_type=autokey salt '*' ntp.set_authentication target=primary authentication_type=none salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 deploy=True ''' ret = {} if target not in ['primary', 'secondary', 'both']: raise salt.exceptions.CommandExecutionError("Target option must be primary, secondary, or both.") if authentication_type not in ['symmetric', 'autokey', 'none']: raise salt.exceptions.CommandExecutionError("Type option must be symmetric, autokey, or both.") if authentication_type == "symmetric" and not authentication_key: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, authentication_key must be " "provided.") if authentication_type == "symmetric" and not key_id: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, key_id must be provided.") if authentication_type == "symmetric" and algorithm not in ['md5', 'sha1']: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, algorithm must be md5 or " "sha1.") if authentication_type == 'symmetric': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'autokey': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'none': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): ''' Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server(str): The secondary NTP server IP address or FQDN. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_servers 0.pool.ntp.org 1.pool.ntp.org salt '*' ntp.set_servers primary_server=0.pool.ntp.org secondary_server=1.pool.ntp.org salt '*' ntp.ser_servers 0.pool.ntp.org 1.pool.ntp.org deploy=True ''' ret = {} if primary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(primary_server)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if secondary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(secondary_server)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_permitted_ip(address=None, deploy=False): ''' Add an IPv4 address or network to the permitted IP list. CLI Example: Args: address (str): The IPv4 address or network to allow access to add to the Palo Alto device. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_permitted_ip 10.0.0.1 salt '*' panos.set_permitted_ip 10.0.0.0/24 salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True ''' if not address: raise CommandExecutionError("Address option must not be empty.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip', 'element': '<entry name=\'{0}\'></entry>'.format(address)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_timezone UTC salt '*' panos.set_timezone UTC deploy=True ''' if not tz: raise CommandExecutionError("Timezone name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/timezone', 'element': '<timezone>{0}</timezone>'.format(tz)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def shutdown(): ''' Shutdown a running system. CLI Example: .. code-block:: bash salt '*' panos.shutdown ''' query = {'type': 'op', 'cmd': '<request><shutdown><system></system></shutdown></request>'} return __proxy__['panos.call'](query) def test_fib_route(ip=None, vr='vr1'): ''' Perform a route lookup within active route table (fib). ip (str): The destination IP address to test. vr (str): The name of the virtual router to test. CLI Example: .. code-block:: bash salt '*' panos.test_fib_route 4.2.2.2 salt '*' panos.test_fib_route 4.2.2.2 my-vr ''' xpath = "<test><routing><fib-lookup>" if ip: xpath += "<ip>{0}</ip>".format(ip) if vr: xpath += "<virtual-router>{0}</virtual-router>".format(vr) xpath += "</fib-lookup></routing></test>" query = {'type': 'op', 'cmd': xpath} return __proxy__['panos.call'](query) def test_security_policy(sourcezone=None, destinationzone=None, source=None, destination=None, protocol=None, port=None, application=None, category=None, vsys='1', allrules=False): ''' Checks which security policy as connection will match on the device. sourcezone (str): The source zone matched against the connection. destinationzone (str): The destination zone matched against the connection. source (str): The source address. This must be a single IP address. destination (str): The destination address. This must be a single IP address. protocol (int): The protocol number for the connection. This is the numerical representation of the protocol. port (int): The port number for the connection. application (str): The application that should be matched. category (str): The category that should be matched. vsys (int): The numerical representation of the VSYS ID. allrules (bool): Show all potential match rules until first allow rule. CLI Example: .. code-block:: bash salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 vsys=2 ''' xpath = "<test><security-policy-match>" if sourcezone: xpath += "<from>{0}</from>".format(sourcezone) if destinationzone: xpath += "<to>{0}</to>".format(destinationzone) if source: xpath += "<source>{0}</source>".format(source) if destination: xpath += "<destination>{0}</destination>".format(destination) if protocol: xpath += "<protocol>{0}</protocol>".format(protocol) if port: xpath += "<destination-port>{0}</destination-port>".format(port) if application: xpath += "<application>{0}</application>".format(application) if category: xpath += "<category>{0}</category>".format(category) if allrules: xpath += "<show-all>yes</show-all>" xpath += "</security-policy-match></test>" query = {'type': 'op', 'vsys': "vsys{0}".format(vsys), 'cmd': xpath} return __proxy__['panos.call'](query) def unlock_admin(username=None): ''' Unlocks a locked administrator account. username Username of the administrator. CLI Example: .. code-block:: bash salt '*' panos.unlock_admin username=bob ''' if not username: raise CommandExecutionError("Username option must not be none.") query = {'type': 'op', 'cmd': '<set><management-server><unlock><admin>{0}</admin></unlock></management-server>' '</set>'.format(username)} return __proxy__['panos.call'](query)
saltstack/salt
salt/modules/panos.py
set_management_icmp
python
def set_management_icmp(enabled=True, deploy=False): ''' Enables or disables the ICMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_icmp salt '*' panos.set_management_icmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-icmp>{0}</disable-icmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret
Enables or disables the ICMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_icmp salt '*' panos.set_management_icmp enabled=False deploy=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/panos.py#L1677-L1714
[ "def commit():\n '''\n Commits the candidate configuration to the running configuration.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' panos.commit\n\n '''\n query = {'type': 'commit', 'cmd': '<commit></commit>'}\n\n return _get_job_results(query)\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Palo Alto compatibility to Salt :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix .. versionadded:: 2018.3.0 Configuration ============= This module accepts connection configuration details either as parameters, or as configuration settings in pillar as a Salt proxy. Options passed into opts will be ignored if options are passed into pillar. .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` About ===== This execution module was designed to handle connections to a Palo Alto based firewall. This module adds support to send connections directly to the device through the XML API or through a brokered connection to Panorama. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import Salt Libs from salt.exceptions import CommandExecutionError import salt.proxy.panos import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'panos' def __virtual__(): ''' Will load for the panos proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'panos': return __virtualname__ except KeyError: pass return False, 'The panos execution module can only be loaded for panos proxy minions.' def _get_job_results(query=None): ''' Executes a query that requires a job for completion. This function will wait for the job to complete and return the results. ''' if not query: raise CommandExecutionError("Query parameters cannot be empty.") response = __proxy__['panos.call'](query) # If the response contains a job, we will wait for the results if 'result' in response and 'job' in response['result']: jid = response['result']['job'] while get_job(jid)['result']['job']['status'] != 'FIN': time.sleep(5) return get_job(jid) else: return response def add_config_lock(): ''' Prevent other users from changing configuration until the lock is released. CLI Example: .. code-block:: bash salt '*' panos.add_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><add></add></config-lock></request>'} return __proxy__['panos.call'](query) def check_antivirus(): ''' Get anti-virus information from PaloAlto Networks server CLI Example: .. code-block:: bash salt '*' panos.check_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><check></check></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def check_software(): ''' Get software information from PaloAlto Networks server. CLI Example: .. code-block:: bash salt '*' panos.check_software ''' query = {'type': 'op', 'cmd': '<request><system><software><check></check></software></system></request>'} return __proxy__['panos.call'](query) def clear_commit_tasks(): ''' Clear all commit tasks. CLI Example: .. code-block:: bash salt '*' panos.clear_commit_tasks ''' query = {'type': 'op', 'cmd': '<request><clear-commit-tasks></clear-commit-tasks></request>'} return __proxy__['panos.call'](query) def commit(): ''' Commits the candidate configuration to the running configuration. CLI Example: .. code-block:: bash salt '*' panos.commit ''' query = {'type': 'commit', 'cmd': '<commit></commit>'} return _get_job_results(query) def deactivate_license(key_name=None): ''' Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<request><license><deactivate><key><features><member>{0}</member></features>' '</key></deactivate></license></request>'.format(key_name)} return __proxy__['panos.call'](query) def delete_license(key_name=None): ''' Remove license keys on disk. key_name(str): The file name of the license key to be deleted. CLI Example: .. code-block:: bash salt '*' panos.delete_license key_name=License_File_Name.key ''' if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<delete><license><key>{0}</key></license></delete>'.format(key_name)} return __proxy__['panos.call'](query) def download_antivirus(): ''' Download the most recent anti-virus package. CLI Example: .. code-block:: bash salt '*' panos.download_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><download>' '<latest></latest></download></upgrade></anti-virus></request>'} return _get_job_results(query) def download_software_file(filename=None, synch=False): ''' Download software packages by filename. Args: filename(str): The filename of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_file PanOS_5000-8.0.0 salt '*' panos.download_software_file PanOS_5000-8.0.0 True ''' if not filename: raise CommandExecutionError("Filename option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<file>{0}</file></download></software></system></request>'.format(filename)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<file>{0}</file></download></software></system></request>'.format(filename)} return _get_job_results(query) def download_software_version(version=None, synch=False): ''' Download software packages by version number. Args: version(str): The version of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_version 8.0.0 salt '*' panos.download_software_version 8.0.0 True ''' if not version: raise CommandExecutionError("Version option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<version>{0}</version></download></software></system></request>'.format(version)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<version>{0}</version></download></software></system></request>'.format(version)} return _get_job_results(query) def fetch_license(auth_code=None): ''' Get new license(s) using from the Palo Alto Network Server. auth_code The license authorization code. CLI Example: .. code-block:: bash salt '*' panos.fetch_license salt '*' panos.fetch_license auth_code=foobar ''' if not auth_code: query = {'type': 'op', 'cmd': '<request><license><fetch></fetch></license></request>'} else: query = {'type': 'op', 'cmd': '<request><license><fetch><auth-code>{0}</auth-code></fetch></license>' '</request>'.format(auth_code)} return __proxy__['panos.call'](query) def get_address(address=None, vsys='1'): ''' Get the candidate configuration for the specified get_address object. This will not return address objects that are marked as pre-defined objects. address(str): The name of the address object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address myhost salt '*' panos.get_address myhost 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address/entry[@name=\'{1}\']'.format(vsys, address)} return __proxy__['panos.call'](query) def get_address_group(addressgroup=None, vsys='1'): ''' Get the candidate configuration for the specified address group. This will not return address groups that are marked as pre-defined objects. addressgroup(str): The name of the address group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address_group foobar salt '*' panos.get_address_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address-group/entry[@name=\'{1}\']'.format(vsys, addressgroup)} return __proxy__['panos.call'](query) def get_admins_active(): ''' Show active administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_active ''' query = {'type': 'op', 'cmd': '<show><admins></admins></show>'} return __proxy__['panos.call'](query) def get_admins_all(): ''' Show all administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_all ''' query = {'type': 'op', 'cmd': '<show><admins><all></all></admins></show>'} return __proxy__['panos.call'](query) def get_antivirus_info(): ''' Show information about available anti-virus packages. CLI Example: .. code-block:: bash salt '*' panos.get_antivirus_info ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><info></info></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def get_arp(): ''' Show ARP information. CLI Example: .. code-block:: bash salt '*' panos.get_arp ''' query = {'type': 'op', 'cmd': '<show><arp><entry name = \'all\'/></arp></show>'} return __proxy__['panos.call'](query) def get_cli_idle_timeout(): ''' Show timeout information for this administrative session. CLI Example: .. code-block:: bash salt '*' panos.get_cli_idle_timeout ''' query = {'type': 'op', 'cmd': '<show><cli><idle-timeout></idle-timeout></cli></show>'} return __proxy__['panos.call'](query) def get_cli_permissions(): ''' Show cli administrative permissions. CLI Example: .. code-block:: bash salt '*' panos.get_cli_permissions ''' query = {'type': 'op', 'cmd': '<show><cli><permissions></permissions></cli></show>'} return __proxy__['panos.call'](query) def get_disk_usage(): ''' Report filesystem disk space usage. CLI Example: .. code-block:: bash salt '*' panos.get_disk_usage ''' query = {'type': 'op', 'cmd': '<show><system><disk-space></disk-space></system></show>'} return __proxy__['panos.call'](query) def get_dns_server_config(): ''' Get the DNS server configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_dns_server_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/dns-setting/servers'} return __proxy__['panos.call'](query) def get_domain_config(): ''' Get the domain name configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_domain_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/domain'} return __proxy__['panos.call'](query) def get_dos_blocks(): ''' Show the DoS block-ip table. CLI Example: .. code-block:: bash salt '*' panos.get_dos_blocks ''' query = {'type': 'op', 'cmd': '<show><dos-block-table><all></all></dos-block-table></show>'} return __proxy__['panos.call'](query) def get_fqdn_cache(): ''' Print FQDNs used in rules and their IPs. CLI Example: .. code-block:: bash salt '*' panos.get_fqdn_cache ''' query = {'type': 'op', 'cmd': '<request><system><fqdn><show></show></fqdn></system></request>'} return __proxy__['panos.call'](query) def get_ha_config(): ''' Get the high availability configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ha_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/high-availability'} return __proxy__['panos.call'](query) def get_ha_link(): ''' Show high-availability link-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_link ''' query = {'type': 'op', 'cmd': '<show><high-availability><link-monitoring></link-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_path(): ''' Show high-availability path-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_path ''' query = {'type': 'op', 'cmd': '<show><high-availability><path-monitoring></path-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_state(): ''' Show high-availability state information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_state ''' query = {'type': 'op', 'cmd': '<show><high-availability><state></state></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_transitions(): ''' Show high-availability transition statistic information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_transitions ''' query = {'type': 'op', 'cmd': '<show><high-availability><transitions></transitions></high-availability></show>'} return __proxy__['panos.call'](query) def get_hostname(): ''' Get the hostname of the device. CLI Example: .. code-block:: bash salt '*' panos.get_hostname ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/hostname'} return __proxy__['panos.call'](query) def get_interface_counters(name='all'): ''' Get the counter statistics for interfaces. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interface_counters salt '*' panos.get_interface_counters ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><counter><interface>{0}</interface></counter></show>'.format(name)} return __proxy__['panos.call'](query) def get_interfaces(name='all'): ''' Show interface information. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interfaces salt '*' panos.get_interfaces ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><interface>{0}</interface></show>'.format(name)} return __proxy__['panos.call'](query) def get_job(jid=None): ''' List all a single job by ID. jid The ID of the job to retrieve. CLI Example: .. code-block:: bash salt '*' panos.get_job jid=15 ''' if not jid: raise CommandExecutionError("ID option must not be none.") query = {'type': 'op', 'cmd': '<show><jobs><id>{0}</id></jobs></show>'.format(jid)} return __proxy__['panos.call'](query) def get_jobs(state='all'): ''' List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending ''' if state.lower() == 'all': query = {'type': 'op', 'cmd': '<show><jobs><all></all></jobs></show>'} elif state.lower() == 'pending': query = {'type': 'op', 'cmd': '<show><jobs><pending></pending></jobs></show>'} elif state.lower() == 'processed': query = {'type': 'op', 'cmd': '<show><jobs><processed></processed></jobs></show>'} else: raise CommandExecutionError("The state parameter must be all, pending, or processed.") return __proxy__['panos.call'](query) def get_lacp(): ''' Show LACP state. CLI Example: .. code-block:: bash salt '*' panos.get_lacp ''' query = {'type': 'op', 'cmd': '<show><lacp><aggregate-ethernet>all</aggregate-ethernet></lacp></show>'} return __proxy__['panos.call'](query) def get_license_info(): ''' Show information about owned license(s). CLI Example: .. code-block:: bash salt '*' panos.get_license_info ''' query = {'type': 'op', 'cmd': '<request><license><info></info></license></request>'} return __proxy__['panos.call'](query) def get_license_tokens(): ''' Show license token files for manual license deactivation. CLI Example: .. code-block:: bash salt '*' panos.get_license_tokens ''' query = {'type': 'op', 'cmd': '<show><license-token-files></license-token-files></show>'} return __proxy__['panos.call'](query) def get_lldp_config(): ''' Show lldp config for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_config ''' query = {'type': 'op', 'cmd': '<show><lldp><config>all</config></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_counters(): ''' Show lldp counters for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_counters ''' query = {'type': 'op', 'cmd': '<show><lldp><counters>all</counters></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_local(): ''' Show lldp local info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_local ''' query = {'type': 'op', 'cmd': '<show><lldp><local>all</local></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_neighbors(): ''' Show lldp neighbors info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_neighbors ''' query = {'type': 'op', 'cmd': '<show><lldp><neighbors>all</neighbors></lldp></show>'} return __proxy__['panos.call'](query) def get_local_admins(): ''' Show all local administrator accounts. CLI Example: .. code-block:: bash salt '*' panos.get_local_admins ''' admin_list = get_users_config() response = [] if 'users' not in admin_list['result']: return response if isinstance(admin_list['result']['users']['entry'], list): for entry in admin_list['result']['users']['entry']: response.append(entry['name']) else: response.append(admin_list['result']['users']['entry']['name']) return response def get_logdb_quota(): ''' Report the logdb quotas. CLI Example: .. code-block:: bash salt '*' panos.get_logdb_quota ''' query = {'type': 'op', 'cmd': '<show><system><logdb-quota></logdb-quota></system></show>'} return __proxy__['panos.call'](query) def get_master_key(): ''' Get the master key properties. CLI Example: .. code-block:: bash salt '*' panos.get_master_key ''' query = {'type': 'op', 'cmd': '<show><system><masterkey-properties></masterkey-properties></system></show>'} return __proxy__['panos.call'](query) def get_ntp_config(): ''' Get the NTP configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers'} return __proxy__['panos.call'](query) def get_ntp_servers(): ''' Get list of configured NTP servers. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_servers ''' query = {'type': 'op', 'cmd': '<show><ntp></ntp></show>'} return __proxy__['panos.call'](query) def get_operational_mode(): ''' Show device operational mode setting. CLI Example: .. code-block:: bash salt '*' panos.get_operational_mode ''' query = {'type': 'op', 'cmd': '<show><operational-mode></operational-mode></show>'} return __proxy__['panos.call'](query) def get_panorama_status(): ''' Show panorama connection status. CLI Example: .. code-block:: bash salt '*' panos.get_panorama_status ''' query = {'type': 'op', 'cmd': '<show><panorama-status></panorama-status></show>'} return __proxy__['panos.call'](query) def get_permitted_ips(): ''' Get the IP addresses that are permitted to establish management connections to the device. CLI Example: .. code-block:: bash salt '*' panos.get_permitted_ips ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip'} return __proxy__['panos.call'](query) def get_platform(): ''' Get the platform model information and limitations. CLI Example: .. code-block:: bash salt '*' panos.get_platform ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/platform'} return __proxy__['panos.call'](query) def get_predefined_application(application=None): ''' Get the configuration for the specified pre-defined application object. This will only return pre-defined application objects. application(str): The name of the pre-defined application object. CLI Example: .. code-block:: bash salt '*' panos.get_predefined_application saltstack ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/predefined/application/entry[@name=\'{0}\']'.format(application)} return __proxy__['panos.call'](query) def get_security_rule(rulename=None, vsys='1'): ''' Get the candidate configuration for the specified security rule. rulename(str): The name of the security rule. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_security_rule rule01 salt '*' panos.get_security_rule rule01 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'rulebase/security/rules/entry[@name=\'{1}\']'.format(vsys, rulename)} return __proxy__['panos.call'](query) def get_service(service=None, vsys='1'): ''' Get the candidate configuration for the specified service object. This will not return services that are marked as pre-defined objects. service(str): The name of the service object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service tcp-443 salt '*' panos.get_service tcp-443 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service/entry[@name=\'{1}\']'.format(vsys, service)} return __proxy__['panos.call'](query) def get_service_group(servicegroup=None, vsys='1'): ''' Get the candidate configuration for the specified service group. This will not return service groups that are marked as pre-defined objects. servicegroup(str): The name of the service group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service_group foobar salt '*' panos.get_service_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service-group/entry[@name=\'{1}\']'.format(vsys, servicegroup)} return __proxy__['panos.call'](query) def get_session_info(): ''' Show device session statistics. CLI Example: .. code-block:: bash salt '*' panos.get_session_info ''' query = {'type': 'op', 'cmd': '<show><session><info></info></session></show>'} return __proxy__['panos.call'](query) def get_snmp_config(): ''' Get the SNMP configuration from the device. CLI Example: .. code-block:: bash salt '*' panos.get_snmp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/snmp-setting'} return __proxy__['panos.call'](query) def get_software_info(): ''' Show information about available software packages. CLI Example: .. code-block:: bash salt '*' panos.get_software_info ''' query = {'type': 'op', 'cmd': '<request><system><software><info></info></software></system></request>'} return __proxy__['panos.call'](query) def get_system_date_time(): ''' Get the system date/time. CLI Example: .. code-block:: bash salt '*' panos.get_system_date_time ''' query = {'type': 'op', 'cmd': '<show><clock></clock></show>'} return __proxy__['panos.call'](query) def get_system_files(): ''' List important files in the system. CLI Example: .. code-block:: bash salt '*' panos.get_system_files ''' query = {'type': 'op', 'cmd': '<show><system><files></files></system></show>'} return __proxy__['panos.call'](query) def get_system_info(): ''' Get the system information. CLI Example: .. code-block:: bash salt '*' panos.get_system_info ''' query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'} return __proxy__['panos.call'](query) def get_system_services(): ''' Show system services. CLI Example: .. code-block:: bash salt '*' panos.get_system_services ''' query = {'type': 'op', 'cmd': '<show><system><services></services></system></show>'} return __proxy__['panos.call'](query) def get_system_state(mask=None): ''' Show the system state variables. mask Filters by a subtree or a wildcard. CLI Example: .. code-block:: bash salt '*' panos.get_system_state salt '*' panos.get_system_state mask=cfg.ha.config.enabled salt '*' panos.get_system_state mask=cfg.ha.* ''' if mask: query = {'type': 'op', 'cmd': '<show><system><state><filter>{0}</filter></state></system></show>'.format(mask)} else: query = {'type': 'op', 'cmd': '<show><system><state></state></system></show>'} return __proxy__['panos.call'](query) def get_uncommitted_changes(): ''' Retrieve a list of all uncommitted changes on the device. Requires PANOS version 8.0.0 or greater. CLI Example: .. code-block:: bash salt '*' panos.get_uncommitted_changes ''' _required_version = '8.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) query = {'type': 'op', 'cmd': '<show><config><list><changes></changes></list></config></show>'} return __proxy__['panos.call'](query) def get_users_config(): ''' Get the local administrative user account configuration. CLI Example: .. code-block:: bash salt '*' panos.get_users_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/mgt-config/users'} return __proxy__['panos.call'](query) def get_vlans(): ''' Show all VLAN information. CLI Example: .. code-block:: bash salt '*' panos.get_vlans ''' query = {'type': 'op', 'cmd': '<show><vlan>all</vlan></show>'} return __proxy__['panos.call'](query) def get_xpath(xpath=''): ''' Retrieve a specified xpath from the candidate configuration. xpath(str): The specified xpath in the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_xpath /config/shared/service ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} return __proxy__['panos.call'](query) def get_zone(zone='', vsys='1'): ''' Get the candidate configuration for the specified zone. zone(str): The name of the zone. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zone trust salt '*' panos.get_zone trust 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone/entry[@name=\'{1}\']'.format(vsys, zone)} return __proxy__['panos.call'](query) def get_zones(vsys='1'): ''' Get all the zones in the candidate configuration. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zones salt '*' panos.get_zones 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone'.format(vsys)} return __proxy__['panos.call'](query) def install_antivirus(version=None, latest=False, synch=False, skip_commit=False,): ''' Install anti-virus packages. Args: version(str): The version of the PANOS file to install. latest(bool): If true, the latest anti-virus file will be installed. The specified version option will be ignored. synch(bool): If true, the anti-virus will synch to the peer unit. skip_commit(bool): If true, the install will skip committing to the device. CLI Example: .. code-block:: bash salt '*' panos.install_antivirus 8.0.0 ''' if not version and latest is False: raise CommandExecutionError("Version option must not be none.") if synch is True: s = "yes" else: s = "no" if skip_commit is True: c = "yes" else: c = "no" if latest is True: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>latest</version></install></upgrade></anti-virus></request>'.format(c, s)} else: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>{2}</version></install></upgrade></anti-virus></request>'.format(c, s, version)} return _get_job_results(query) def install_license(): ''' Install the license key(s). CLI Example: .. code-block:: bash salt '*' panos.install_license ''' query = {'type': 'op', 'cmd': '<request><license><install></install></license></request>'} return __proxy__['panos.call'](query) def install_software(version=None): ''' Upgrade to a software package by version. Args: version(str): The version of the PANOS file to install. CLI Example: .. code-block:: bash salt '*' panos.install_license 8.0.0 ''' if not version: raise CommandExecutionError("Version option must not be none.") query = {'type': 'op', 'cmd': '<request><system><software><install>' '<version>{0}</version></install></software></system></request>'.format(version)} return _get_job_results(query) def reboot(): ''' Reboot a running system. CLI Example: .. code-block:: bash salt '*' panos.reboot ''' query = {'type': 'op', 'cmd': '<request><restart><system></system></restart></request>'} return __proxy__['panos.call'](query) def refresh_fqdn_cache(force=False): ''' Force refreshes all FQDNs used in rules. force Forces all fqdn refresh CLI Example: .. code-block:: bash salt '*' panos.refresh_fqdn_cache salt '*' panos.refresh_fqdn_cache force=True ''' if not isinstance(force, bool): raise CommandExecutionError("Force option must be boolean.") if force: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh><force>yes</force></refresh></fqdn></system></request>'} else: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh></refresh></fqdn></system></request>'} return __proxy__['panos.call'](query) def remove_config_lock(): ''' Release config lock previously held. CLI Example: .. code-block:: bash salt '*' panos.remove_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><remove></remove></config-lock></request>'} return __proxy__['panos.call'](query) def resolve_address(address=None, vsys=None): ''' Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com salt '*' panos.resolve_address foo.bar.com vsys=2 ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not address: raise CommandExecutionError("FQDN to resolve must be provided as address.") if not vsys: query = {'type': 'op', 'cmd': '<request><resolve><address>{0}</address></resolve></request>'.format(address)} else: query = {'type': 'op', 'cmd': '<request><resolve><vsys>{0}</vsys><address>{1}</address></resolve>' '</request>'.format(vsys, address)} return __proxy__['panos.call'](query) def save_device_config(filename=None): ''' Save device configuration to a named file. filename The filename to save the configuration to. CLI Example: .. code-block:: bash salt '*' panos.save_device_config foo.xml ''' if not filename: raise CommandExecutionError("Filename must not be empty.") query = {'type': 'op', 'cmd': '<save><config><to>{0}</to></config></save>'.format(filename)} return __proxy__['panos.call'](query) def save_device_state(): ''' Save files needed to restore device to local disk. CLI Example: .. code-block:: bash salt '*' panos.save_device_state ''' query = {'type': 'op', 'cmd': '<save><device-state></device-state></save>'} return __proxy__['panos.call'](query) def set_authentication_profile(profile=None, deploy=False): ''' Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_authentication_profile foo salt '*' panos.set_authentication_profile foo deploy=True ''' if not profile: raise CommandExecutionError("Profile name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/' 'authentication-profile', 'element': '<authentication-profile>{0}</authentication-profile>'.format(profile)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_hostname(hostname=None, deploy=False): ''' Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True ''' if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system', 'element': '<hostname>{0}</hostname>'.format(hostname)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_http(enabled=True, deploy=False): ''' Enables or disables the HTTP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_http salt '*' panos.set_management_http enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http>{0}</disable-http>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_https(enabled=True, deploy=False): ''' Enables or disables the HTTPS management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_https salt '*' panos.set_management_https enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-https>{0}</disable-https>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ocsp(enabled=True, deploy=False): ''' Enables or disables the HTTP OCSP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ocsp salt '*' panos.set_management_ocsp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http-ocsp>{0}</disable-http-ocsp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_snmp(enabled=True, deploy=False): ''' Enables or disables the SNMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_snmp salt '*' panos.set_management_snmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-snmp>{0}</disable-snmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ssh(enabled=True, deploy=False): ''' Enables or disables the SSH management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ssh salt '*' panos.set_management_ssh enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-ssh>{0}</disable-ssh>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_telnet(enabled=True, deploy=False): ''' Enables or disables the Telnet management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_telnet salt '*' panos.set_management_telnet enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-telnet>{0}</disable-telnet>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_ntp_authentication(target=None, authentication_type=None, key_id=None, authentication_key=None, algorithm=None, deploy=False): ''' Set the NTP authentication of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: target(str): Determines the target of the authentication. Valid options are primary, secondary, or both. authentication_type(str): The authentication type to be used. Valid options are symmetric, autokey, and none. key_id(int): The NTP authentication key ID. authentication_key(str): The authentication key. algorithm(str): The algorithm type to be used for a symmetric key. Valid options are md5 and sha1. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_authentication target=both authentication_type=autokey salt '*' ntp.set_authentication target=primary authentication_type=none salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 deploy=True ''' ret = {} if target not in ['primary', 'secondary', 'both']: raise salt.exceptions.CommandExecutionError("Target option must be primary, secondary, or both.") if authentication_type not in ['symmetric', 'autokey', 'none']: raise salt.exceptions.CommandExecutionError("Type option must be symmetric, autokey, or both.") if authentication_type == "symmetric" and not authentication_key: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, authentication_key must be " "provided.") if authentication_type == "symmetric" and not key_id: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, key_id must be provided.") if authentication_type == "symmetric" and algorithm not in ['md5', 'sha1']: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, algorithm must be md5 or " "sha1.") if authentication_type == 'symmetric': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'autokey': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'none': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): ''' Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server(str): The secondary NTP server IP address or FQDN. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_servers 0.pool.ntp.org 1.pool.ntp.org salt '*' ntp.set_servers primary_server=0.pool.ntp.org secondary_server=1.pool.ntp.org salt '*' ntp.ser_servers 0.pool.ntp.org 1.pool.ntp.org deploy=True ''' ret = {} if primary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(primary_server)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if secondary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(secondary_server)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_permitted_ip(address=None, deploy=False): ''' Add an IPv4 address or network to the permitted IP list. CLI Example: Args: address (str): The IPv4 address or network to allow access to add to the Palo Alto device. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_permitted_ip 10.0.0.1 salt '*' panos.set_permitted_ip 10.0.0.0/24 salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True ''' if not address: raise CommandExecutionError("Address option must not be empty.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip', 'element': '<entry name=\'{0}\'></entry>'.format(address)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_timezone UTC salt '*' panos.set_timezone UTC deploy=True ''' if not tz: raise CommandExecutionError("Timezone name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/timezone', 'element': '<timezone>{0}</timezone>'.format(tz)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def shutdown(): ''' Shutdown a running system. CLI Example: .. code-block:: bash salt '*' panos.shutdown ''' query = {'type': 'op', 'cmd': '<request><shutdown><system></system></shutdown></request>'} return __proxy__['panos.call'](query) def test_fib_route(ip=None, vr='vr1'): ''' Perform a route lookup within active route table (fib). ip (str): The destination IP address to test. vr (str): The name of the virtual router to test. CLI Example: .. code-block:: bash salt '*' panos.test_fib_route 4.2.2.2 salt '*' panos.test_fib_route 4.2.2.2 my-vr ''' xpath = "<test><routing><fib-lookup>" if ip: xpath += "<ip>{0}</ip>".format(ip) if vr: xpath += "<virtual-router>{0}</virtual-router>".format(vr) xpath += "</fib-lookup></routing></test>" query = {'type': 'op', 'cmd': xpath} return __proxy__['panos.call'](query) def test_security_policy(sourcezone=None, destinationzone=None, source=None, destination=None, protocol=None, port=None, application=None, category=None, vsys='1', allrules=False): ''' Checks which security policy as connection will match on the device. sourcezone (str): The source zone matched against the connection. destinationzone (str): The destination zone matched against the connection. source (str): The source address. This must be a single IP address. destination (str): The destination address. This must be a single IP address. protocol (int): The protocol number for the connection. This is the numerical representation of the protocol. port (int): The port number for the connection. application (str): The application that should be matched. category (str): The category that should be matched. vsys (int): The numerical representation of the VSYS ID. allrules (bool): Show all potential match rules until first allow rule. CLI Example: .. code-block:: bash salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 vsys=2 ''' xpath = "<test><security-policy-match>" if sourcezone: xpath += "<from>{0}</from>".format(sourcezone) if destinationzone: xpath += "<to>{0}</to>".format(destinationzone) if source: xpath += "<source>{0}</source>".format(source) if destination: xpath += "<destination>{0}</destination>".format(destination) if protocol: xpath += "<protocol>{0}</protocol>".format(protocol) if port: xpath += "<destination-port>{0}</destination-port>".format(port) if application: xpath += "<application>{0}</application>".format(application) if category: xpath += "<category>{0}</category>".format(category) if allrules: xpath += "<show-all>yes</show-all>" xpath += "</security-policy-match></test>" query = {'type': 'op', 'vsys': "vsys{0}".format(vsys), 'cmd': xpath} return __proxy__['panos.call'](query) def unlock_admin(username=None): ''' Unlocks a locked administrator account. username Username of the administrator. CLI Example: .. code-block:: bash salt '*' panos.unlock_admin username=bob ''' if not username: raise CommandExecutionError("Username option must not be none.") query = {'type': 'op', 'cmd': '<set><management-server><unlock><admin>{0}</admin></unlock></management-server>' '</set>'.format(username)} return __proxy__['panos.call'](query)
saltstack/salt
salt/modules/panos.py
set_ntp_authentication
python
def set_ntp_authentication(target=None, authentication_type=None, key_id=None, authentication_key=None, algorithm=None, deploy=False): ''' Set the NTP authentication of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: target(str): Determines the target of the authentication. Valid options are primary, secondary, or both. authentication_type(str): The authentication type to be used. Valid options are symmetric, autokey, and none. key_id(int): The NTP authentication key ID. authentication_key(str): The authentication key. algorithm(str): The algorithm type to be used for a symmetric key. Valid options are md5 and sha1. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_authentication target=both authentication_type=autokey salt '*' ntp.set_authentication target=primary authentication_type=none salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 deploy=True ''' ret = {} if target not in ['primary', 'secondary', 'both']: raise salt.exceptions.CommandExecutionError("Target option must be primary, secondary, or both.") if authentication_type not in ['symmetric', 'autokey', 'none']: raise salt.exceptions.CommandExecutionError("Type option must be symmetric, autokey, or both.") if authentication_type == "symmetric" and not authentication_key: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, authentication_key must be " "provided.") if authentication_type == "symmetric" and not key_id: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, key_id must be provided.") if authentication_type == "symmetric" and algorithm not in ['md5', 'sha1']: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, algorithm must be md5 or " "sha1.") if authentication_type == 'symmetric': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'autokey': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'none': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret
Set the NTP authentication of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: target(str): Determines the target of the authentication. Valid options are primary, secondary, or both. authentication_type(str): The authentication type to be used. Valid options are symmetric, autokey, and none. key_id(int): The NTP authentication key ID. authentication_key(str): The authentication key. algorithm(str): The algorithm type to be used for a symmetric key. Valid options are md5 and sha1. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_authentication target=both authentication_type=autokey salt '*' ntp.set_authentication target=primary authentication_type=none salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 deploy=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/panos.py#L1957-L2066
[ "def commit():\n '''\n Commits the candidate configuration to the running configuration.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' panos.commit\n\n '''\n query = {'type': 'commit', 'cmd': '<commit></commit>'}\n\n return _get_job_results(query)\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Palo Alto compatibility to Salt :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix .. versionadded:: 2018.3.0 Configuration ============= This module accepts connection configuration details either as parameters, or as configuration settings in pillar as a Salt proxy. Options passed into opts will be ignored if options are passed into pillar. .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` About ===== This execution module was designed to handle connections to a Palo Alto based firewall. This module adds support to send connections directly to the device through the XML API or through a brokered connection to Panorama. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import Salt Libs from salt.exceptions import CommandExecutionError import salt.proxy.panos import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'panos' def __virtual__(): ''' Will load for the panos proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'panos': return __virtualname__ except KeyError: pass return False, 'The panos execution module can only be loaded for panos proxy minions.' def _get_job_results(query=None): ''' Executes a query that requires a job for completion. This function will wait for the job to complete and return the results. ''' if not query: raise CommandExecutionError("Query parameters cannot be empty.") response = __proxy__['panos.call'](query) # If the response contains a job, we will wait for the results if 'result' in response and 'job' in response['result']: jid = response['result']['job'] while get_job(jid)['result']['job']['status'] != 'FIN': time.sleep(5) return get_job(jid) else: return response def add_config_lock(): ''' Prevent other users from changing configuration until the lock is released. CLI Example: .. code-block:: bash salt '*' panos.add_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><add></add></config-lock></request>'} return __proxy__['panos.call'](query) def check_antivirus(): ''' Get anti-virus information from PaloAlto Networks server CLI Example: .. code-block:: bash salt '*' panos.check_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><check></check></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def check_software(): ''' Get software information from PaloAlto Networks server. CLI Example: .. code-block:: bash salt '*' panos.check_software ''' query = {'type': 'op', 'cmd': '<request><system><software><check></check></software></system></request>'} return __proxy__['panos.call'](query) def clear_commit_tasks(): ''' Clear all commit tasks. CLI Example: .. code-block:: bash salt '*' panos.clear_commit_tasks ''' query = {'type': 'op', 'cmd': '<request><clear-commit-tasks></clear-commit-tasks></request>'} return __proxy__['panos.call'](query) def commit(): ''' Commits the candidate configuration to the running configuration. CLI Example: .. code-block:: bash salt '*' panos.commit ''' query = {'type': 'commit', 'cmd': '<commit></commit>'} return _get_job_results(query) def deactivate_license(key_name=None): ''' Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<request><license><deactivate><key><features><member>{0}</member></features>' '</key></deactivate></license></request>'.format(key_name)} return __proxy__['panos.call'](query) def delete_license(key_name=None): ''' Remove license keys on disk. key_name(str): The file name of the license key to be deleted. CLI Example: .. code-block:: bash salt '*' panos.delete_license key_name=License_File_Name.key ''' if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<delete><license><key>{0}</key></license></delete>'.format(key_name)} return __proxy__['panos.call'](query) def download_antivirus(): ''' Download the most recent anti-virus package. CLI Example: .. code-block:: bash salt '*' panos.download_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><download>' '<latest></latest></download></upgrade></anti-virus></request>'} return _get_job_results(query) def download_software_file(filename=None, synch=False): ''' Download software packages by filename. Args: filename(str): The filename of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_file PanOS_5000-8.0.0 salt '*' panos.download_software_file PanOS_5000-8.0.0 True ''' if not filename: raise CommandExecutionError("Filename option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<file>{0}</file></download></software></system></request>'.format(filename)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<file>{0}</file></download></software></system></request>'.format(filename)} return _get_job_results(query) def download_software_version(version=None, synch=False): ''' Download software packages by version number. Args: version(str): The version of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_version 8.0.0 salt '*' panos.download_software_version 8.0.0 True ''' if not version: raise CommandExecutionError("Version option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<version>{0}</version></download></software></system></request>'.format(version)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<version>{0}</version></download></software></system></request>'.format(version)} return _get_job_results(query) def fetch_license(auth_code=None): ''' Get new license(s) using from the Palo Alto Network Server. auth_code The license authorization code. CLI Example: .. code-block:: bash salt '*' panos.fetch_license salt '*' panos.fetch_license auth_code=foobar ''' if not auth_code: query = {'type': 'op', 'cmd': '<request><license><fetch></fetch></license></request>'} else: query = {'type': 'op', 'cmd': '<request><license><fetch><auth-code>{0}</auth-code></fetch></license>' '</request>'.format(auth_code)} return __proxy__['panos.call'](query) def get_address(address=None, vsys='1'): ''' Get the candidate configuration for the specified get_address object. This will not return address objects that are marked as pre-defined objects. address(str): The name of the address object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address myhost salt '*' panos.get_address myhost 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address/entry[@name=\'{1}\']'.format(vsys, address)} return __proxy__['panos.call'](query) def get_address_group(addressgroup=None, vsys='1'): ''' Get the candidate configuration for the specified address group. This will not return address groups that are marked as pre-defined objects. addressgroup(str): The name of the address group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address_group foobar salt '*' panos.get_address_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address-group/entry[@name=\'{1}\']'.format(vsys, addressgroup)} return __proxy__['panos.call'](query) def get_admins_active(): ''' Show active administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_active ''' query = {'type': 'op', 'cmd': '<show><admins></admins></show>'} return __proxy__['panos.call'](query) def get_admins_all(): ''' Show all administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_all ''' query = {'type': 'op', 'cmd': '<show><admins><all></all></admins></show>'} return __proxy__['panos.call'](query) def get_antivirus_info(): ''' Show information about available anti-virus packages. CLI Example: .. code-block:: bash salt '*' panos.get_antivirus_info ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><info></info></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def get_arp(): ''' Show ARP information. CLI Example: .. code-block:: bash salt '*' panos.get_arp ''' query = {'type': 'op', 'cmd': '<show><arp><entry name = \'all\'/></arp></show>'} return __proxy__['panos.call'](query) def get_cli_idle_timeout(): ''' Show timeout information for this administrative session. CLI Example: .. code-block:: bash salt '*' panos.get_cli_idle_timeout ''' query = {'type': 'op', 'cmd': '<show><cli><idle-timeout></idle-timeout></cli></show>'} return __proxy__['panos.call'](query) def get_cli_permissions(): ''' Show cli administrative permissions. CLI Example: .. code-block:: bash salt '*' panos.get_cli_permissions ''' query = {'type': 'op', 'cmd': '<show><cli><permissions></permissions></cli></show>'} return __proxy__['panos.call'](query) def get_disk_usage(): ''' Report filesystem disk space usage. CLI Example: .. code-block:: bash salt '*' panos.get_disk_usage ''' query = {'type': 'op', 'cmd': '<show><system><disk-space></disk-space></system></show>'} return __proxy__['panos.call'](query) def get_dns_server_config(): ''' Get the DNS server configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_dns_server_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/dns-setting/servers'} return __proxy__['panos.call'](query) def get_domain_config(): ''' Get the domain name configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_domain_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/domain'} return __proxy__['panos.call'](query) def get_dos_blocks(): ''' Show the DoS block-ip table. CLI Example: .. code-block:: bash salt '*' panos.get_dos_blocks ''' query = {'type': 'op', 'cmd': '<show><dos-block-table><all></all></dos-block-table></show>'} return __proxy__['panos.call'](query) def get_fqdn_cache(): ''' Print FQDNs used in rules and their IPs. CLI Example: .. code-block:: bash salt '*' panos.get_fqdn_cache ''' query = {'type': 'op', 'cmd': '<request><system><fqdn><show></show></fqdn></system></request>'} return __proxy__['panos.call'](query) def get_ha_config(): ''' Get the high availability configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ha_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/high-availability'} return __proxy__['panos.call'](query) def get_ha_link(): ''' Show high-availability link-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_link ''' query = {'type': 'op', 'cmd': '<show><high-availability><link-monitoring></link-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_path(): ''' Show high-availability path-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_path ''' query = {'type': 'op', 'cmd': '<show><high-availability><path-monitoring></path-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_state(): ''' Show high-availability state information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_state ''' query = {'type': 'op', 'cmd': '<show><high-availability><state></state></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_transitions(): ''' Show high-availability transition statistic information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_transitions ''' query = {'type': 'op', 'cmd': '<show><high-availability><transitions></transitions></high-availability></show>'} return __proxy__['panos.call'](query) def get_hostname(): ''' Get the hostname of the device. CLI Example: .. code-block:: bash salt '*' panos.get_hostname ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/hostname'} return __proxy__['panos.call'](query) def get_interface_counters(name='all'): ''' Get the counter statistics for interfaces. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interface_counters salt '*' panos.get_interface_counters ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><counter><interface>{0}</interface></counter></show>'.format(name)} return __proxy__['panos.call'](query) def get_interfaces(name='all'): ''' Show interface information. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interfaces salt '*' panos.get_interfaces ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><interface>{0}</interface></show>'.format(name)} return __proxy__['panos.call'](query) def get_job(jid=None): ''' List all a single job by ID. jid The ID of the job to retrieve. CLI Example: .. code-block:: bash salt '*' panos.get_job jid=15 ''' if not jid: raise CommandExecutionError("ID option must not be none.") query = {'type': 'op', 'cmd': '<show><jobs><id>{0}</id></jobs></show>'.format(jid)} return __proxy__['panos.call'](query) def get_jobs(state='all'): ''' List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending ''' if state.lower() == 'all': query = {'type': 'op', 'cmd': '<show><jobs><all></all></jobs></show>'} elif state.lower() == 'pending': query = {'type': 'op', 'cmd': '<show><jobs><pending></pending></jobs></show>'} elif state.lower() == 'processed': query = {'type': 'op', 'cmd': '<show><jobs><processed></processed></jobs></show>'} else: raise CommandExecutionError("The state parameter must be all, pending, or processed.") return __proxy__['panos.call'](query) def get_lacp(): ''' Show LACP state. CLI Example: .. code-block:: bash salt '*' panos.get_lacp ''' query = {'type': 'op', 'cmd': '<show><lacp><aggregate-ethernet>all</aggregate-ethernet></lacp></show>'} return __proxy__['panos.call'](query) def get_license_info(): ''' Show information about owned license(s). CLI Example: .. code-block:: bash salt '*' panos.get_license_info ''' query = {'type': 'op', 'cmd': '<request><license><info></info></license></request>'} return __proxy__['panos.call'](query) def get_license_tokens(): ''' Show license token files for manual license deactivation. CLI Example: .. code-block:: bash salt '*' panos.get_license_tokens ''' query = {'type': 'op', 'cmd': '<show><license-token-files></license-token-files></show>'} return __proxy__['panos.call'](query) def get_lldp_config(): ''' Show lldp config for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_config ''' query = {'type': 'op', 'cmd': '<show><lldp><config>all</config></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_counters(): ''' Show lldp counters for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_counters ''' query = {'type': 'op', 'cmd': '<show><lldp><counters>all</counters></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_local(): ''' Show lldp local info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_local ''' query = {'type': 'op', 'cmd': '<show><lldp><local>all</local></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_neighbors(): ''' Show lldp neighbors info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_neighbors ''' query = {'type': 'op', 'cmd': '<show><lldp><neighbors>all</neighbors></lldp></show>'} return __proxy__['panos.call'](query) def get_local_admins(): ''' Show all local administrator accounts. CLI Example: .. code-block:: bash salt '*' panos.get_local_admins ''' admin_list = get_users_config() response = [] if 'users' not in admin_list['result']: return response if isinstance(admin_list['result']['users']['entry'], list): for entry in admin_list['result']['users']['entry']: response.append(entry['name']) else: response.append(admin_list['result']['users']['entry']['name']) return response def get_logdb_quota(): ''' Report the logdb quotas. CLI Example: .. code-block:: bash salt '*' panos.get_logdb_quota ''' query = {'type': 'op', 'cmd': '<show><system><logdb-quota></logdb-quota></system></show>'} return __proxy__['panos.call'](query) def get_master_key(): ''' Get the master key properties. CLI Example: .. code-block:: bash salt '*' panos.get_master_key ''' query = {'type': 'op', 'cmd': '<show><system><masterkey-properties></masterkey-properties></system></show>'} return __proxy__['panos.call'](query) def get_ntp_config(): ''' Get the NTP configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers'} return __proxy__['panos.call'](query) def get_ntp_servers(): ''' Get list of configured NTP servers. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_servers ''' query = {'type': 'op', 'cmd': '<show><ntp></ntp></show>'} return __proxy__['panos.call'](query) def get_operational_mode(): ''' Show device operational mode setting. CLI Example: .. code-block:: bash salt '*' panos.get_operational_mode ''' query = {'type': 'op', 'cmd': '<show><operational-mode></operational-mode></show>'} return __proxy__['panos.call'](query) def get_panorama_status(): ''' Show panorama connection status. CLI Example: .. code-block:: bash salt '*' panos.get_panorama_status ''' query = {'type': 'op', 'cmd': '<show><panorama-status></panorama-status></show>'} return __proxy__['panos.call'](query) def get_permitted_ips(): ''' Get the IP addresses that are permitted to establish management connections to the device. CLI Example: .. code-block:: bash salt '*' panos.get_permitted_ips ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip'} return __proxy__['panos.call'](query) def get_platform(): ''' Get the platform model information and limitations. CLI Example: .. code-block:: bash salt '*' panos.get_platform ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/platform'} return __proxy__['panos.call'](query) def get_predefined_application(application=None): ''' Get the configuration for the specified pre-defined application object. This will only return pre-defined application objects. application(str): The name of the pre-defined application object. CLI Example: .. code-block:: bash salt '*' panos.get_predefined_application saltstack ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/predefined/application/entry[@name=\'{0}\']'.format(application)} return __proxy__['panos.call'](query) def get_security_rule(rulename=None, vsys='1'): ''' Get the candidate configuration for the specified security rule. rulename(str): The name of the security rule. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_security_rule rule01 salt '*' panos.get_security_rule rule01 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'rulebase/security/rules/entry[@name=\'{1}\']'.format(vsys, rulename)} return __proxy__['panos.call'](query) def get_service(service=None, vsys='1'): ''' Get the candidate configuration for the specified service object. This will not return services that are marked as pre-defined objects. service(str): The name of the service object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service tcp-443 salt '*' panos.get_service tcp-443 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service/entry[@name=\'{1}\']'.format(vsys, service)} return __proxy__['panos.call'](query) def get_service_group(servicegroup=None, vsys='1'): ''' Get the candidate configuration for the specified service group. This will not return service groups that are marked as pre-defined objects. servicegroup(str): The name of the service group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service_group foobar salt '*' panos.get_service_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service-group/entry[@name=\'{1}\']'.format(vsys, servicegroup)} return __proxy__['panos.call'](query) def get_session_info(): ''' Show device session statistics. CLI Example: .. code-block:: bash salt '*' panos.get_session_info ''' query = {'type': 'op', 'cmd': '<show><session><info></info></session></show>'} return __proxy__['panos.call'](query) def get_snmp_config(): ''' Get the SNMP configuration from the device. CLI Example: .. code-block:: bash salt '*' panos.get_snmp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/snmp-setting'} return __proxy__['panos.call'](query) def get_software_info(): ''' Show information about available software packages. CLI Example: .. code-block:: bash salt '*' panos.get_software_info ''' query = {'type': 'op', 'cmd': '<request><system><software><info></info></software></system></request>'} return __proxy__['panos.call'](query) def get_system_date_time(): ''' Get the system date/time. CLI Example: .. code-block:: bash salt '*' panos.get_system_date_time ''' query = {'type': 'op', 'cmd': '<show><clock></clock></show>'} return __proxy__['panos.call'](query) def get_system_files(): ''' List important files in the system. CLI Example: .. code-block:: bash salt '*' panos.get_system_files ''' query = {'type': 'op', 'cmd': '<show><system><files></files></system></show>'} return __proxy__['panos.call'](query) def get_system_info(): ''' Get the system information. CLI Example: .. code-block:: bash salt '*' panos.get_system_info ''' query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'} return __proxy__['panos.call'](query) def get_system_services(): ''' Show system services. CLI Example: .. code-block:: bash salt '*' panos.get_system_services ''' query = {'type': 'op', 'cmd': '<show><system><services></services></system></show>'} return __proxy__['panos.call'](query) def get_system_state(mask=None): ''' Show the system state variables. mask Filters by a subtree or a wildcard. CLI Example: .. code-block:: bash salt '*' panos.get_system_state salt '*' panos.get_system_state mask=cfg.ha.config.enabled salt '*' panos.get_system_state mask=cfg.ha.* ''' if mask: query = {'type': 'op', 'cmd': '<show><system><state><filter>{0}</filter></state></system></show>'.format(mask)} else: query = {'type': 'op', 'cmd': '<show><system><state></state></system></show>'} return __proxy__['panos.call'](query) def get_uncommitted_changes(): ''' Retrieve a list of all uncommitted changes on the device. Requires PANOS version 8.0.0 or greater. CLI Example: .. code-block:: bash salt '*' panos.get_uncommitted_changes ''' _required_version = '8.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) query = {'type': 'op', 'cmd': '<show><config><list><changes></changes></list></config></show>'} return __proxy__['panos.call'](query) def get_users_config(): ''' Get the local administrative user account configuration. CLI Example: .. code-block:: bash salt '*' panos.get_users_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/mgt-config/users'} return __proxy__['panos.call'](query) def get_vlans(): ''' Show all VLAN information. CLI Example: .. code-block:: bash salt '*' panos.get_vlans ''' query = {'type': 'op', 'cmd': '<show><vlan>all</vlan></show>'} return __proxy__['panos.call'](query) def get_xpath(xpath=''): ''' Retrieve a specified xpath from the candidate configuration. xpath(str): The specified xpath in the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_xpath /config/shared/service ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} return __proxy__['panos.call'](query) def get_zone(zone='', vsys='1'): ''' Get the candidate configuration for the specified zone. zone(str): The name of the zone. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zone trust salt '*' panos.get_zone trust 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone/entry[@name=\'{1}\']'.format(vsys, zone)} return __proxy__['panos.call'](query) def get_zones(vsys='1'): ''' Get all the zones in the candidate configuration. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zones salt '*' panos.get_zones 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone'.format(vsys)} return __proxy__['panos.call'](query) def install_antivirus(version=None, latest=False, synch=False, skip_commit=False,): ''' Install anti-virus packages. Args: version(str): The version of the PANOS file to install. latest(bool): If true, the latest anti-virus file will be installed. The specified version option will be ignored. synch(bool): If true, the anti-virus will synch to the peer unit. skip_commit(bool): If true, the install will skip committing to the device. CLI Example: .. code-block:: bash salt '*' panos.install_antivirus 8.0.0 ''' if not version and latest is False: raise CommandExecutionError("Version option must not be none.") if synch is True: s = "yes" else: s = "no" if skip_commit is True: c = "yes" else: c = "no" if latest is True: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>latest</version></install></upgrade></anti-virus></request>'.format(c, s)} else: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>{2}</version></install></upgrade></anti-virus></request>'.format(c, s, version)} return _get_job_results(query) def install_license(): ''' Install the license key(s). CLI Example: .. code-block:: bash salt '*' panos.install_license ''' query = {'type': 'op', 'cmd': '<request><license><install></install></license></request>'} return __proxy__['panos.call'](query) def install_software(version=None): ''' Upgrade to a software package by version. Args: version(str): The version of the PANOS file to install. CLI Example: .. code-block:: bash salt '*' panos.install_license 8.0.0 ''' if not version: raise CommandExecutionError("Version option must not be none.") query = {'type': 'op', 'cmd': '<request><system><software><install>' '<version>{0}</version></install></software></system></request>'.format(version)} return _get_job_results(query) def reboot(): ''' Reboot a running system. CLI Example: .. code-block:: bash salt '*' panos.reboot ''' query = {'type': 'op', 'cmd': '<request><restart><system></system></restart></request>'} return __proxy__['panos.call'](query) def refresh_fqdn_cache(force=False): ''' Force refreshes all FQDNs used in rules. force Forces all fqdn refresh CLI Example: .. code-block:: bash salt '*' panos.refresh_fqdn_cache salt '*' panos.refresh_fqdn_cache force=True ''' if not isinstance(force, bool): raise CommandExecutionError("Force option must be boolean.") if force: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh><force>yes</force></refresh></fqdn></system></request>'} else: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh></refresh></fqdn></system></request>'} return __proxy__['panos.call'](query) def remove_config_lock(): ''' Release config lock previously held. CLI Example: .. code-block:: bash salt '*' panos.remove_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><remove></remove></config-lock></request>'} return __proxy__['panos.call'](query) def resolve_address(address=None, vsys=None): ''' Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com salt '*' panos.resolve_address foo.bar.com vsys=2 ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not address: raise CommandExecutionError("FQDN to resolve must be provided as address.") if not vsys: query = {'type': 'op', 'cmd': '<request><resolve><address>{0}</address></resolve></request>'.format(address)} else: query = {'type': 'op', 'cmd': '<request><resolve><vsys>{0}</vsys><address>{1}</address></resolve>' '</request>'.format(vsys, address)} return __proxy__['panos.call'](query) def save_device_config(filename=None): ''' Save device configuration to a named file. filename The filename to save the configuration to. CLI Example: .. code-block:: bash salt '*' panos.save_device_config foo.xml ''' if not filename: raise CommandExecutionError("Filename must not be empty.") query = {'type': 'op', 'cmd': '<save><config><to>{0}</to></config></save>'.format(filename)} return __proxy__['panos.call'](query) def save_device_state(): ''' Save files needed to restore device to local disk. CLI Example: .. code-block:: bash salt '*' panos.save_device_state ''' query = {'type': 'op', 'cmd': '<save><device-state></device-state></save>'} return __proxy__['panos.call'](query) def set_authentication_profile(profile=None, deploy=False): ''' Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_authentication_profile foo salt '*' panos.set_authentication_profile foo deploy=True ''' if not profile: raise CommandExecutionError("Profile name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/' 'authentication-profile', 'element': '<authentication-profile>{0}</authentication-profile>'.format(profile)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_hostname(hostname=None, deploy=False): ''' Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True ''' if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system', 'element': '<hostname>{0}</hostname>'.format(hostname)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_icmp(enabled=True, deploy=False): ''' Enables or disables the ICMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_icmp salt '*' panos.set_management_icmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-icmp>{0}</disable-icmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_http(enabled=True, deploy=False): ''' Enables or disables the HTTP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_http salt '*' panos.set_management_http enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http>{0}</disable-http>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_https(enabled=True, deploy=False): ''' Enables or disables the HTTPS management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_https salt '*' panos.set_management_https enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-https>{0}</disable-https>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ocsp(enabled=True, deploy=False): ''' Enables or disables the HTTP OCSP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ocsp salt '*' panos.set_management_ocsp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http-ocsp>{0}</disable-http-ocsp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_snmp(enabled=True, deploy=False): ''' Enables or disables the SNMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_snmp salt '*' panos.set_management_snmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-snmp>{0}</disable-snmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ssh(enabled=True, deploy=False): ''' Enables or disables the SSH management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ssh salt '*' panos.set_management_ssh enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-ssh>{0}</disable-ssh>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_telnet(enabled=True, deploy=False): ''' Enables or disables the Telnet management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_telnet salt '*' panos.set_management_telnet enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-telnet>{0}</disable-telnet>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): ''' Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server(str): The secondary NTP server IP address or FQDN. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_servers 0.pool.ntp.org 1.pool.ntp.org salt '*' ntp.set_servers primary_server=0.pool.ntp.org secondary_server=1.pool.ntp.org salt '*' ntp.ser_servers 0.pool.ntp.org 1.pool.ntp.org deploy=True ''' ret = {} if primary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(primary_server)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if secondary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(secondary_server)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_permitted_ip(address=None, deploy=False): ''' Add an IPv4 address or network to the permitted IP list. CLI Example: Args: address (str): The IPv4 address or network to allow access to add to the Palo Alto device. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_permitted_ip 10.0.0.1 salt '*' panos.set_permitted_ip 10.0.0.0/24 salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True ''' if not address: raise CommandExecutionError("Address option must not be empty.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip', 'element': '<entry name=\'{0}\'></entry>'.format(address)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_timezone UTC salt '*' panos.set_timezone UTC deploy=True ''' if not tz: raise CommandExecutionError("Timezone name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/timezone', 'element': '<timezone>{0}</timezone>'.format(tz)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def shutdown(): ''' Shutdown a running system. CLI Example: .. code-block:: bash salt '*' panos.shutdown ''' query = {'type': 'op', 'cmd': '<request><shutdown><system></system></shutdown></request>'} return __proxy__['panos.call'](query) def test_fib_route(ip=None, vr='vr1'): ''' Perform a route lookup within active route table (fib). ip (str): The destination IP address to test. vr (str): The name of the virtual router to test. CLI Example: .. code-block:: bash salt '*' panos.test_fib_route 4.2.2.2 salt '*' panos.test_fib_route 4.2.2.2 my-vr ''' xpath = "<test><routing><fib-lookup>" if ip: xpath += "<ip>{0}</ip>".format(ip) if vr: xpath += "<virtual-router>{0}</virtual-router>".format(vr) xpath += "</fib-lookup></routing></test>" query = {'type': 'op', 'cmd': xpath} return __proxy__['panos.call'](query) def test_security_policy(sourcezone=None, destinationzone=None, source=None, destination=None, protocol=None, port=None, application=None, category=None, vsys='1', allrules=False): ''' Checks which security policy as connection will match on the device. sourcezone (str): The source zone matched against the connection. destinationzone (str): The destination zone matched against the connection. source (str): The source address. This must be a single IP address. destination (str): The destination address. This must be a single IP address. protocol (int): The protocol number for the connection. This is the numerical representation of the protocol. port (int): The port number for the connection. application (str): The application that should be matched. category (str): The category that should be matched. vsys (int): The numerical representation of the VSYS ID. allrules (bool): Show all potential match rules until first allow rule. CLI Example: .. code-block:: bash salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 vsys=2 ''' xpath = "<test><security-policy-match>" if sourcezone: xpath += "<from>{0}</from>".format(sourcezone) if destinationzone: xpath += "<to>{0}</to>".format(destinationzone) if source: xpath += "<source>{0}</source>".format(source) if destination: xpath += "<destination>{0}</destination>".format(destination) if protocol: xpath += "<protocol>{0}</protocol>".format(protocol) if port: xpath += "<destination-port>{0}</destination-port>".format(port) if application: xpath += "<application>{0}</application>".format(application) if category: xpath += "<category>{0}</category>".format(category) if allrules: xpath += "<show-all>yes</show-all>" xpath += "</security-policy-match></test>" query = {'type': 'op', 'vsys': "vsys{0}".format(vsys), 'cmd': xpath} return __proxy__['panos.call'](query) def unlock_admin(username=None): ''' Unlocks a locked administrator account. username Username of the administrator. CLI Example: .. code-block:: bash salt '*' panos.unlock_admin username=bob ''' if not username: raise CommandExecutionError("Username option must not be none.") query = {'type': 'op', 'cmd': '<set><management-server><unlock><admin>{0}</admin></unlock></management-server>' '</set>'.format(username)} return __proxy__['panos.call'](query)
saltstack/salt
salt/modules/panos.py
set_ntp_servers
python
def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): ''' Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server(str): The secondary NTP server IP address or FQDN. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_servers 0.pool.ntp.org 1.pool.ntp.org salt '*' ntp.set_servers primary_server=0.pool.ntp.org secondary_server=1.pool.ntp.org salt '*' ntp.ser_servers 0.pool.ntp.org 1.pool.ntp.org deploy=True ''' ret = {} if primary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(primary_server)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if secondary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(secondary_server)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret
Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server(str): The secondary NTP server IP address or FQDN. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_servers 0.pool.ntp.org 1.pool.ntp.org salt '*' ntp.set_servers primary_server=0.pool.ntp.org secondary_server=1.pool.ntp.org salt '*' ntp.ser_servers 0.pool.ntp.org 1.pool.ntp.org deploy=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/panos.py#L2069-L2110
[ "def commit():\n '''\n Commits the candidate configuration to the running configuration.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' panos.commit\n\n '''\n query = {'type': 'commit', 'cmd': '<commit></commit>'}\n\n return _get_job_results(query)\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Palo Alto compatibility to Salt :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix .. versionadded:: 2018.3.0 Configuration ============= This module accepts connection configuration details either as parameters, or as configuration settings in pillar as a Salt proxy. Options passed into opts will be ignored if options are passed into pillar. .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` About ===== This execution module was designed to handle connections to a Palo Alto based firewall. This module adds support to send connections directly to the device through the XML API or through a brokered connection to Panorama. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import Salt Libs from salt.exceptions import CommandExecutionError import salt.proxy.panos import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'panos' def __virtual__(): ''' Will load for the panos proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'panos': return __virtualname__ except KeyError: pass return False, 'The panos execution module can only be loaded for panos proxy minions.' def _get_job_results(query=None): ''' Executes a query that requires a job for completion. This function will wait for the job to complete and return the results. ''' if not query: raise CommandExecutionError("Query parameters cannot be empty.") response = __proxy__['panos.call'](query) # If the response contains a job, we will wait for the results if 'result' in response and 'job' in response['result']: jid = response['result']['job'] while get_job(jid)['result']['job']['status'] != 'FIN': time.sleep(5) return get_job(jid) else: return response def add_config_lock(): ''' Prevent other users from changing configuration until the lock is released. CLI Example: .. code-block:: bash salt '*' panos.add_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><add></add></config-lock></request>'} return __proxy__['panos.call'](query) def check_antivirus(): ''' Get anti-virus information from PaloAlto Networks server CLI Example: .. code-block:: bash salt '*' panos.check_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><check></check></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def check_software(): ''' Get software information from PaloAlto Networks server. CLI Example: .. code-block:: bash salt '*' panos.check_software ''' query = {'type': 'op', 'cmd': '<request><system><software><check></check></software></system></request>'} return __proxy__['panos.call'](query) def clear_commit_tasks(): ''' Clear all commit tasks. CLI Example: .. code-block:: bash salt '*' panos.clear_commit_tasks ''' query = {'type': 'op', 'cmd': '<request><clear-commit-tasks></clear-commit-tasks></request>'} return __proxy__['panos.call'](query) def commit(): ''' Commits the candidate configuration to the running configuration. CLI Example: .. code-block:: bash salt '*' panos.commit ''' query = {'type': 'commit', 'cmd': '<commit></commit>'} return _get_job_results(query) def deactivate_license(key_name=None): ''' Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<request><license><deactivate><key><features><member>{0}</member></features>' '</key></deactivate></license></request>'.format(key_name)} return __proxy__['panos.call'](query) def delete_license(key_name=None): ''' Remove license keys on disk. key_name(str): The file name of the license key to be deleted. CLI Example: .. code-block:: bash salt '*' panos.delete_license key_name=License_File_Name.key ''' if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<delete><license><key>{0}</key></license></delete>'.format(key_name)} return __proxy__['panos.call'](query) def download_antivirus(): ''' Download the most recent anti-virus package. CLI Example: .. code-block:: bash salt '*' panos.download_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><download>' '<latest></latest></download></upgrade></anti-virus></request>'} return _get_job_results(query) def download_software_file(filename=None, synch=False): ''' Download software packages by filename. Args: filename(str): The filename of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_file PanOS_5000-8.0.0 salt '*' panos.download_software_file PanOS_5000-8.0.0 True ''' if not filename: raise CommandExecutionError("Filename option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<file>{0}</file></download></software></system></request>'.format(filename)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<file>{0}</file></download></software></system></request>'.format(filename)} return _get_job_results(query) def download_software_version(version=None, synch=False): ''' Download software packages by version number. Args: version(str): The version of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_version 8.0.0 salt '*' panos.download_software_version 8.0.0 True ''' if not version: raise CommandExecutionError("Version option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<version>{0}</version></download></software></system></request>'.format(version)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<version>{0}</version></download></software></system></request>'.format(version)} return _get_job_results(query) def fetch_license(auth_code=None): ''' Get new license(s) using from the Palo Alto Network Server. auth_code The license authorization code. CLI Example: .. code-block:: bash salt '*' panos.fetch_license salt '*' panos.fetch_license auth_code=foobar ''' if not auth_code: query = {'type': 'op', 'cmd': '<request><license><fetch></fetch></license></request>'} else: query = {'type': 'op', 'cmd': '<request><license><fetch><auth-code>{0}</auth-code></fetch></license>' '</request>'.format(auth_code)} return __proxy__['panos.call'](query) def get_address(address=None, vsys='1'): ''' Get the candidate configuration for the specified get_address object. This will not return address objects that are marked as pre-defined objects. address(str): The name of the address object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address myhost salt '*' panos.get_address myhost 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address/entry[@name=\'{1}\']'.format(vsys, address)} return __proxy__['panos.call'](query) def get_address_group(addressgroup=None, vsys='1'): ''' Get the candidate configuration for the specified address group. This will not return address groups that are marked as pre-defined objects. addressgroup(str): The name of the address group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address_group foobar salt '*' panos.get_address_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address-group/entry[@name=\'{1}\']'.format(vsys, addressgroup)} return __proxy__['panos.call'](query) def get_admins_active(): ''' Show active administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_active ''' query = {'type': 'op', 'cmd': '<show><admins></admins></show>'} return __proxy__['panos.call'](query) def get_admins_all(): ''' Show all administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_all ''' query = {'type': 'op', 'cmd': '<show><admins><all></all></admins></show>'} return __proxy__['panos.call'](query) def get_antivirus_info(): ''' Show information about available anti-virus packages. CLI Example: .. code-block:: bash salt '*' panos.get_antivirus_info ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><info></info></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def get_arp(): ''' Show ARP information. CLI Example: .. code-block:: bash salt '*' panos.get_arp ''' query = {'type': 'op', 'cmd': '<show><arp><entry name = \'all\'/></arp></show>'} return __proxy__['panos.call'](query) def get_cli_idle_timeout(): ''' Show timeout information for this administrative session. CLI Example: .. code-block:: bash salt '*' panos.get_cli_idle_timeout ''' query = {'type': 'op', 'cmd': '<show><cli><idle-timeout></idle-timeout></cli></show>'} return __proxy__['panos.call'](query) def get_cli_permissions(): ''' Show cli administrative permissions. CLI Example: .. code-block:: bash salt '*' panos.get_cli_permissions ''' query = {'type': 'op', 'cmd': '<show><cli><permissions></permissions></cli></show>'} return __proxy__['panos.call'](query) def get_disk_usage(): ''' Report filesystem disk space usage. CLI Example: .. code-block:: bash salt '*' panos.get_disk_usage ''' query = {'type': 'op', 'cmd': '<show><system><disk-space></disk-space></system></show>'} return __proxy__['panos.call'](query) def get_dns_server_config(): ''' Get the DNS server configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_dns_server_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/dns-setting/servers'} return __proxy__['panos.call'](query) def get_domain_config(): ''' Get the domain name configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_domain_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/domain'} return __proxy__['panos.call'](query) def get_dos_blocks(): ''' Show the DoS block-ip table. CLI Example: .. code-block:: bash salt '*' panos.get_dos_blocks ''' query = {'type': 'op', 'cmd': '<show><dos-block-table><all></all></dos-block-table></show>'} return __proxy__['panos.call'](query) def get_fqdn_cache(): ''' Print FQDNs used in rules and their IPs. CLI Example: .. code-block:: bash salt '*' panos.get_fqdn_cache ''' query = {'type': 'op', 'cmd': '<request><system><fqdn><show></show></fqdn></system></request>'} return __proxy__['panos.call'](query) def get_ha_config(): ''' Get the high availability configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ha_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/high-availability'} return __proxy__['panos.call'](query) def get_ha_link(): ''' Show high-availability link-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_link ''' query = {'type': 'op', 'cmd': '<show><high-availability><link-monitoring></link-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_path(): ''' Show high-availability path-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_path ''' query = {'type': 'op', 'cmd': '<show><high-availability><path-monitoring></path-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_state(): ''' Show high-availability state information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_state ''' query = {'type': 'op', 'cmd': '<show><high-availability><state></state></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_transitions(): ''' Show high-availability transition statistic information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_transitions ''' query = {'type': 'op', 'cmd': '<show><high-availability><transitions></transitions></high-availability></show>'} return __proxy__['panos.call'](query) def get_hostname(): ''' Get the hostname of the device. CLI Example: .. code-block:: bash salt '*' panos.get_hostname ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/hostname'} return __proxy__['panos.call'](query) def get_interface_counters(name='all'): ''' Get the counter statistics for interfaces. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interface_counters salt '*' panos.get_interface_counters ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><counter><interface>{0}</interface></counter></show>'.format(name)} return __proxy__['panos.call'](query) def get_interfaces(name='all'): ''' Show interface information. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interfaces salt '*' panos.get_interfaces ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><interface>{0}</interface></show>'.format(name)} return __proxy__['panos.call'](query) def get_job(jid=None): ''' List all a single job by ID. jid The ID of the job to retrieve. CLI Example: .. code-block:: bash salt '*' panos.get_job jid=15 ''' if not jid: raise CommandExecutionError("ID option must not be none.") query = {'type': 'op', 'cmd': '<show><jobs><id>{0}</id></jobs></show>'.format(jid)} return __proxy__['panos.call'](query) def get_jobs(state='all'): ''' List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending ''' if state.lower() == 'all': query = {'type': 'op', 'cmd': '<show><jobs><all></all></jobs></show>'} elif state.lower() == 'pending': query = {'type': 'op', 'cmd': '<show><jobs><pending></pending></jobs></show>'} elif state.lower() == 'processed': query = {'type': 'op', 'cmd': '<show><jobs><processed></processed></jobs></show>'} else: raise CommandExecutionError("The state parameter must be all, pending, or processed.") return __proxy__['panos.call'](query) def get_lacp(): ''' Show LACP state. CLI Example: .. code-block:: bash salt '*' panos.get_lacp ''' query = {'type': 'op', 'cmd': '<show><lacp><aggregate-ethernet>all</aggregate-ethernet></lacp></show>'} return __proxy__['panos.call'](query) def get_license_info(): ''' Show information about owned license(s). CLI Example: .. code-block:: bash salt '*' panos.get_license_info ''' query = {'type': 'op', 'cmd': '<request><license><info></info></license></request>'} return __proxy__['panos.call'](query) def get_license_tokens(): ''' Show license token files for manual license deactivation. CLI Example: .. code-block:: bash salt '*' panos.get_license_tokens ''' query = {'type': 'op', 'cmd': '<show><license-token-files></license-token-files></show>'} return __proxy__['panos.call'](query) def get_lldp_config(): ''' Show lldp config for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_config ''' query = {'type': 'op', 'cmd': '<show><lldp><config>all</config></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_counters(): ''' Show lldp counters for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_counters ''' query = {'type': 'op', 'cmd': '<show><lldp><counters>all</counters></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_local(): ''' Show lldp local info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_local ''' query = {'type': 'op', 'cmd': '<show><lldp><local>all</local></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_neighbors(): ''' Show lldp neighbors info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_neighbors ''' query = {'type': 'op', 'cmd': '<show><lldp><neighbors>all</neighbors></lldp></show>'} return __proxy__['panos.call'](query) def get_local_admins(): ''' Show all local administrator accounts. CLI Example: .. code-block:: bash salt '*' panos.get_local_admins ''' admin_list = get_users_config() response = [] if 'users' not in admin_list['result']: return response if isinstance(admin_list['result']['users']['entry'], list): for entry in admin_list['result']['users']['entry']: response.append(entry['name']) else: response.append(admin_list['result']['users']['entry']['name']) return response def get_logdb_quota(): ''' Report the logdb quotas. CLI Example: .. code-block:: bash salt '*' panos.get_logdb_quota ''' query = {'type': 'op', 'cmd': '<show><system><logdb-quota></logdb-quota></system></show>'} return __proxy__['panos.call'](query) def get_master_key(): ''' Get the master key properties. CLI Example: .. code-block:: bash salt '*' panos.get_master_key ''' query = {'type': 'op', 'cmd': '<show><system><masterkey-properties></masterkey-properties></system></show>'} return __proxy__['panos.call'](query) def get_ntp_config(): ''' Get the NTP configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers'} return __proxy__['panos.call'](query) def get_ntp_servers(): ''' Get list of configured NTP servers. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_servers ''' query = {'type': 'op', 'cmd': '<show><ntp></ntp></show>'} return __proxy__['panos.call'](query) def get_operational_mode(): ''' Show device operational mode setting. CLI Example: .. code-block:: bash salt '*' panos.get_operational_mode ''' query = {'type': 'op', 'cmd': '<show><operational-mode></operational-mode></show>'} return __proxy__['panos.call'](query) def get_panorama_status(): ''' Show panorama connection status. CLI Example: .. code-block:: bash salt '*' panos.get_panorama_status ''' query = {'type': 'op', 'cmd': '<show><panorama-status></panorama-status></show>'} return __proxy__['panos.call'](query) def get_permitted_ips(): ''' Get the IP addresses that are permitted to establish management connections to the device. CLI Example: .. code-block:: bash salt '*' panos.get_permitted_ips ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip'} return __proxy__['panos.call'](query) def get_platform(): ''' Get the platform model information and limitations. CLI Example: .. code-block:: bash salt '*' panos.get_platform ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/platform'} return __proxy__['panos.call'](query) def get_predefined_application(application=None): ''' Get the configuration for the specified pre-defined application object. This will only return pre-defined application objects. application(str): The name of the pre-defined application object. CLI Example: .. code-block:: bash salt '*' panos.get_predefined_application saltstack ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/predefined/application/entry[@name=\'{0}\']'.format(application)} return __proxy__['panos.call'](query) def get_security_rule(rulename=None, vsys='1'): ''' Get the candidate configuration for the specified security rule. rulename(str): The name of the security rule. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_security_rule rule01 salt '*' panos.get_security_rule rule01 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'rulebase/security/rules/entry[@name=\'{1}\']'.format(vsys, rulename)} return __proxy__['panos.call'](query) def get_service(service=None, vsys='1'): ''' Get the candidate configuration for the specified service object. This will not return services that are marked as pre-defined objects. service(str): The name of the service object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service tcp-443 salt '*' panos.get_service tcp-443 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service/entry[@name=\'{1}\']'.format(vsys, service)} return __proxy__['panos.call'](query) def get_service_group(servicegroup=None, vsys='1'): ''' Get the candidate configuration for the specified service group. This will not return service groups that are marked as pre-defined objects. servicegroup(str): The name of the service group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service_group foobar salt '*' panos.get_service_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service-group/entry[@name=\'{1}\']'.format(vsys, servicegroup)} return __proxy__['panos.call'](query) def get_session_info(): ''' Show device session statistics. CLI Example: .. code-block:: bash salt '*' panos.get_session_info ''' query = {'type': 'op', 'cmd': '<show><session><info></info></session></show>'} return __proxy__['panos.call'](query) def get_snmp_config(): ''' Get the SNMP configuration from the device. CLI Example: .. code-block:: bash salt '*' panos.get_snmp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/snmp-setting'} return __proxy__['panos.call'](query) def get_software_info(): ''' Show information about available software packages. CLI Example: .. code-block:: bash salt '*' panos.get_software_info ''' query = {'type': 'op', 'cmd': '<request><system><software><info></info></software></system></request>'} return __proxy__['panos.call'](query) def get_system_date_time(): ''' Get the system date/time. CLI Example: .. code-block:: bash salt '*' panos.get_system_date_time ''' query = {'type': 'op', 'cmd': '<show><clock></clock></show>'} return __proxy__['panos.call'](query) def get_system_files(): ''' List important files in the system. CLI Example: .. code-block:: bash salt '*' panos.get_system_files ''' query = {'type': 'op', 'cmd': '<show><system><files></files></system></show>'} return __proxy__['panos.call'](query) def get_system_info(): ''' Get the system information. CLI Example: .. code-block:: bash salt '*' panos.get_system_info ''' query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'} return __proxy__['panos.call'](query) def get_system_services(): ''' Show system services. CLI Example: .. code-block:: bash salt '*' panos.get_system_services ''' query = {'type': 'op', 'cmd': '<show><system><services></services></system></show>'} return __proxy__['panos.call'](query) def get_system_state(mask=None): ''' Show the system state variables. mask Filters by a subtree or a wildcard. CLI Example: .. code-block:: bash salt '*' panos.get_system_state salt '*' panos.get_system_state mask=cfg.ha.config.enabled salt '*' panos.get_system_state mask=cfg.ha.* ''' if mask: query = {'type': 'op', 'cmd': '<show><system><state><filter>{0}</filter></state></system></show>'.format(mask)} else: query = {'type': 'op', 'cmd': '<show><system><state></state></system></show>'} return __proxy__['panos.call'](query) def get_uncommitted_changes(): ''' Retrieve a list of all uncommitted changes on the device. Requires PANOS version 8.0.0 or greater. CLI Example: .. code-block:: bash salt '*' panos.get_uncommitted_changes ''' _required_version = '8.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) query = {'type': 'op', 'cmd': '<show><config><list><changes></changes></list></config></show>'} return __proxy__['panos.call'](query) def get_users_config(): ''' Get the local administrative user account configuration. CLI Example: .. code-block:: bash salt '*' panos.get_users_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/mgt-config/users'} return __proxy__['panos.call'](query) def get_vlans(): ''' Show all VLAN information. CLI Example: .. code-block:: bash salt '*' panos.get_vlans ''' query = {'type': 'op', 'cmd': '<show><vlan>all</vlan></show>'} return __proxy__['panos.call'](query) def get_xpath(xpath=''): ''' Retrieve a specified xpath from the candidate configuration. xpath(str): The specified xpath in the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_xpath /config/shared/service ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} return __proxy__['panos.call'](query) def get_zone(zone='', vsys='1'): ''' Get the candidate configuration for the specified zone. zone(str): The name of the zone. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zone trust salt '*' panos.get_zone trust 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone/entry[@name=\'{1}\']'.format(vsys, zone)} return __proxy__['panos.call'](query) def get_zones(vsys='1'): ''' Get all the zones in the candidate configuration. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zones salt '*' panos.get_zones 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone'.format(vsys)} return __proxy__['panos.call'](query) def install_antivirus(version=None, latest=False, synch=False, skip_commit=False,): ''' Install anti-virus packages. Args: version(str): The version of the PANOS file to install. latest(bool): If true, the latest anti-virus file will be installed. The specified version option will be ignored. synch(bool): If true, the anti-virus will synch to the peer unit. skip_commit(bool): If true, the install will skip committing to the device. CLI Example: .. code-block:: bash salt '*' panos.install_antivirus 8.0.0 ''' if not version and latest is False: raise CommandExecutionError("Version option must not be none.") if synch is True: s = "yes" else: s = "no" if skip_commit is True: c = "yes" else: c = "no" if latest is True: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>latest</version></install></upgrade></anti-virus></request>'.format(c, s)} else: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>{2}</version></install></upgrade></anti-virus></request>'.format(c, s, version)} return _get_job_results(query) def install_license(): ''' Install the license key(s). CLI Example: .. code-block:: bash salt '*' panos.install_license ''' query = {'type': 'op', 'cmd': '<request><license><install></install></license></request>'} return __proxy__['panos.call'](query) def install_software(version=None): ''' Upgrade to a software package by version. Args: version(str): The version of the PANOS file to install. CLI Example: .. code-block:: bash salt '*' panos.install_license 8.0.0 ''' if not version: raise CommandExecutionError("Version option must not be none.") query = {'type': 'op', 'cmd': '<request><system><software><install>' '<version>{0}</version></install></software></system></request>'.format(version)} return _get_job_results(query) def reboot(): ''' Reboot a running system. CLI Example: .. code-block:: bash salt '*' panos.reboot ''' query = {'type': 'op', 'cmd': '<request><restart><system></system></restart></request>'} return __proxy__['panos.call'](query) def refresh_fqdn_cache(force=False): ''' Force refreshes all FQDNs used in rules. force Forces all fqdn refresh CLI Example: .. code-block:: bash salt '*' panos.refresh_fqdn_cache salt '*' panos.refresh_fqdn_cache force=True ''' if not isinstance(force, bool): raise CommandExecutionError("Force option must be boolean.") if force: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh><force>yes</force></refresh></fqdn></system></request>'} else: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh></refresh></fqdn></system></request>'} return __proxy__['panos.call'](query) def remove_config_lock(): ''' Release config lock previously held. CLI Example: .. code-block:: bash salt '*' panos.remove_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><remove></remove></config-lock></request>'} return __proxy__['panos.call'](query) def resolve_address(address=None, vsys=None): ''' Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com salt '*' panos.resolve_address foo.bar.com vsys=2 ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not address: raise CommandExecutionError("FQDN to resolve must be provided as address.") if not vsys: query = {'type': 'op', 'cmd': '<request><resolve><address>{0}</address></resolve></request>'.format(address)} else: query = {'type': 'op', 'cmd': '<request><resolve><vsys>{0}</vsys><address>{1}</address></resolve>' '</request>'.format(vsys, address)} return __proxy__['panos.call'](query) def save_device_config(filename=None): ''' Save device configuration to a named file. filename The filename to save the configuration to. CLI Example: .. code-block:: bash salt '*' panos.save_device_config foo.xml ''' if not filename: raise CommandExecutionError("Filename must not be empty.") query = {'type': 'op', 'cmd': '<save><config><to>{0}</to></config></save>'.format(filename)} return __proxy__['panos.call'](query) def save_device_state(): ''' Save files needed to restore device to local disk. CLI Example: .. code-block:: bash salt '*' panos.save_device_state ''' query = {'type': 'op', 'cmd': '<save><device-state></device-state></save>'} return __proxy__['panos.call'](query) def set_authentication_profile(profile=None, deploy=False): ''' Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_authentication_profile foo salt '*' panos.set_authentication_profile foo deploy=True ''' if not profile: raise CommandExecutionError("Profile name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/' 'authentication-profile', 'element': '<authentication-profile>{0}</authentication-profile>'.format(profile)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_hostname(hostname=None, deploy=False): ''' Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True ''' if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system', 'element': '<hostname>{0}</hostname>'.format(hostname)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_icmp(enabled=True, deploy=False): ''' Enables or disables the ICMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_icmp salt '*' panos.set_management_icmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-icmp>{0}</disable-icmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_http(enabled=True, deploy=False): ''' Enables or disables the HTTP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_http salt '*' panos.set_management_http enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http>{0}</disable-http>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_https(enabled=True, deploy=False): ''' Enables or disables the HTTPS management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_https salt '*' panos.set_management_https enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-https>{0}</disable-https>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ocsp(enabled=True, deploy=False): ''' Enables or disables the HTTP OCSP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ocsp salt '*' panos.set_management_ocsp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http-ocsp>{0}</disable-http-ocsp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_snmp(enabled=True, deploy=False): ''' Enables or disables the SNMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_snmp salt '*' panos.set_management_snmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-snmp>{0}</disable-snmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ssh(enabled=True, deploy=False): ''' Enables or disables the SSH management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ssh salt '*' panos.set_management_ssh enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-ssh>{0}</disable-ssh>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_telnet(enabled=True, deploy=False): ''' Enables or disables the Telnet management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_telnet salt '*' panos.set_management_telnet enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-telnet>{0}</disable-telnet>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_ntp_authentication(target=None, authentication_type=None, key_id=None, authentication_key=None, algorithm=None, deploy=False): ''' Set the NTP authentication of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: target(str): Determines the target of the authentication. Valid options are primary, secondary, or both. authentication_type(str): The authentication type to be used. Valid options are symmetric, autokey, and none. key_id(int): The NTP authentication key ID. authentication_key(str): The authentication key. algorithm(str): The algorithm type to be used for a symmetric key. Valid options are md5 and sha1. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_authentication target=both authentication_type=autokey salt '*' ntp.set_authentication target=primary authentication_type=none salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 deploy=True ''' ret = {} if target not in ['primary', 'secondary', 'both']: raise salt.exceptions.CommandExecutionError("Target option must be primary, secondary, or both.") if authentication_type not in ['symmetric', 'autokey', 'none']: raise salt.exceptions.CommandExecutionError("Type option must be symmetric, autokey, or both.") if authentication_type == "symmetric" and not authentication_key: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, authentication_key must be " "provided.") if authentication_type == "symmetric" and not key_id: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, key_id must be provided.") if authentication_type == "symmetric" and algorithm not in ['md5', 'sha1']: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, algorithm must be md5 or " "sha1.") if authentication_type == 'symmetric': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'autokey': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'none': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_permitted_ip(address=None, deploy=False): ''' Add an IPv4 address or network to the permitted IP list. CLI Example: Args: address (str): The IPv4 address or network to allow access to add to the Palo Alto device. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_permitted_ip 10.0.0.1 salt '*' panos.set_permitted_ip 10.0.0.0/24 salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True ''' if not address: raise CommandExecutionError("Address option must not be empty.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip', 'element': '<entry name=\'{0}\'></entry>'.format(address)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_timezone UTC salt '*' panos.set_timezone UTC deploy=True ''' if not tz: raise CommandExecutionError("Timezone name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/timezone', 'element': '<timezone>{0}</timezone>'.format(tz)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def shutdown(): ''' Shutdown a running system. CLI Example: .. code-block:: bash salt '*' panos.shutdown ''' query = {'type': 'op', 'cmd': '<request><shutdown><system></system></shutdown></request>'} return __proxy__['panos.call'](query) def test_fib_route(ip=None, vr='vr1'): ''' Perform a route lookup within active route table (fib). ip (str): The destination IP address to test. vr (str): The name of the virtual router to test. CLI Example: .. code-block:: bash salt '*' panos.test_fib_route 4.2.2.2 salt '*' panos.test_fib_route 4.2.2.2 my-vr ''' xpath = "<test><routing><fib-lookup>" if ip: xpath += "<ip>{0}</ip>".format(ip) if vr: xpath += "<virtual-router>{0}</virtual-router>".format(vr) xpath += "</fib-lookup></routing></test>" query = {'type': 'op', 'cmd': xpath} return __proxy__['panos.call'](query) def test_security_policy(sourcezone=None, destinationzone=None, source=None, destination=None, protocol=None, port=None, application=None, category=None, vsys='1', allrules=False): ''' Checks which security policy as connection will match on the device. sourcezone (str): The source zone matched against the connection. destinationzone (str): The destination zone matched against the connection. source (str): The source address. This must be a single IP address. destination (str): The destination address. This must be a single IP address. protocol (int): The protocol number for the connection. This is the numerical representation of the protocol. port (int): The port number for the connection. application (str): The application that should be matched. category (str): The category that should be matched. vsys (int): The numerical representation of the VSYS ID. allrules (bool): Show all potential match rules until first allow rule. CLI Example: .. code-block:: bash salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 vsys=2 ''' xpath = "<test><security-policy-match>" if sourcezone: xpath += "<from>{0}</from>".format(sourcezone) if destinationzone: xpath += "<to>{0}</to>".format(destinationzone) if source: xpath += "<source>{0}</source>".format(source) if destination: xpath += "<destination>{0}</destination>".format(destination) if protocol: xpath += "<protocol>{0}</protocol>".format(protocol) if port: xpath += "<destination-port>{0}</destination-port>".format(port) if application: xpath += "<application>{0}</application>".format(application) if category: xpath += "<category>{0}</category>".format(category) if allrules: xpath += "<show-all>yes</show-all>" xpath += "</security-policy-match></test>" query = {'type': 'op', 'vsys': "vsys{0}".format(vsys), 'cmd': xpath} return __proxy__['panos.call'](query) def unlock_admin(username=None): ''' Unlocks a locked administrator account. username Username of the administrator. CLI Example: .. code-block:: bash salt '*' panos.unlock_admin username=bob ''' if not username: raise CommandExecutionError("Username option must not be none.") query = {'type': 'op', 'cmd': '<set><management-server><unlock><admin>{0}</admin></unlock></management-server>' '</set>'.format(username)} return __proxy__['panos.call'](query)
saltstack/salt
salt/modules/panos.py
set_permitted_ip
python
def set_permitted_ip(address=None, deploy=False): ''' Add an IPv4 address or network to the permitted IP list. CLI Example: Args: address (str): The IPv4 address or network to allow access to add to the Palo Alto device. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_permitted_ip 10.0.0.1 salt '*' panos.set_permitted_ip 10.0.0.0/24 salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True ''' if not address: raise CommandExecutionError("Address option must not be empty.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip', 'element': '<entry name=\'{0}\'></entry>'.format(address)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret
Add an IPv4 address or network to the permitted IP list. CLI Example: Args: address (str): The IPv4 address or network to allow access to add to the Palo Alto device. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_permitted_ip 10.0.0.1 salt '*' panos.set_permitted_ip 10.0.0.0/24 salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/panos.py#L2113-L2147
[ "def commit():\n '''\n Commits the candidate configuration to the running configuration.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' panos.commit\n\n '''\n query = {'type': 'commit', 'cmd': '<commit></commit>'}\n\n return _get_job_results(query)\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Palo Alto compatibility to Salt :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix .. versionadded:: 2018.3.0 Configuration ============= This module accepts connection configuration details either as parameters, or as configuration settings in pillar as a Salt proxy. Options passed into opts will be ignored if options are passed into pillar. .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` About ===== This execution module was designed to handle connections to a Palo Alto based firewall. This module adds support to send connections directly to the device through the XML API or through a brokered connection to Panorama. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import Salt Libs from salt.exceptions import CommandExecutionError import salt.proxy.panos import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'panos' def __virtual__(): ''' Will load for the panos proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'panos': return __virtualname__ except KeyError: pass return False, 'The panos execution module can only be loaded for panos proxy minions.' def _get_job_results(query=None): ''' Executes a query that requires a job for completion. This function will wait for the job to complete and return the results. ''' if not query: raise CommandExecutionError("Query parameters cannot be empty.") response = __proxy__['panos.call'](query) # If the response contains a job, we will wait for the results if 'result' in response and 'job' in response['result']: jid = response['result']['job'] while get_job(jid)['result']['job']['status'] != 'FIN': time.sleep(5) return get_job(jid) else: return response def add_config_lock(): ''' Prevent other users from changing configuration until the lock is released. CLI Example: .. code-block:: bash salt '*' panos.add_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><add></add></config-lock></request>'} return __proxy__['panos.call'](query) def check_antivirus(): ''' Get anti-virus information from PaloAlto Networks server CLI Example: .. code-block:: bash salt '*' panos.check_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><check></check></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def check_software(): ''' Get software information from PaloAlto Networks server. CLI Example: .. code-block:: bash salt '*' panos.check_software ''' query = {'type': 'op', 'cmd': '<request><system><software><check></check></software></system></request>'} return __proxy__['panos.call'](query) def clear_commit_tasks(): ''' Clear all commit tasks. CLI Example: .. code-block:: bash salt '*' panos.clear_commit_tasks ''' query = {'type': 'op', 'cmd': '<request><clear-commit-tasks></clear-commit-tasks></request>'} return __proxy__['panos.call'](query) def commit(): ''' Commits the candidate configuration to the running configuration. CLI Example: .. code-block:: bash salt '*' panos.commit ''' query = {'type': 'commit', 'cmd': '<commit></commit>'} return _get_job_results(query) def deactivate_license(key_name=None): ''' Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<request><license><deactivate><key><features><member>{0}</member></features>' '</key></deactivate></license></request>'.format(key_name)} return __proxy__['panos.call'](query) def delete_license(key_name=None): ''' Remove license keys on disk. key_name(str): The file name of the license key to be deleted. CLI Example: .. code-block:: bash salt '*' panos.delete_license key_name=License_File_Name.key ''' if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<delete><license><key>{0}</key></license></delete>'.format(key_name)} return __proxy__['panos.call'](query) def download_antivirus(): ''' Download the most recent anti-virus package. CLI Example: .. code-block:: bash salt '*' panos.download_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><download>' '<latest></latest></download></upgrade></anti-virus></request>'} return _get_job_results(query) def download_software_file(filename=None, synch=False): ''' Download software packages by filename. Args: filename(str): The filename of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_file PanOS_5000-8.0.0 salt '*' panos.download_software_file PanOS_5000-8.0.0 True ''' if not filename: raise CommandExecutionError("Filename option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<file>{0}</file></download></software></system></request>'.format(filename)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<file>{0}</file></download></software></system></request>'.format(filename)} return _get_job_results(query) def download_software_version(version=None, synch=False): ''' Download software packages by version number. Args: version(str): The version of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_version 8.0.0 salt '*' panos.download_software_version 8.0.0 True ''' if not version: raise CommandExecutionError("Version option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<version>{0}</version></download></software></system></request>'.format(version)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<version>{0}</version></download></software></system></request>'.format(version)} return _get_job_results(query) def fetch_license(auth_code=None): ''' Get new license(s) using from the Palo Alto Network Server. auth_code The license authorization code. CLI Example: .. code-block:: bash salt '*' panos.fetch_license salt '*' panos.fetch_license auth_code=foobar ''' if not auth_code: query = {'type': 'op', 'cmd': '<request><license><fetch></fetch></license></request>'} else: query = {'type': 'op', 'cmd': '<request><license><fetch><auth-code>{0}</auth-code></fetch></license>' '</request>'.format(auth_code)} return __proxy__['panos.call'](query) def get_address(address=None, vsys='1'): ''' Get the candidate configuration for the specified get_address object. This will not return address objects that are marked as pre-defined objects. address(str): The name of the address object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address myhost salt '*' panos.get_address myhost 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address/entry[@name=\'{1}\']'.format(vsys, address)} return __proxy__['panos.call'](query) def get_address_group(addressgroup=None, vsys='1'): ''' Get the candidate configuration for the specified address group. This will not return address groups that are marked as pre-defined objects. addressgroup(str): The name of the address group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address_group foobar salt '*' panos.get_address_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address-group/entry[@name=\'{1}\']'.format(vsys, addressgroup)} return __proxy__['panos.call'](query) def get_admins_active(): ''' Show active administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_active ''' query = {'type': 'op', 'cmd': '<show><admins></admins></show>'} return __proxy__['panos.call'](query) def get_admins_all(): ''' Show all administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_all ''' query = {'type': 'op', 'cmd': '<show><admins><all></all></admins></show>'} return __proxy__['panos.call'](query) def get_antivirus_info(): ''' Show information about available anti-virus packages. CLI Example: .. code-block:: bash salt '*' panos.get_antivirus_info ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><info></info></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def get_arp(): ''' Show ARP information. CLI Example: .. code-block:: bash salt '*' panos.get_arp ''' query = {'type': 'op', 'cmd': '<show><arp><entry name = \'all\'/></arp></show>'} return __proxy__['panos.call'](query) def get_cli_idle_timeout(): ''' Show timeout information for this administrative session. CLI Example: .. code-block:: bash salt '*' panos.get_cli_idle_timeout ''' query = {'type': 'op', 'cmd': '<show><cli><idle-timeout></idle-timeout></cli></show>'} return __proxy__['panos.call'](query) def get_cli_permissions(): ''' Show cli administrative permissions. CLI Example: .. code-block:: bash salt '*' panos.get_cli_permissions ''' query = {'type': 'op', 'cmd': '<show><cli><permissions></permissions></cli></show>'} return __proxy__['panos.call'](query) def get_disk_usage(): ''' Report filesystem disk space usage. CLI Example: .. code-block:: bash salt '*' panos.get_disk_usage ''' query = {'type': 'op', 'cmd': '<show><system><disk-space></disk-space></system></show>'} return __proxy__['panos.call'](query) def get_dns_server_config(): ''' Get the DNS server configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_dns_server_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/dns-setting/servers'} return __proxy__['panos.call'](query) def get_domain_config(): ''' Get the domain name configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_domain_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/domain'} return __proxy__['panos.call'](query) def get_dos_blocks(): ''' Show the DoS block-ip table. CLI Example: .. code-block:: bash salt '*' panos.get_dos_blocks ''' query = {'type': 'op', 'cmd': '<show><dos-block-table><all></all></dos-block-table></show>'} return __proxy__['panos.call'](query) def get_fqdn_cache(): ''' Print FQDNs used in rules and their IPs. CLI Example: .. code-block:: bash salt '*' panos.get_fqdn_cache ''' query = {'type': 'op', 'cmd': '<request><system><fqdn><show></show></fqdn></system></request>'} return __proxy__['panos.call'](query) def get_ha_config(): ''' Get the high availability configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ha_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/high-availability'} return __proxy__['panos.call'](query) def get_ha_link(): ''' Show high-availability link-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_link ''' query = {'type': 'op', 'cmd': '<show><high-availability><link-monitoring></link-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_path(): ''' Show high-availability path-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_path ''' query = {'type': 'op', 'cmd': '<show><high-availability><path-monitoring></path-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_state(): ''' Show high-availability state information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_state ''' query = {'type': 'op', 'cmd': '<show><high-availability><state></state></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_transitions(): ''' Show high-availability transition statistic information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_transitions ''' query = {'type': 'op', 'cmd': '<show><high-availability><transitions></transitions></high-availability></show>'} return __proxy__['panos.call'](query) def get_hostname(): ''' Get the hostname of the device. CLI Example: .. code-block:: bash salt '*' panos.get_hostname ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/hostname'} return __proxy__['panos.call'](query) def get_interface_counters(name='all'): ''' Get the counter statistics for interfaces. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interface_counters salt '*' panos.get_interface_counters ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><counter><interface>{0}</interface></counter></show>'.format(name)} return __proxy__['panos.call'](query) def get_interfaces(name='all'): ''' Show interface information. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interfaces salt '*' panos.get_interfaces ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><interface>{0}</interface></show>'.format(name)} return __proxy__['panos.call'](query) def get_job(jid=None): ''' List all a single job by ID. jid The ID of the job to retrieve. CLI Example: .. code-block:: bash salt '*' panos.get_job jid=15 ''' if not jid: raise CommandExecutionError("ID option must not be none.") query = {'type': 'op', 'cmd': '<show><jobs><id>{0}</id></jobs></show>'.format(jid)} return __proxy__['panos.call'](query) def get_jobs(state='all'): ''' List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending ''' if state.lower() == 'all': query = {'type': 'op', 'cmd': '<show><jobs><all></all></jobs></show>'} elif state.lower() == 'pending': query = {'type': 'op', 'cmd': '<show><jobs><pending></pending></jobs></show>'} elif state.lower() == 'processed': query = {'type': 'op', 'cmd': '<show><jobs><processed></processed></jobs></show>'} else: raise CommandExecutionError("The state parameter must be all, pending, or processed.") return __proxy__['panos.call'](query) def get_lacp(): ''' Show LACP state. CLI Example: .. code-block:: bash salt '*' panos.get_lacp ''' query = {'type': 'op', 'cmd': '<show><lacp><aggregate-ethernet>all</aggregate-ethernet></lacp></show>'} return __proxy__['panos.call'](query) def get_license_info(): ''' Show information about owned license(s). CLI Example: .. code-block:: bash salt '*' panos.get_license_info ''' query = {'type': 'op', 'cmd': '<request><license><info></info></license></request>'} return __proxy__['panos.call'](query) def get_license_tokens(): ''' Show license token files for manual license deactivation. CLI Example: .. code-block:: bash salt '*' panos.get_license_tokens ''' query = {'type': 'op', 'cmd': '<show><license-token-files></license-token-files></show>'} return __proxy__['panos.call'](query) def get_lldp_config(): ''' Show lldp config for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_config ''' query = {'type': 'op', 'cmd': '<show><lldp><config>all</config></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_counters(): ''' Show lldp counters for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_counters ''' query = {'type': 'op', 'cmd': '<show><lldp><counters>all</counters></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_local(): ''' Show lldp local info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_local ''' query = {'type': 'op', 'cmd': '<show><lldp><local>all</local></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_neighbors(): ''' Show lldp neighbors info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_neighbors ''' query = {'type': 'op', 'cmd': '<show><lldp><neighbors>all</neighbors></lldp></show>'} return __proxy__['panos.call'](query) def get_local_admins(): ''' Show all local administrator accounts. CLI Example: .. code-block:: bash salt '*' panos.get_local_admins ''' admin_list = get_users_config() response = [] if 'users' not in admin_list['result']: return response if isinstance(admin_list['result']['users']['entry'], list): for entry in admin_list['result']['users']['entry']: response.append(entry['name']) else: response.append(admin_list['result']['users']['entry']['name']) return response def get_logdb_quota(): ''' Report the logdb quotas. CLI Example: .. code-block:: bash salt '*' panos.get_logdb_quota ''' query = {'type': 'op', 'cmd': '<show><system><logdb-quota></logdb-quota></system></show>'} return __proxy__['panos.call'](query) def get_master_key(): ''' Get the master key properties. CLI Example: .. code-block:: bash salt '*' panos.get_master_key ''' query = {'type': 'op', 'cmd': '<show><system><masterkey-properties></masterkey-properties></system></show>'} return __proxy__['panos.call'](query) def get_ntp_config(): ''' Get the NTP configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers'} return __proxy__['panos.call'](query) def get_ntp_servers(): ''' Get list of configured NTP servers. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_servers ''' query = {'type': 'op', 'cmd': '<show><ntp></ntp></show>'} return __proxy__['panos.call'](query) def get_operational_mode(): ''' Show device operational mode setting. CLI Example: .. code-block:: bash salt '*' panos.get_operational_mode ''' query = {'type': 'op', 'cmd': '<show><operational-mode></operational-mode></show>'} return __proxy__['panos.call'](query) def get_panorama_status(): ''' Show panorama connection status. CLI Example: .. code-block:: bash salt '*' panos.get_panorama_status ''' query = {'type': 'op', 'cmd': '<show><panorama-status></panorama-status></show>'} return __proxy__['panos.call'](query) def get_permitted_ips(): ''' Get the IP addresses that are permitted to establish management connections to the device. CLI Example: .. code-block:: bash salt '*' panos.get_permitted_ips ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip'} return __proxy__['panos.call'](query) def get_platform(): ''' Get the platform model information and limitations. CLI Example: .. code-block:: bash salt '*' panos.get_platform ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/platform'} return __proxy__['panos.call'](query) def get_predefined_application(application=None): ''' Get the configuration for the specified pre-defined application object. This will only return pre-defined application objects. application(str): The name of the pre-defined application object. CLI Example: .. code-block:: bash salt '*' panos.get_predefined_application saltstack ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/predefined/application/entry[@name=\'{0}\']'.format(application)} return __proxy__['panos.call'](query) def get_security_rule(rulename=None, vsys='1'): ''' Get the candidate configuration for the specified security rule. rulename(str): The name of the security rule. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_security_rule rule01 salt '*' panos.get_security_rule rule01 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'rulebase/security/rules/entry[@name=\'{1}\']'.format(vsys, rulename)} return __proxy__['panos.call'](query) def get_service(service=None, vsys='1'): ''' Get the candidate configuration for the specified service object. This will not return services that are marked as pre-defined objects. service(str): The name of the service object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service tcp-443 salt '*' panos.get_service tcp-443 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service/entry[@name=\'{1}\']'.format(vsys, service)} return __proxy__['panos.call'](query) def get_service_group(servicegroup=None, vsys='1'): ''' Get the candidate configuration for the specified service group. This will not return service groups that are marked as pre-defined objects. servicegroup(str): The name of the service group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service_group foobar salt '*' panos.get_service_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service-group/entry[@name=\'{1}\']'.format(vsys, servicegroup)} return __proxy__['panos.call'](query) def get_session_info(): ''' Show device session statistics. CLI Example: .. code-block:: bash salt '*' panos.get_session_info ''' query = {'type': 'op', 'cmd': '<show><session><info></info></session></show>'} return __proxy__['panos.call'](query) def get_snmp_config(): ''' Get the SNMP configuration from the device. CLI Example: .. code-block:: bash salt '*' panos.get_snmp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/snmp-setting'} return __proxy__['panos.call'](query) def get_software_info(): ''' Show information about available software packages. CLI Example: .. code-block:: bash salt '*' panos.get_software_info ''' query = {'type': 'op', 'cmd': '<request><system><software><info></info></software></system></request>'} return __proxy__['panos.call'](query) def get_system_date_time(): ''' Get the system date/time. CLI Example: .. code-block:: bash salt '*' panos.get_system_date_time ''' query = {'type': 'op', 'cmd': '<show><clock></clock></show>'} return __proxy__['panos.call'](query) def get_system_files(): ''' List important files in the system. CLI Example: .. code-block:: bash salt '*' panos.get_system_files ''' query = {'type': 'op', 'cmd': '<show><system><files></files></system></show>'} return __proxy__['panos.call'](query) def get_system_info(): ''' Get the system information. CLI Example: .. code-block:: bash salt '*' panos.get_system_info ''' query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'} return __proxy__['panos.call'](query) def get_system_services(): ''' Show system services. CLI Example: .. code-block:: bash salt '*' panos.get_system_services ''' query = {'type': 'op', 'cmd': '<show><system><services></services></system></show>'} return __proxy__['panos.call'](query) def get_system_state(mask=None): ''' Show the system state variables. mask Filters by a subtree or a wildcard. CLI Example: .. code-block:: bash salt '*' panos.get_system_state salt '*' panos.get_system_state mask=cfg.ha.config.enabled salt '*' panos.get_system_state mask=cfg.ha.* ''' if mask: query = {'type': 'op', 'cmd': '<show><system><state><filter>{0}</filter></state></system></show>'.format(mask)} else: query = {'type': 'op', 'cmd': '<show><system><state></state></system></show>'} return __proxy__['panos.call'](query) def get_uncommitted_changes(): ''' Retrieve a list of all uncommitted changes on the device. Requires PANOS version 8.0.0 or greater. CLI Example: .. code-block:: bash salt '*' panos.get_uncommitted_changes ''' _required_version = '8.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) query = {'type': 'op', 'cmd': '<show><config><list><changes></changes></list></config></show>'} return __proxy__['panos.call'](query) def get_users_config(): ''' Get the local administrative user account configuration. CLI Example: .. code-block:: bash salt '*' panos.get_users_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/mgt-config/users'} return __proxy__['panos.call'](query) def get_vlans(): ''' Show all VLAN information. CLI Example: .. code-block:: bash salt '*' panos.get_vlans ''' query = {'type': 'op', 'cmd': '<show><vlan>all</vlan></show>'} return __proxy__['panos.call'](query) def get_xpath(xpath=''): ''' Retrieve a specified xpath from the candidate configuration. xpath(str): The specified xpath in the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_xpath /config/shared/service ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} return __proxy__['panos.call'](query) def get_zone(zone='', vsys='1'): ''' Get the candidate configuration for the specified zone. zone(str): The name of the zone. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zone trust salt '*' panos.get_zone trust 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone/entry[@name=\'{1}\']'.format(vsys, zone)} return __proxy__['panos.call'](query) def get_zones(vsys='1'): ''' Get all the zones in the candidate configuration. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zones salt '*' panos.get_zones 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone'.format(vsys)} return __proxy__['panos.call'](query) def install_antivirus(version=None, latest=False, synch=False, skip_commit=False,): ''' Install anti-virus packages. Args: version(str): The version of the PANOS file to install. latest(bool): If true, the latest anti-virus file will be installed. The specified version option will be ignored. synch(bool): If true, the anti-virus will synch to the peer unit. skip_commit(bool): If true, the install will skip committing to the device. CLI Example: .. code-block:: bash salt '*' panos.install_antivirus 8.0.0 ''' if not version and latest is False: raise CommandExecutionError("Version option must not be none.") if synch is True: s = "yes" else: s = "no" if skip_commit is True: c = "yes" else: c = "no" if latest is True: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>latest</version></install></upgrade></anti-virus></request>'.format(c, s)} else: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>{2}</version></install></upgrade></anti-virus></request>'.format(c, s, version)} return _get_job_results(query) def install_license(): ''' Install the license key(s). CLI Example: .. code-block:: bash salt '*' panos.install_license ''' query = {'type': 'op', 'cmd': '<request><license><install></install></license></request>'} return __proxy__['panos.call'](query) def install_software(version=None): ''' Upgrade to a software package by version. Args: version(str): The version of the PANOS file to install. CLI Example: .. code-block:: bash salt '*' panos.install_license 8.0.0 ''' if not version: raise CommandExecutionError("Version option must not be none.") query = {'type': 'op', 'cmd': '<request><system><software><install>' '<version>{0}</version></install></software></system></request>'.format(version)} return _get_job_results(query) def reboot(): ''' Reboot a running system. CLI Example: .. code-block:: bash salt '*' panos.reboot ''' query = {'type': 'op', 'cmd': '<request><restart><system></system></restart></request>'} return __proxy__['panos.call'](query) def refresh_fqdn_cache(force=False): ''' Force refreshes all FQDNs used in rules. force Forces all fqdn refresh CLI Example: .. code-block:: bash salt '*' panos.refresh_fqdn_cache salt '*' panos.refresh_fqdn_cache force=True ''' if not isinstance(force, bool): raise CommandExecutionError("Force option must be boolean.") if force: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh><force>yes</force></refresh></fqdn></system></request>'} else: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh></refresh></fqdn></system></request>'} return __proxy__['panos.call'](query) def remove_config_lock(): ''' Release config lock previously held. CLI Example: .. code-block:: bash salt '*' panos.remove_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><remove></remove></config-lock></request>'} return __proxy__['panos.call'](query) def resolve_address(address=None, vsys=None): ''' Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com salt '*' panos.resolve_address foo.bar.com vsys=2 ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not address: raise CommandExecutionError("FQDN to resolve must be provided as address.") if not vsys: query = {'type': 'op', 'cmd': '<request><resolve><address>{0}</address></resolve></request>'.format(address)} else: query = {'type': 'op', 'cmd': '<request><resolve><vsys>{0}</vsys><address>{1}</address></resolve>' '</request>'.format(vsys, address)} return __proxy__['panos.call'](query) def save_device_config(filename=None): ''' Save device configuration to a named file. filename The filename to save the configuration to. CLI Example: .. code-block:: bash salt '*' panos.save_device_config foo.xml ''' if not filename: raise CommandExecutionError("Filename must not be empty.") query = {'type': 'op', 'cmd': '<save><config><to>{0}</to></config></save>'.format(filename)} return __proxy__['panos.call'](query) def save_device_state(): ''' Save files needed to restore device to local disk. CLI Example: .. code-block:: bash salt '*' panos.save_device_state ''' query = {'type': 'op', 'cmd': '<save><device-state></device-state></save>'} return __proxy__['panos.call'](query) def set_authentication_profile(profile=None, deploy=False): ''' Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_authentication_profile foo salt '*' panos.set_authentication_profile foo deploy=True ''' if not profile: raise CommandExecutionError("Profile name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/' 'authentication-profile', 'element': '<authentication-profile>{0}</authentication-profile>'.format(profile)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_hostname(hostname=None, deploy=False): ''' Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True ''' if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system', 'element': '<hostname>{0}</hostname>'.format(hostname)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_icmp(enabled=True, deploy=False): ''' Enables or disables the ICMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_icmp salt '*' panos.set_management_icmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-icmp>{0}</disable-icmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_http(enabled=True, deploy=False): ''' Enables or disables the HTTP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_http salt '*' panos.set_management_http enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http>{0}</disable-http>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_https(enabled=True, deploy=False): ''' Enables or disables the HTTPS management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_https salt '*' panos.set_management_https enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-https>{0}</disable-https>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ocsp(enabled=True, deploy=False): ''' Enables or disables the HTTP OCSP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ocsp salt '*' panos.set_management_ocsp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http-ocsp>{0}</disable-http-ocsp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_snmp(enabled=True, deploy=False): ''' Enables or disables the SNMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_snmp salt '*' panos.set_management_snmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-snmp>{0}</disable-snmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ssh(enabled=True, deploy=False): ''' Enables or disables the SSH management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ssh salt '*' panos.set_management_ssh enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-ssh>{0}</disable-ssh>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_telnet(enabled=True, deploy=False): ''' Enables or disables the Telnet management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_telnet salt '*' panos.set_management_telnet enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-telnet>{0}</disable-telnet>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_ntp_authentication(target=None, authentication_type=None, key_id=None, authentication_key=None, algorithm=None, deploy=False): ''' Set the NTP authentication of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: target(str): Determines the target of the authentication. Valid options are primary, secondary, or both. authentication_type(str): The authentication type to be used. Valid options are symmetric, autokey, and none. key_id(int): The NTP authentication key ID. authentication_key(str): The authentication key. algorithm(str): The algorithm type to be used for a symmetric key. Valid options are md5 and sha1. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_authentication target=both authentication_type=autokey salt '*' ntp.set_authentication target=primary authentication_type=none salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 deploy=True ''' ret = {} if target not in ['primary', 'secondary', 'both']: raise salt.exceptions.CommandExecutionError("Target option must be primary, secondary, or both.") if authentication_type not in ['symmetric', 'autokey', 'none']: raise salt.exceptions.CommandExecutionError("Type option must be symmetric, autokey, or both.") if authentication_type == "symmetric" and not authentication_key: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, authentication_key must be " "provided.") if authentication_type == "symmetric" and not key_id: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, key_id must be provided.") if authentication_type == "symmetric" and algorithm not in ['md5', 'sha1']: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, algorithm must be md5 or " "sha1.") if authentication_type == 'symmetric': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'autokey': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'none': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): ''' Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server(str): The secondary NTP server IP address or FQDN. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_servers 0.pool.ntp.org 1.pool.ntp.org salt '*' ntp.set_servers primary_server=0.pool.ntp.org secondary_server=1.pool.ntp.org salt '*' ntp.ser_servers 0.pool.ntp.org 1.pool.ntp.org deploy=True ''' ret = {} if primary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(primary_server)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if secondary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(secondary_server)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_timezone UTC salt '*' panos.set_timezone UTC deploy=True ''' if not tz: raise CommandExecutionError("Timezone name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/timezone', 'element': '<timezone>{0}</timezone>'.format(tz)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def shutdown(): ''' Shutdown a running system. CLI Example: .. code-block:: bash salt '*' panos.shutdown ''' query = {'type': 'op', 'cmd': '<request><shutdown><system></system></shutdown></request>'} return __proxy__['panos.call'](query) def test_fib_route(ip=None, vr='vr1'): ''' Perform a route lookup within active route table (fib). ip (str): The destination IP address to test. vr (str): The name of the virtual router to test. CLI Example: .. code-block:: bash salt '*' panos.test_fib_route 4.2.2.2 salt '*' panos.test_fib_route 4.2.2.2 my-vr ''' xpath = "<test><routing><fib-lookup>" if ip: xpath += "<ip>{0}</ip>".format(ip) if vr: xpath += "<virtual-router>{0}</virtual-router>".format(vr) xpath += "</fib-lookup></routing></test>" query = {'type': 'op', 'cmd': xpath} return __proxy__['panos.call'](query) def test_security_policy(sourcezone=None, destinationzone=None, source=None, destination=None, protocol=None, port=None, application=None, category=None, vsys='1', allrules=False): ''' Checks which security policy as connection will match on the device. sourcezone (str): The source zone matched against the connection. destinationzone (str): The destination zone matched against the connection. source (str): The source address. This must be a single IP address. destination (str): The destination address. This must be a single IP address. protocol (int): The protocol number for the connection. This is the numerical representation of the protocol. port (int): The port number for the connection. application (str): The application that should be matched. category (str): The category that should be matched. vsys (int): The numerical representation of the VSYS ID. allrules (bool): Show all potential match rules until first allow rule. CLI Example: .. code-block:: bash salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 vsys=2 ''' xpath = "<test><security-policy-match>" if sourcezone: xpath += "<from>{0}</from>".format(sourcezone) if destinationzone: xpath += "<to>{0}</to>".format(destinationzone) if source: xpath += "<source>{0}</source>".format(source) if destination: xpath += "<destination>{0}</destination>".format(destination) if protocol: xpath += "<protocol>{0}</protocol>".format(protocol) if port: xpath += "<destination-port>{0}</destination-port>".format(port) if application: xpath += "<application>{0}</application>".format(application) if category: xpath += "<category>{0}</category>".format(category) if allrules: xpath += "<show-all>yes</show-all>" xpath += "</security-policy-match></test>" query = {'type': 'op', 'vsys': "vsys{0}".format(vsys), 'cmd': xpath} return __proxy__['panos.call'](query) def unlock_admin(username=None): ''' Unlocks a locked administrator account. username Username of the administrator. CLI Example: .. code-block:: bash salt '*' panos.unlock_admin username=bob ''' if not username: raise CommandExecutionError("Username option must not be none.") query = {'type': 'op', 'cmd': '<set><management-server><unlock><admin>{0}</admin></unlock></management-server>' '</set>'.format(username)} return __proxy__['panos.call'](query)
saltstack/salt
salt/modules/panos.py
set_timezone
python
def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_timezone UTC salt '*' panos.set_timezone UTC deploy=True ''' if not tz: raise CommandExecutionError("Timezone name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/timezone', 'element': '<timezone>{0}</timezone>'.format(tz)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret
Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_timezone UTC salt '*' panos.set_timezone UTC deploy=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/panos.py#L2150-L2183
[ "def commit():\n '''\n Commits the candidate configuration to the running configuration.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' panos.commit\n\n '''\n query = {'type': 'commit', 'cmd': '<commit></commit>'}\n\n return _get_job_results(query)\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Palo Alto compatibility to Salt :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix .. versionadded:: 2018.3.0 Configuration ============= This module accepts connection configuration details either as parameters, or as configuration settings in pillar as a Salt proxy. Options passed into opts will be ignored if options are passed into pillar. .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` About ===== This execution module was designed to handle connections to a Palo Alto based firewall. This module adds support to send connections directly to the device through the XML API or through a brokered connection to Panorama. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import Salt Libs from salt.exceptions import CommandExecutionError import salt.proxy.panos import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'panos' def __virtual__(): ''' Will load for the panos proxy minions. ''' try: if salt.utils.platform.is_proxy() and \ __opts__['proxy']['proxytype'] == 'panos': return __virtualname__ except KeyError: pass return False, 'The panos execution module can only be loaded for panos proxy minions.' def _get_job_results(query=None): ''' Executes a query that requires a job for completion. This function will wait for the job to complete and return the results. ''' if not query: raise CommandExecutionError("Query parameters cannot be empty.") response = __proxy__['panos.call'](query) # If the response contains a job, we will wait for the results if 'result' in response and 'job' in response['result']: jid = response['result']['job'] while get_job(jid)['result']['job']['status'] != 'FIN': time.sleep(5) return get_job(jid) else: return response def add_config_lock(): ''' Prevent other users from changing configuration until the lock is released. CLI Example: .. code-block:: bash salt '*' panos.add_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><add></add></config-lock></request>'} return __proxy__['panos.call'](query) def check_antivirus(): ''' Get anti-virus information from PaloAlto Networks server CLI Example: .. code-block:: bash salt '*' panos.check_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><check></check></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def check_software(): ''' Get software information from PaloAlto Networks server. CLI Example: .. code-block:: bash salt '*' panos.check_software ''' query = {'type': 'op', 'cmd': '<request><system><software><check></check></software></system></request>'} return __proxy__['panos.call'](query) def clear_commit_tasks(): ''' Clear all commit tasks. CLI Example: .. code-block:: bash salt '*' panos.clear_commit_tasks ''' query = {'type': 'op', 'cmd': '<request><clear-commit-tasks></clear-commit-tasks></request>'} return __proxy__['panos.call'](query) def commit(): ''' Commits the candidate configuration to the running configuration. CLI Example: .. code-block:: bash salt '*' panos.commit ''' query = {'type': 'commit', 'cmd': '<commit></commit>'} return _get_job_results(query) def deactivate_license(key_name=None): ''' Deactivates an installed license. Required version 7.0.0 or greater. key_name(str): The file name of the license key installed. CLI Example: .. code-block:: bash salt '*' panos.deactivate_license key_name=License_File_Name.key ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<request><license><deactivate><key><features><member>{0}</member></features>' '</key></deactivate></license></request>'.format(key_name)} return __proxy__['panos.call'](query) def delete_license(key_name=None): ''' Remove license keys on disk. key_name(str): The file name of the license key to be deleted. CLI Example: .. code-block:: bash salt '*' panos.delete_license key_name=License_File_Name.key ''' if not key_name: return False, 'You must specify a key_name.' else: query = {'type': 'op', 'cmd': '<delete><license><key>{0}</key></license></delete>'.format(key_name)} return __proxy__['panos.call'](query) def download_antivirus(): ''' Download the most recent anti-virus package. CLI Example: .. code-block:: bash salt '*' panos.download_antivirus ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><download>' '<latest></latest></download></upgrade></anti-virus></request>'} return _get_job_results(query) def download_software_file(filename=None, synch=False): ''' Download software packages by filename. Args: filename(str): The filename of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_file PanOS_5000-8.0.0 salt '*' panos.download_software_file PanOS_5000-8.0.0 True ''' if not filename: raise CommandExecutionError("Filename option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<file>{0}</file></download></software></system></request>'.format(filename)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<file>{0}</file></download></software></system></request>'.format(filename)} return _get_job_results(query) def download_software_version(version=None, synch=False): ''' Download software packages by version number. Args: version(str): The version of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_version 8.0.0 salt '*' panos.download_software_version 8.0.0 True ''' if not version: raise CommandExecutionError("Version option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', 'cmd': '<request><system><software><download>' '<version>{0}</version></download></software></system></request>'.format(version)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<version>{0}</version></download></software></system></request>'.format(version)} return _get_job_results(query) def fetch_license(auth_code=None): ''' Get new license(s) using from the Palo Alto Network Server. auth_code The license authorization code. CLI Example: .. code-block:: bash salt '*' panos.fetch_license salt '*' panos.fetch_license auth_code=foobar ''' if not auth_code: query = {'type': 'op', 'cmd': '<request><license><fetch></fetch></license></request>'} else: query = {'type': 'op', 'cmd': '<request><license><fetch><auth-code>{0}</auth-code></fetch></license>' '</request>'.format(auth_code)} return __proxy__['panos.call'](query) def get_address(address=None, vsys='1'): ''' Get the candidate configuration for the specified get_address object. This will not return address objects that are marked as pre-defined objects. address(str): The name of the address object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address myhost salt '*' panos.get_address myhost 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address/entry[@name=\'{1}\']'.format(vsys, address)} return __proxy__['panos.call'](query) def get_address_group(addressgroup=None, vsys='1'): ''' Get the candidate configuration for the specified address group. This will not return address groups that are marked as pre-defined objects. addressgroup(str): The name of the address group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_address_group foobar salt '*' panos.get_address_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'address-group/entry[@name=\'{1}\']'.format(vsys, addressgroup)} return __proxy__['panos.call'](query) def get_admins_active(): ''' Show active administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_active ''' query = {'type': 'op', 'cmd': '<show><admins></admins></show>'} return __proxy__['panos.call'](query) def get_admins_all(): ''' Show all administrators. CLI Example: .. code-block:: bash salt '*' panos.get_admins_all ''' query = {'type': 'op', 'cmd': '<show><admins><all></all></admins></show>'} return __proxy__['panos.call'](query) def get_antivirus_info(): ''' Show information about available anti-virus packages. CLI Example: .. code-block:: bash salt '*' panos.get_antivirus_info ''' query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><info></info></upgrade></anti-virus></request>'} return __proxy__['panos.call'](query) def get_arp(): ''' Show ARP information. CLI Example: .. code-block:: bash salt '*' panos.get_arp ''' query = {'type': 'op', 'cmd': '<show><arp><entry name = \'all\'/></arp></show>'} return __proxy__['panos.call'](query) def get_cli_idle_timeout(): ''' Show timeout information for this administrative session. CLI Example: .. code-block:: bash salt '*' panos.get_cli_idle_timeout ''' query = {'type': 'op', 'cmd': '<show><cli><idle-timeout></idle-timeout></cli></show>'} return __proxy__['panos.call'](query) def get_cli_permissions(): ''' Show cli administrative permissions. CLI Example: .. code-block:: bash salt '*' panos.get_cli_permissions ''' query = {'type': 'op', 'cmd': '<show><cli><permissions></permissions></cli></show>'} return __proxy__['panos.call'](query) def get_disk_usage(): ''' Report filesystem disk space usage. CLI Example: .. code-block:: bash salt '*' panos.get_disk_usage ''' query = {'type': 'op', 'cmd': '<show><system><disk-space></disk-space></system></show>'} return __proxy__['panos.call'](query) def get_dns_server_config(): ''' Get the DNS server configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_dns_server_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/dns-setting/servers'} return __proxy__['panos.call'](query) def get_domain_config(): ''' Get the domain name configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_domain_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/domain'} return __proxy__['panos.call'](query) def get_dos_blocks(): ''' Show the DoS block-ip table. CLI Example: .. code-block:: bash salt '*' panos.get_dos_blocks ''' query = {'type': 'op', 'cmd': '<show><dos-block-table><all></all></dos-block-table></show>'} return __proxy__['panos.call'](query) def get_fqdn_cache(): ''' Print FQDNs used in rules and their IPs. CLI Example: .. code-block:: bash salt '*' panos.get_fqdn_cache ''' query = {'type': 'op', 'cmd': '<request><system><fqdn><show></show></fqdn></system></request>'} return __proxy__['panos.call'](query) def get_ha_config(): ''' Get the high availability configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ha_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/high-availability'} return __proxy__['panos.call'](query) def get_ha_link(): ''' Show high-availability link-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_link ''' query = {'type': 'op', 'cmd': '<show><high-availability><link-monitoring></link-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_path(): ''' Show high-availability path-monitoring state. CLI Example: .. code-block:: bash salt '*' panos.get_ha_path ''' query = {'type': 'op', 'cmd': '<show><high-availability><path-monitoring></path-monitoring></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_state(): ''' Show high-availability state information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_state ''' query = {'type': 'op', 'cmd': '<show><high-availability><state></state></high-availability></show>'} return __proxy__['panos.call'](query) def get_ha_transitions(): ''' Show high-availability transition statistic information. CLI Example: .. code-block:: bash salt '*' panos.get_ha_transitions ''' query = {'type': 'op', 'cmd': '<show><high-availability><transitions></transitions></high-availability></show>'} return __proxy__['panos.call'](query) def get_hostname(): ''' Get the hostname of the device. CLI Example: .. code-block:: bash salt '*' panos.get_hostname ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/hostname'} return __proxy__['panos.call'](query) def get_interface_counters(name='all'): ''' Get the counter statistics for interfaces. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interface_counters salt '*' panos.get_interface_counters ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><counter><interface>{0}</interface></counter></show>'.format(name)} return __proxy__['panos.call'](query) def get_interfaces(name='all'): ''' Show interface information. Args: name (str): The name of the interface to view. By default, all interface statistics are viewed. CLI Example: .. code-block:: bash salt '*' panos.get_interfaces salt '*' panos.get_interfaces ethernet1/1 ''' query = {'type': 'op', 'cmd': '<show><interface>{0}</interface></show>'.format(name)} return __proxy__['panos.call'](query) def get_job(jid=None): ''' List all a single job by ID. jid The ID of the job to retrieve. CLI Example: .. code-block:: bash salt '*' panos.get_job jid=15 ''' if not jid: raise CommandExecutionError("ID option must not be none.") query = {'type': 'op', 'cmd': '<show><jobs><id>{0}</id></jobs></show>'.format(jid)} return __proxy__['panos.call'](query) def get_jobs(state='all'): ''' List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending ''' if state.lower() == 'all': query = {'type': 'op', 'cmd': '<show><jobs><all></all></jobs></show>'} elif state.lower() == 'pending': query = {'type': 'op', 'cmd': '<show><jobs><pending></pending></jobs></show>'} elif state.lower() == 'processed': query = {'type': 'op', 'cmd': '<show><jobs><processed></processed></jobs></show>'} else: raise CommandExecutionError("The state parameter must be all, pending, or processed.") return __proxy__['panos.call'](query) def get_lacp(): ''' Show LACP state. CLI Example: .. code-block:: bash salt '*' panos.get_lacp ''' query = {'type': 'op', 'cmd': '<show><lacp><aggregate-ethernet>all</aggregate-ethernet></lacp></show>'} return __proxy__['panos.call'](query) def get_license_info(): ''' Show information about owned license(s). CLI Example: .. code-block:: bash salt '*' panos.get_license_info ''' query = {'type': 'op', 'cmd': '<request><license><info></info></license></request>'} return __proxy__['panos.call'](query) def get_license_tokens(): ''' Show license token files for manual license deactivation. CLI Example: .. code-block:: bash salt '*' panos.get_license_tokens ''' query = {'type': 'op', 'cmd': '<show><license-token-files></license-token-files></show>'} return __proxy__['panos.call'](query) def get_lldp_config(): ''' Show lldp config for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_config ''' query = {'type': 'op', 'cmd': '<show><lldp><config>all</config></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_counters(): ''' Show lldp counters for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_counters ''' query = {'type': 'op', 'cmd': '<show><lldp><counters>all</counters></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_local(): ''' Show lldp local info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_local ''' query = {'type': 'op', 'cmd': '<show><lldp><local>all</local></lldp></show>'} return __proxy__['panos.call'](query) def get_lldp_neighbors(): ''' Show lldp neighbors info for interfaces. CLI Example: .. code-block:: bash salt '*' panos.get_lldp_neighbors ''' query = {'type': 'op', 'cmd': '<show><lldp><neighbors>all</neighbors></lldp></show>'} return __proxy__['panos.call'](query) def get_local_admins(): ''' Show all local administrator accounts. CLI Example: .. code-block:: bash salt '*' panos.get_local_admins ''' admin_list = get_users_config() response = [] if 'users' not in admin_list['result']: return response if isinstance(admin_list['result']['users']['entry'], list): for entry in admin_list['result']['users']['entry']: response.append(entry['name']) else: response.append(admin_list['result']['users']['entry']['name']) return response def get_logdb_quota(): ''' Report the logdb quotas. CLI Example: .. code-block:: bash salt '*' panos.get_logdb_quota ''' query = {'type': 'op', 'cmd': '<show><system><logdb-quota></logdb-quota></system></show>'} return __proxy__['panos.call'](query) def get_master_key(): ''' Get the master key properties. CLI Example: .. code-block:: bash salt '*' panos.get_master_key ''' query = {'type': 'op', 'cmd': '<show><system><masterkey-properties></masterkey-properties></system></show>'} return __proxy__['panos.call'](query) def get_ntp_config(): ''' Get the NTP configuration from the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers'} return __proxy__['panos.call'](query) def get_ntp_servers(): ''' Get list of configured NTP servers. CLI Example: .. code-block:: bash salt '*' panos.get_ntp_servers ''' query = {'type': 'op', 'cmd': '<show><ntp></ntp></show>'} return __proxy__['panos.call'](query) def get_operational_mode(): ''' Show device operational mode setting. CLI Example: .. code-block:: bash salt '*' panos.get_operational_mode ''' query = {'type': 'op', 'cmd': '<show><operational-mode></operational-mode></show>'} return __proxy__['panos.call'](query) def get_panorama_status(): ''' Show panorama connection status. CLI Example: .. code-block:: bash salt '*' panos.get_panorama_status ''' query = {'type': 'op', 'cmd': '<show><panorama-status></panorama-status></show>'} return __proxy__['panos.call'](query) def get_permitted_ips(): ''' Get the IP addresses that are permitted to establish management connections to the device. CLI Example: .. code-block:: bash salt '*' panos.get_permitted_ips ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip'} return __proxy__['panos.call'](query) def get_platform(): ''' Get the platform model information and limitations. CLI Example: .. code-block:: bash salt '*' panos.get_platform ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/platform'} return __proxy__['panos.call'](query) def get_predefined_application(application=None): ''' Get the configuration for the specified pre-defined application object. This will only return pre-defined application objects. application(str): The name of the pre-defined application object. CLI Example: .. code-block:: bash salt '*' panos.get_predefined_application saltstack ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/predefined/application/entry[@name=\'{0}\']'.format(application)} return __proxy__['panos.call'](query) def get_security_rule(rulename=None, vsys='1'): ''' Get the candidate configuration for the specified security rule. rulename(str): The name of the security rule. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_security_rule rule01 salt '*' panos.get_security_rule rule01 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'rulebase/security/rules/entry[@name=\'{1}\']'.format(vsys, rulename)} return __proxy__['panos.call'](query) def get_service(service=None, vsys='1'): ''' Get the candidate configuration for the specified service object. This will not return services that are marked as pre-defined objects. service(str): The name of the service object. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service tcp-443 salt '*' panos.get_service tcp-443 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service/entry[@name=\'{1}\']'.format(vsys, service)} return __proxy__['panos.call'](query) def get_service_group(servicegroup=None, vsys='1'): ''' Get the candidate configuration for the specified service group. This will not return service groups that are marked as pre-defined objects. servicegroup(str): The name of the service group. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_service_group foobar salt '*' panos.get_service_group foobar 3 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'service-group/entry[@name=\'{1}\']'.format(vsys, servicegroup)} return __proxy__['panos.call'](query) def get_session_info(): ''' Show device session statistics. CLI Example: .. code-block:: bash salt '*' panos.get_session_info ''' query = {'type': 'op', 'cmd': '<show><session><info></info></session></show>'} return __proxy__['panos.call'](query) def get_snmp_config(): ''' Get the SNMP configuration from the device. CLI Example: .. code-block:: bash salt '*' panos.get_snmp_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/snmp-setting'} return __proxy__['panos.call'](query) def get_software_info(): ''' Show information about available software packages. CLI Example: .. code-block:: bash salt '*' panos.get_software_info ''' query = {'type': 'op', 'cmd': '<request><system><software><info></info></software></system></request>'} return __proxy__['panos.call'](query) def get_system_date_time(): ''' Get the system date/time. CLI Example: .. code-block:: bash salt '*' panos.get_system_date_time ''' query = {'type': 'op', 'cmd': '<show><clock></clock></show>'} return __proxy__['panos.call'](query) def get_system_files(): ''' List important files in the system. CLI Example: .. code-block:: bash salt '*' panos.get_system_files ''' query = {'type': 'op', 'cmd': '<show><system><files></files></system></show>'} return __proxy__['panos.call'](query) def get_system_info(): ''' Get the system information. CLI Example: .. code-block:: bash salt '*' panos.get_system_info ''' query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'} return __proxy__['panos.call'](query) def get_system_services(): ''' Show system services. CLI Example: .. code-block:: bash salt '*' panos.get_system_services ''' query = {'type': 'op', 'cmd': '<show><system><services></services></system></show>'} return __proxy__['panos.call'](query) def get_system_state(mask=None): ''' Show the system state variables. mask Filters by a subtree or a wildcard. CLI Example: .. code-block:: bash salt '*' panos.get_system_state salt '*' panos.get_system_state mask=cfg.ha.config.enabled salt '*' panos.get_system_state mask=cfg.ha.* ''' if mask: query = {'type': 'op', 'cmd': '<show><system><state><filter>{0}</filter></state></system></show>'.format(mask)} else: query = {'type': 'op', 'cmd': '<show><system><state></state></system></show>'} return __proxy__['panos.call'](query) def get_uncommitted_changes(): ''' Retrieve a list of all uncommitted changes on the device. Requires PANOS version 8.0.0 or greater. CLI Example: .. code-block:: bash salt '*' panos.get_uncommitted_changes ''' _required_version = '8.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) query = {'type': 'op', 'cmd': '<show><config><list><changes></changes></list></config></show>'} return __proxy__['panos.call'](query) def get_users_config(): ''' Get the local administrative user account configuration. CLI Example: .. code-block:: bash salt '*' panos.get_users_config ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/mgt-config/users'} return __proxy__['panos.call'](query) def get_vlans(): ''' Show all VLAN information. CLI Example: .. code-block:: bash salt '*' panos.get_vlans ''' query = {'type': 'op', 'cmd': '<show><vlan>all</vlan></show>'} return __proxy__['panos.call'](query) def get_xpath(xpath=''): ''' Retrieve a specified xpath from the candidate configuration. xpath(str): The specified xpath in the candidate configuration. CLI Example: .. code-block:: bash salt '*' panos.get_xpath /config/shared/service ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} return __proxy__['panos.call'](query) def get_zone(zone='', vsys='1'): ''' Get the candidate configuration for the specified zone. zone(str): The name of the zone. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zone trust salt '*' panos.get_zone trust 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone/entry[@name=\'{1}\']'.format(vsys, zone)} return __proxy__['panos.call'](query) def get_zones(vsys='1'): ''' Get all the zones in the candidate configuration. vsys(str): The string representation of the VSYS ID. CLI Example: .. code-block:: bash salt '*' panos.get_zones salt '*' panos.get_zones 2 ''' query = {'type': 'config', 'action': 'get', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/' 'zone'.format(vsys)} return __proxy__['panos.call'](query) def install_antivirus(version=None, latest=False, synch=False, skip_commit=False,): ''' Install anti-virus packages. Args: version(str): The version of the PANOS file to install. latest(bool): If true, the latest anti-virus file will be installed. The specified version option will be ignored. synch(bool): If true, the anti-virus will synch to the peer unit. skip_commit(bool): If true, the install will skip committing to the device. CLI Example: .. code-block:: bash salt '*' panos.install_antivirus 8.0.0 ''' if not version and latest is False: raise CommandExecutionError("Version option must not be none.") if synch is True: s = "yes" else: s = "no" if skip_commit is True: c = "yes" else: c = "no" if latest is True: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>latest</version></install></upgrade></anti-virus></request>'.format(c, s)} else: query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install>' '<commit>{0}</commit><sync-to-peer>{1}</sync-to-peer>' '<version>{2}</version></install></upgrade></anti-virus></request>'.format(c, s, version)} return _get_job_results(query) def install_license(): ''' Install the license key(s). CLI Example: .. code-block:: bash salt '*' panos.install_license ''' query = {'type': 'op', 'cmd': '<request><license><install></install></license></request>'} return __proxy__['panos.call'](query) def install_software(version=None): ''' Upgrade to a software package by version. Args: version(str): The version of the PANOS file to install. CLI Example: .. code-block:: bash salt '*' panos.install_license 8.0.0 ''' if not version: raise CommandExecutionError("Version option must not be none.") query = {'type': 'op', 'cmd': '<request><system><software><install>' '<version>{0}</version></install></software></system></request>'.format(version)} return _get_job_results(query) def reboot(): ''' Reboot a running system. CLI Example: .. code-block:: bash salt '*' panos.reboot ''' query = {'type': 'op', 'cmd': '<request><restart><system></system></restart></request>'} return __proxy__['panos.call'](query) def refresh_fqdn_cache(force=False): ''' Force refreshes all FQDNs used in rules. force Forces all fqdn refresh CLI Example: .. code-block:: bash salt '*' panos.refresh_fqdn_cache salt '*' panos.refresh_fqdn_cache force=True ''' if not isinstance(force, bool): raise CommandExecutionError("Force option must be boolean.") if force: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh><force>yes</force></refresh></fqdn></system></request>'} else: query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh></refresh></fqdn></system></request>'} return __proxy__['panos.call'](query) def remove_config_lock(): ''' Release config lock previously held. CLI Example: .. code-block:: bash salt '*' panos.remove_config_lock ''' query = {'type': 'op', 'cmd': '<request><config-lock><remove></remove></config-lock></request>'} return __proxy__['panos.call'](query) def resolve_address(address=None, vsys=None): ''' Resolve address to ip address. Required version 7.0.0 or greater. address Address name you want to resolve. vsys The vsys name. CLI Example: .. code-block:: bash salt '*' panos.resolve_address foo.bar.com salt '*' panos.resolve_address foo.bar.com vsys=2 ''' _required_version = '7.0.0' if not __proxy__['panos.is_required_version'](_required_version): return False, 'The panos device requires version {0} or greater for this command.'.format(_required_version) if not address: raise CommandExecutionError("FQDN to resolve must be provided as address.") if not vsys: query = {'type': 'op', 'cmd': '<request><resolve><address>{0}</address></resolve></request>'.format(address)} else: query = {'type': 'op', 'cmd': '<request><resolve><vsys>{0}</vsys><address>{1}</address></resolve>' '</request>'.format(vsys, address)} return __proxy__['panos.call'](query) def save_device_config(filename=None): ''' Save device configuration to a named file. filename The filename to save the configuration to. CLI Example: .. code-block:: bash salt '*' panos.save_device_config foo.xml ''' if not filename: raise CommandExecutionError("Filename must not be empty.") query = {'type': 'op', 'cmd': '<save><config><to>{0}</to></config></save>'.format(filename)} return __proxy__['panos.call'](query) def save_device_state(): ''' Save files needed to restore device to local disk. CLI Example: .. code-block:: bash salt '*' panos.save_device_state ''' query = {'type': 'op', 'cmd': '<save><device-state></device-state></save>'} return __proxy__['panos.call'](query) def set_authentication_profile(profile=None, deploy=False): ''' Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_authentication_profile foo salt '*' panos.set_authentication_profile foo deploy=True ''' if not profile: raise CommandExecutionError("Profile name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/' 'authentication-profile', 'element': '<authentication-profile>{0}</authentication-profile>'.format(profile)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_hostname(hostname=None, deploy=False): ''' Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True ''' if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system', 'element': '<hostname>{0}</hostname>'.format(hostname)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_icmp(enabled=True, deploy=False): ''' Enables or disables the ICMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_icmp salt '*' panos.set_management_icmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-icmp>{0}</disable-icmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_http(enabled=True, deploy=False): ''' Enables or disables the HTTP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_http salt '*' panos.set_management_http enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http>{0}</disable-http>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_https(enabled=True, deploy=False): ''' Enables or disables the HTTPS management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_https salt '*' panos.set_management_https enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-https>{0}</disable-https>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ocsp(enabled=True, deploy=False): ''' Enables or disables the HTTP OCSP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ocsp salt '*' panos.set_management_ocsp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-http-ocsp>{0}</disable-http-ocsp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_snmp(enabled=True, deploy=False): ''' Enables or disables the SNMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_snmp salt '*' panos.set_management_snmp enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-snmp>{0}</disable-snmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_ssh(enabled=True, deploy=False): ''' Enables or disables the SSH management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_ssh salt '*' panos.set_management_ssh enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-ssh>{0}</disable-ssh>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_management_telnet(enabled=True, deploy=False): ''' Enables or disables the Telnet management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_management_telnet salt '*' panos.set_management_telnet enabled=False deploy=True ''' if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-telnet>{0}</disable-telnet>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def set_ntp_authentication(target=None, authentication_type=None, key_id=None, authentication_key=None, algorithm=None, deploy=False): ''' Set the NTP authentication of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: target(str): Determines the target of the authentication. Valid options are primary, secondary, or both. authentication_type(str): The authentication type to be used. Valid options are symmetric, autokey, and none. key_id(int): The NTP authentication key ID. authentication_key(str): The authentication key. algorithm(str): The algorithm type to be used for a symmetric key. Valid options are md5 and sha1. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_authentication target=both authentication_type=autokey salt '*' ntp.set_authentication target=primary authentication_type=none salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 salt '*' ntp.set_authentication target=both authentication_type=symmetric key_id=15 authentication_key=mykey algorithm=md5 deploy=True ''' ret = {} if target not in ['primary', 'secondary', 'both']: raise salt.exceptions.CommandExecutionError("Target option must be primary, secondary, or both.") if authentication_type not in ['symmetric', 'autokey', 'none']: raise salt.exceptions.CommandExecutionError("Type option must be symmetric, autokey, or both.") if authentication_type == "symmetric" and not authentication_key: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, authentication_key must be " "provided.") if authentication_type == "symmetric" and not key_id: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, key_id must be provided.") if authentication_type == "symmetric" and algorithm not in ['md5', 'sha1']: raise salt.exceptions.CommandExecutionError("When using symmetric authentication, algorithm must be md5 or " "sha1.") if authentication_type == 'symmetric': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<symmetric-key><algorithm><{0}><authentication-key>{1}</authentication-key></{0}>' '</algorithm><key-id>{2}</key-id></symmetric-key>'.format(algorithm, authentication_key, key_id)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'autokey': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<autokey/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) elif authentication_type == 'none': if target == 'primary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'primary_server': __proxy__['panos.call'](query)}) if target == 'secondary' or target == 'both': query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server/authentication-type', 'element': '<none/>'} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): ''' Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server(str): The secondary NTP server IP address or FQDN. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' ntp.set_servers 0.pool.ntp.org 1.pool.ntp.org salt '*' ntp.set_servers primary_server=0.pool.ntp.org secondary_server=1.pool.ntp.org salt '*' ntp.ser_servers 0.pool.ntp.org 1.pool.ntp.org deploy=True ''' ret = {} if primary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'primary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(primary_server)} ret.update({'primary_server': __proxy__['panos.call'](query)}) if secondary_server: query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/ntp-servers/' 'secondary-ntp-server', 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(secondary_server)} ret.update({'secondary_server': __proxy__['panos.call'](query)}) if deploy is True: ret.update(commit()) return ret def set_permitted_ip(address=None, deploy=False): ''' Add an IPv4 address or network to the permitted IP list. CLI Example: Args: address (str): The IPv4 address or network to allow access to add to the Palo Alto device. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_permitted_ip 10.0.0.1 salt '*' panos.set_permitted_ip 10.0.0.0/24 salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True ''' if not address: raise CommandExecutionError("Address option must not be empty.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip', 'element': '<entry name=\'{0}\'></entry>'.format(address)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret def shutdown(): ''' Shutdown a running system. CLI Example: .. code-block:: bash salt '*' panos.shutdown ''' query = {'type': 'op', 'cmd': '<request><shutdown><system></system></shutdown></request>'} return __proxy__['panos.call'](query) def test_fib_route(ip=None, vr='vr1'): ''' Perform a route lookup within active route table (fib). ip (str): The destination IP address to test. vr (str): The name of the virtual router to test. CLI Example: .. code-block:: bash salt '*' panos.test_fib_route 4.2.2.2 salt '*' panos.test_fib_route 4.2.2.2 my-vr ''' xpath = "<test><routing><fib-lookup>" if ip: xpath += "<ip>{0}</ip>".format(ip) if vr: xpath += "<virtual-router>{0}</virtual-router>".format(vr) xpath += "</fib-lookup></routing></test>" query = {'type': 'op', 'cmd': xpath} return __proxy__['panos.call'](query) def test_security_policy(sourcezone=None, destinationzone=None, source=None, destination=None, protocol=None, port=None, application=None, category=None, vsys='1', allrules=False): ''' Checks which security policy as connection will match on the device. sourcezone (str): The source zone matched against the connection. destinationzone (str): The destination zone matched against the connection. source (str): The source address. This must be a single IP address. destination (str): The destination address. This must be a single IP address. protocol (int): The protocol number for the connection. This is the numerical representation of the protocol. port (int): The port number for the connection. application (str): The application that should be matched. category (str): The category that should be matched. vsys (int): The numerical representation of the VSYS ID. allrules (bool): Show all potential match rules until first allow rule. CLI Example: .. code-block:: bash salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 salt '*' panos.test_security_policy sourcezone=trust destinationzone=untrust protocol=6 port=22 vsys=2 ''' xpath = "<test><security-policy-match>" if sourcezone: xpath += "<from>{0}</from>".format(sourcezone) if destinationzone: xpath += "<to>{0}</to>".format(destinationzone) if source: xpath += "<source>{0}</source>".format(source) if destination: xpath += "<destination>{0}</destination>".format(destination) if protocol: xpath += "<protocol>{0}</protocol>".format(protocol) if port: xpath += "<destination-port>{0}</destination-port>".format(port) if application: xpath += "<application>{0}</application>".format(application) if category: xpath += "<category>{0}</category>".format(category) if allrules: xpath += "<show-all>yes</show-all>" xpath += "</security-policy-match></test>" query = {'type': 'op', 'vsys': "vsys{0}".format(vsys), 'cmd': xpath} return __proxy__['panos.call'](query) def unlock_admin(username=None): ''' Unlocks a locked administrator account. username Username of the administrator. CLI Example: .. code-block:: bash salt '*' panos.unlock_admin username=bob ''' if not username: raise CommandExecutionError("Username option must not be none.") query = {'type': 'op', 'cmd': '<set><management-server><unlock><admin>{0}</admin></unlock></management-server>' '</set>'.format(username)} return __proxy__['panos.call'](query)
saltstack/salt
salt/states/vault.py
policy_present
python
def policy_present(name, rules): ''' Ensure a Vault policy with the given name and rules is present. name The name of the policy rules Rules formatted as in-line HCL .. code-block:: yaml demo-policy: vault.policy_present: - name: foo/bar - rules: | path "secret/top-secret/*" { policy = "deny" } path "secret/not-very-secret/*" { policy = "write" } ''' url = "v1/sys/policy/{0}".format(name) response = __utils__['vault.make_request']('GET', url) try: if response.status_code == 200: return _handle_existing_policy(name, rules, response.json()['rules']) elif response.status_code == 404: return _create_new_policy(name, rules) else: response.raise_for_status() except Exception as e: return { 'name': name, 'changes': {}, 'result': False, 'comment': 'Failed to get policy: {0}'.format(e) }
Ensure a Vault policy with the given name and rules is present. name The name of the policy rules Rules formatted as in-line HCL .. code-block:: yaml demo-policy: vault.policy_present: - name: foo/bar - rules: | path "secret/top-secret/*" { policy = "deny" } path "secret/not-very-secret/*" { policy = "write" }
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/vault.py#L21-L61
[ "def _handle_existing_policy(name, new_rules, existing_rules):\n ret = {'name': name}\n if new_rules == existing_rules:\n ret['result'] = True\n ret['changes'] = {}\n ret['comment'] = 'Policy exists, and has the correct content'\n return ret\n\n change = ''.join(difflib.unified_diff(existing_rules.splitlines(True), new_rules.splitlines(True)))\n if __opts__['test']:\n ret['result'] = None\n ret['changes'] = {name: {'change': change}}\n ret['comment'] = 'Policy would be changed'\n return ret\n\n payload = {'rules': new_rules}\n\n url = \"v1/sys/policy/{0}\".format(name)\n response = __utils__['vault.make_request']('PUT', url, json=payload)\n if response.status_code not in [200, 204]:\n return {\n 'name': name,\n 'changes': {},\n 'result': False,\n 'comment': 'Failed to change policy: {0}'.format(response.reason)\n }\n\n ret['result'] = True\n ret['changes'] = {name: {'change': change}}\n ret['comment'] = 'Policy was updated'\n\n return ret\n", "def _create_new_policy(name, rules):\n if __opts__['test']:\n return {\n 'name': name,\n 'changes': {name: {'old': '', 'new': rules}},\n 'result': None,\n 'comment': 'Policy would be created'\n }\n\n payload = {'rules': rules}\n url = \"v1/sys/policy/{0}\".format(name)\n response = __utils__['vault.make_request']('PUT', url, json=payload)\n if response.status_code not in [200, 204]:\n return {\n 'name': name,\n 'changes': {},\n 'result': False,\n 'comment': 'Failed to create policy: {0}'.format(response.reason)\n }\n\n return {\n 'name': name,\n 'result': True,\n 'changes': {name: {'old': None, 'new': rules}},\n 'comment': 'Policy was created'\n }\n" ]
# -*- coding: utf-8 -*- ''' States for managing Hashicorp Vault. Currently handles policies. Configuration instructions are documented in the execution module docs. :maintainer: SaltStack :maturity: new :platform: all .. versionadded:: 2017.7.0 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import difflib log = logging.getLogger(__name__) def _create_new_policy(name, rules): if __opts__['test']: return { 'name': name, 'changes': {name: {'old': '', 'new': rules}}, 'result': None, 'comment': 'Policy would be created' } payload = {'rules': rules} url = "v1/sys/policy/{0}".format(name) response = __utils__['vault.make_request']('PUT', url, json=payload) if response.status_code not in [200, 204]: return { 'name': name, 'changes': {}, 'result': False, 'comment': 'Failed to create policy: {0}'.format(response.reason) } return { 'name': name, 'result': True, 'changes': {name: {'old': None, 'new': rules}}, 'comment': 'Policy was created' } def _handle_existing_policy(name, new_rules, existing_rules): ret = {'name': name} if new_rules == existing_rules: ret['result'] = True ret['changes'] = {} ret['comment'] = 'Policy exists, and has the correct content' return ret change = ''.join(difflib.unified_diff(existing_rules.splitlines(True), new_rules.splitlines(True))) if __opts__['test']: ret['result'] = None ret['changes'] = {name: {'change': change}} ret['comment'] = 'Policy would be changed' return ret payload = {'rules': new_rules} url = "v1/sys/policy/{0}".format(name) response = __utils__['vault.make_request']('PUT', url, json=payload) if response.status_code not in [200, 204]: return { 'name': name, 'changes': {}, 'result': False, 'comment': 'Failed to change policy: {0}'.format(response.reason) } ret['result'] = True ret['changes'] = {name: {'change': change}} ret['comment'] = 'Policy was updated' return ret
saltstack/salt
salt/returners/rawfile_json.py
returner
python
def returner(ret): ''' Write the return data to a file on the minion. ''' opts = _get_options(ret) try: with salt.utils.files.flopen(opts['filename'], 'a') as logfile: salt.utils.json.dump(ret, logfile) logfile.write(str('\n')) # future lint: disable=blacklisted-function except Exception: log.error('Could not write to rawdata_json file %s', opts['filename']) raise
Write the return data to a file on the minion.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/rawfile_json.py#L54-L65
[ "def dump(obj, fp, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dump, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dump does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dump(obj, fp, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def _get_options(ret):\n '''\n Returns options used for the rawfile_json returner.\n '''\n defaults = {'filename': '/var/log/salt/events'}\n attrs = {'filename': 'filename'}\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__,\n defaults=defaults)\n\n return _options\n" ]
# -*- coding: utf-8 -*- ''' Take data from salt and "return" it into a raw file containing the json, with one line per event. Add the following to the minion or master configuration file. .. code-block:: yaml rawfile_json.filename: <path_to_output_file> Default is ``/var/log/salt/events``. Common use is to log all events on the master. This can generate a lot of noise, so you may wish to configure batch processing and/or configure the :conf_master:`event_return_whitelist` or :conf_master:`event_return_blacklist` to restrict the events that are written. ''' # Import python libs from __future__ import absolute_import, print_function, with_statement, unicode_literals import logging import salt.returners import salt.utils.files import salt.utils.json log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'rawfile_json' def __virtual__(): return __virtualname__ def _get_options(ret): ''' Returns options used for the rawfile_json returner. ''' defaults = {'filename': '/var/log/salt/events'} attrs = {'filename': 'filename'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__, defaults=defaults) return _options def event_return(events): ''' Write event data (return data and non-return data) to file on the master. ''' if not events: # events is an empty list. # Don't open the logfile in vain. return opts = _get_options({}) # Pass in empty ret, since this is a list of events try: with salt.utils.files.flopen(opts['filename'], 'a') as logfile: for event in events: salt.utils.json.dump(event, logfile) logfile.write(str('\n')) # future lint: disable=blacklisted-function except Exception: log.error('Could not write to rawdata_json file %s', opts['filename']) raise
saltstack/salt
salt/returners/rawfile_json.py
event_return
python
def event_return(events): ''' Write event data (return data and non-return data) to file on the master. ''' if not events: # events is an empty list. # Don't open the logfile in vain. return opts = _get_options({}) # Pass in empty ret, since this is a list of events try: with salt.utils.files.flopen(opts['filename'], 'a') as logfile: for event in events: salt.utils.json.dump(event, logfile) logfile.write(str('\n')) # future lint: disable=blacklisted-function except Exception: log.error('Could not write to rawdata_json file %s', opts['filename']) raise
Write event data (return data and non-return data) to file on the master.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/rawfile_json.py#L68-L84
[ "def dump(obj, fp, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dump, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dump does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dump(obj, fp, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def _get_options(ret):\n '''\n Returns options used for the rawfile_json returner.\n '''\n defaults = {'filename': '/var/log/salt/events'}\n attrs = {'filename': 'filename'}\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__,\n defaults=defaults)\n\n return _options\n" ]
# -*- coding: utf-8 -*- ''' Take data from salt and "return" it into a raw file containing the json, with one line per event. Add the following to the minion or master configuration file. .. code-block:: yaml rawfile_json.filename: <path_to_output_file> Default is ``/var/log/salt/events``. Common use is to log all events on the master. This can generate a lot of noise, so you may wish to configure batch processing and/or configure the :conf_master:`event_return_whitelist` or :conf_master:`event_return_blacklist` to restrict the events that are written. ''' # Import python libs from __future__ import absolute_import, print_function, with_statement, unicode_literals import logging import salt.returners import salt.utils.files import salt.utils.json log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'rawfile_json' def __virtual__(): return __virtualname__ def _get_options(ret): ''' Returns options used for the rawfile_json returner. ''' defaults = {'filename': '/var/log/salt/events'} attrs = {'filename': 'filename'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__, defaults=defaults) return _options def returner(ret): ''' Write the return data to a file on the minion. ''' opts = _get_options(ret) try: with salt.utils.files.flopen(opts['filename'], 'a') as logfile: salt.utils.json.dump(ret, logfile) logfile.write(str('\n')) # future lint: disable=blacklisted-function except Exception: log.error('Could not write to rawdata_json file %s', opts['filename']) raise
saltstack/salt
salt/states/zpool.py
_layout_to_vdev
python
def _layout_to_vdev(layout, device_dir=None): ''' Turn the layout data into usable vdevs spedcification We need to support 2 ways of passing the layout: .. code:: layout_new: - mirror: - disk0 - disk1 - mirror: - disk2 - disk3 .. code: layout_legacy: mirror-0: disk0 disk1 mirror-1: disk2 disk3 ''' vdevs = [] # NOTE: check device_dir exists if device_dir and not os.path.exists(device_dir): device_dir = None # NOTE: handle list of OrderedDicts (new layout) if isinstance(layout, list): # NOTE: parse each vdev as a tiny layout and just append for vdev in layout: if isinstance(vdev, OrderedDict): vdevs.extend(_layout_to_vdev(vdev, device_dir)) else: if device_dir and vdev[0] != '/': vdev = os.path.join(device_dir, vdev) vdevs.append(vdev) # NOTE: handle nested OrderedDict (legacy layout) # this is also used to parse the nested OrderedDicts # from the new layout elif isinstance(layout, OrderedDict): for vdev in layout: # NOTE: extract the vdev type and disks in the vdev vdev_type = vdev.split('-')[0] vdev_disk = layout[vdev] # NOTE: skip appending the dummy type 'disk' if vdev_type != 'disk': vdevs.append(vdev_type) # NOTE: ensure the disks are a list (legacy layout are not) if not isinstance(vdev_disk, list): vdev_disk = vdev_disk.split(' ') # NOTE: also append the actualy disks behind the type # also prepend device_dir to disks if required for disk in vdev_disk: if device_dir and disk[0] != '/': disk = os.path.join(device_dir, disk) vdevs.append(disk) # NOTE: we got invalid data for layout else: vdevs = None return vdevs
Turn the layout data into usable vdevs spedcification We need to support 2 ways of passing the layout: .. code:: layout_new: - mirror: - disk0 - disk1 - mirror: - disk2 - disk3 .. code: layout_legacy: mirror-0: disk0 disk1 mirror-1: disk2 disk3
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zpool.py#L97-L167
null
# -*- coding: utf-8 -*- ''' States for managing zpools :maintainer: Jorge Schrauwen <sjorge@blackdot.be> :maturity: new :depends: salt.utils.zfs, salt.modules.zpool :platform: smartos, illumos, solaris, freebsd, linux .. versionadded:: 2016.3.0 .. versionchanged:: 2018.3.1 Big refactor to remove duplicate code, better type converions and improved consistancy in output. .. code-block:: yaml oldpool: zpool.absent: - export: true newpool: zpool.present: - config: import: false force: true - properties: comment: salty storage pool - layout: - mirror: - /dev/disk0 - /dev/disk1 - mirror: - /dev/disk2 - /dev/disk3 partitionpool: zpool.present: - config: import: false force: true - properties: comment: disk partition salty storage pool ashift: '12' feature@lz4_compress: enabled - filesystem_properties: compression: lz4 atime: on relatime: on - layout: - /dev/disk/by-uuid/3e43ce94-77af-4f52-a91b-6cdbb0b0f41b simplepool: zpool.present: - config: import: false force: true - properties: comment: another salty storage pool - layout: - /dev/disk0 - /dev/disk1 .. warning:: The layout will never be updated, it will only be used at time of creation. It's a whole lot of work to figure out if a devices needs to be detached, removed, etc. This is best done by the sysadmin on a case per case basis. Filesystem properties are also not updated, this should be managed by the zfs state module. ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import os import logging # Import Salt libs from salt.utils.odict import OrderedDict log = logging.getLogger(__name__) # Define the state's virtual name __virtualname__ = 'zpool' def __virtual__(): ''' Provides zpool state ''' if __grains__['zfs_support']: return __virtualname__ else: return False, 'The zpool state cannot be loaded: zfs not supported' def present(name, properties=None, filesystem_properties=None, layout=None, config=None): ''' ensure storage pool is present on the system name : string name of storage pool properties : dict optional set of properties to set for the storage pool filesystem_properties : dict optional set of filesystem properties to set for the storage pool (creation only) layout: dict disk layout to use if the pool does not exist (creation only) config : dict fine grain control over this state .. note:: The following configuration properties can be toggled in the config parameter. - import (true) - try to import the pool before creating it if absent - import_dirs (None) - specify additional locations to scan for devices on import (comma-seperated) - device_dir (None, SunOS=/dev/dsk, Linux=/dev) - specify device directory to prepend for none absolute device paths - force (false) - try to force the import or creation .. note:: It is no longer needed to give a unique name to each top-level vdev, the old layout format is still supported but no longer recommended. .. code-block:: yaml - mirror: - /tmp/vdisk3 - /tmp/vdisk2 - mirror: - /tmp/vdisk0 - /tmp/vdisk1 The above yaml will always result in the following zpool create: .. code-block:: bash zpool create mypool mirror /tmp/vdisk3 /tmp/vdisk2 mirror /tmp/vdisk0 /tmp/vdisk1 .. warning:: The legacy format is also still supported but not recommended, because ID's inside the layout dict must be unique they need to have a suffix. .. code-block:: yaml mirror-0: /tmp/vdisk3 /tmp/vdisk2 mirror-1: /tmp/vdisk0 /tmp/vdisk1 .. warning:: Pay attention to the order of your dict! .. code-block:: yaml - mirror: - /tmp/vdisk0 - /tmp/vdisk1 - /tmp/vdisk2 The above will result in the following zpool create: .. code-block:: bash zpool create mypool mirror /tmp/vdisk0 /tmp/vdisk1 /tmp/vdisk2 Creating a 3-way mirror! While you probably expect it to be mirror root vdev with 2 devices + a root vdev of 1 device! ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} # config defaults default_config = { 'import': True, 'import_dirs': None, 'device_dir': None, 'force': False } if __grains__['kernel'] == 'SunOS': default_config['device_dir'] = '/dev/dsk' elif __grains__['kernel'] == 'Linux': default_config['device_dir'] = '/dev' # merge state config if config: default_config.update(config) config = default_config # ensure properties are zfs values if properties: properties = __utils__['zfs.from_auto_dict'](properties) elif properties is None: properties = {} if filesystem_properties: filesystem_properties = __utils__['zfs.from_auto_dict'](filesystem_properties) elif filesystem_properties is None: filesystem_properties = {} # parse layout vdevs = _layout_to_vdev(layout, config['device_dir']) if vdevs: vdevs.insert(0, name) # log configuration log.debug('zpool.present::%s::config - %s', name, config) log.debug('zpool.present::%s::vdevs - %s', name, vdevs) log.debug('zpool.present::%s::properties - %s', name, properties) log.debug('zpool.present::%s::filesystem_properties - %s', name, filesystem_properties) # ensure the pool is present ret['result'] = False # don't do anything because this is a test if __opts__['test']: ret['result'] = True if __salt__['zpool.exists'](name): ret['changes'][name] = 'uptodate' else: ret['changes'][name] = 'imported' if config['import'] else 'created' ret['comment'] = 'storage pool {0} was {1}'.format(name, ret['changes'][name]) # update pool elif __salt__['zpool.exists'](name): ret['result'] = True # fetch current pool properties properties_current = __salt__['zpool.get'](name, parsable=True) # build list of properties to update properties_update = [] if properties: for prop in properties: # skip unexisting properties if prop not in properties_current: log.warning('zpool.present::%s::update - unknown property: %s', name, prop) continue # compare current and wanted value if properties_current[prop] != properties[prop]: properties_update.append(prop) # update pool properties for prop in properties_update: res = __salt__['zpool.set'](name, prop, properties[prop]) if res['set']: if name not in ret['changes']: ret['changes'][name] = {} ret['changes'][name][prop] = properties[prop] else: ret['result'] = False if ret['comment'] == '': ret['comment'] = 'The following properties were not updated:' ret['comment'] = '{0} {1}'.format(ret['comment'], prop) if ret['result']: ret['comment'] = 'properties updated' if ret['changes'] else 'no update needed' # import or create the pool (at least try to anyway) else: # import pool if config['import']: mod_res = __salt__['zpool.import']( name, force=config['force'], dir=config['import_dirs'], ) ret['result'] = mod_res['imported'] if ret['result']: ret['changes'][name] = 'imported' ret['comment'] = 'storage pool {0} was imported'.format(name) # create pool if not ret['result'] and vdevs: log.debug('zpool.present::%s::creating', name) # execute zpool.create mod_res = __salt__['zpool.create']( *vdevs, force=config['force'], properties=properties, filesystem_properties=filesystem_properties ) ret['result'] = mod_res['created'] if ret['result']: ret['changes'][name] = 'created' ret['comment'] = 'storage pool {0} was created'.format(name) elif 'error' in mod_res: ret['comment'] = mod_res['error'] else: ret['comment'] = 'could not create storage pool {0}'.format(name) # give up, we cannot import the pool and we do not have a layout to create it if not ret['result'] and not vdevs: ret['comment'] = 'storage pool {0} was not imported, no (valid) layout specified for creation'.format(name) return ret def absent(name, export=False, force=False): ''' ensure storage pool is absent on the system name : string name of storage pool export : boolean export instread of destroy the zpool if present force : boolean force destroy or export ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} # log configuration log.debug('zpool.absent::%s::config::force = %s', name, force) log.debug('zpool.absent::%s::config::export = %s', name, export) # ensure the pool is absent if __salt__['zpool.exists'](name): # looks like we need to do some work mod_res = {} ret['result'] = False # NOTE: handle test if __opts__['test']: ret['result'] = True # NOTE: try to export the pool elif export: mod_res = __salt__['zpool.export'](name, force=force) ret['result'] = mod_res['exported'] # NOTE: try to destroy the pool else: mod_res = __salt__['zpool.destroy'](name, force=force) ret['result'] = mod_res['destroyed'] if ret['result']: # update the changes and comment ret['changes'][name] = 'exported' if export else 'destroyed' ret['comment'] = 'storage pool {0} was {1}'.format(name, ret['changes'][name]) elif 'error' in mod_res: ret['comment'] = mod_res['error'] else: # we are looking good ret['result'] = True ret['comment'] = 'storage pool {0} is absent'.format(name) return ret # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/states/zpool.py
present
python
def present(name, properties=None, filesystem_properties=None, layout=None, config=None): ''' ensure storage pool is present on the system name : string name of storage pool properties : dict optional set of properties to set for the storage pool filesystem_properties : dict optional set of filesystem properties to set for the storage pool (creation only) layout: dict disk layout to use if the pool does not exist (creation only) config : dict fine grain control over this state .. note:: The following configuration properties can be toggled in the config parameter. - import (true) - try to import the pool before creating it if absent - import_dirs (None) - specify additional locations to scan for devices on import (comma-seperated) - device_dir (None, SunOS=/dev/dsk, Linux=/dev) - specify device directory to prepend for none absolute device paths - force (false) - try to force the import or creation .. note:: It is no longer needed to give a unique name to each top-level vdev, the old layout format is still supported but no longer recommended. .. code-block:: yaml - mirror: - /tmp/vdisk3 - /tmp/vdisk2 - mirror: - /tmp/vdisk0 - /tmp/vdisk1 The above yaml will always result in the following zpool create: .. code-block:: bash zpool create mypool mirror /tmp/vdisk3 /tmp/vdisk2 mirror /tmp/vdisk0 /tmp/vdisk1 .. warning:: The legacy format is also still supported but not recommended, because ID's inside the layout dict must be unique they need to have a suffix. .. code-block:: yaml mirror-0: /tmp/vdisk3 /tmp/vdisk2 mirror-1: /tmp/vdisk0 /tmp/vdisk1 .. warning:: Pay attention to the order of your dict! .. code-block:: yaml - mirror: - /tmp/vdisk0 - /tmp/vdisk1 - /tmp/vdisk2 The above will result in the following zpool create: .. code-block:: bash zpool create mypool mirror /tmp/vdisk0 /tmp/vdisk1 /tmp/vdisk2 Creating a 3-way mirror! While you probably expect it to be mirror root vdev with 2 devices + a root vdev of 1 device! ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} # config defaults default_config = { 'import': True, 'import_dirs': None, 'device_dir': None, 'force': False } if __grains__['kernel'] == 'SunOS': default_config['device_dir'] = '/dev/dsk' elif __grains__['kernel'] == 'Linux': default_config['device_dir'] = '/dev' # merge state config if config: default_config.update(config) config = default_config # ensure properties are zfs values if properties: properties = __utils__['zfs.from_auto_dict'](properties) elif properties is None: properties = {} if filesystem_properties: filesystem_properties = __utils__['zfs.from_auto_dict'](filesystem_properties) elif filesystem_properties is None: filesystem_properties = {} # parse layout vdevs = _layout_to_vdev(layout, config['device_dir']) if vdevs: vdevs.insert(0, name) # log configuration log.debug('zpool.present::%s::config - %s', name, config) log.debug('zpool.present::%s::vdevs - %s', name, vdevs) log.debug('zpool.present::%s::properties - %s', name, properties) log.debug('zpool.present::%s::filesystem_properties - %s', name, filesystem_properties) # ensure the pool is present ret['result'] = False # don't do anything because this is a test if __opts__['test']: ret['result'] = True if __salt__['zpool.exists'](name): ret['changes'][name] = 'uptodate' else: ret['changes'][name] = 'imported' if config['import'] else 'created' ret['comment'] = 'storage pool {0} was {1}'.format(name, ret['changes'][name]) # update pool elif __salt__['zpool.exists'](name): ret['result'] = True # fetch current pool properties properties_current = __salt__['zpool.get'](name, parsable=True) # build list of properties to update properties_update = [] if properties: for prop in properties: # skip unexisting properties if prop not in properties_current: log.warning('zpool.present::%s::update - unknown property: %s', name, prop) continue # compare current and wanted value if properties_current[prop] != properties[prop]: properties_update.append(prop) # update pool properties for prop in properties_update: res = __salt__['zpool.set'](name, prop, properties[prop]) if res['set']: if name not in ret['changes']: ret['changes'][name] = {} ret['changes'][name][prop] = properties[prop] else: ret['result'] = False if ret['comment'] == '': ret['comment'] = 'The following properties were not updated:' ret['comment'] = '{0} {1}'.format(ret['comment'], prop) if ret['result']: ret['comment'] = 'properties updated' if ret['changes'] else 'no update needed' # import or create the pool (at least try to anyway) else: # import pool if config['import']: mod_res = __salt__['zpool.import']( name, force=config['force'], dir=config['import_dirs'], ) ret['result'] = mod_res['imported'] if ret['result']: ret['changes'][name] = 'imported' ret['comment'] = 'storage pool {0} was imported'.format(name) # create pool if not ret['result'] and vdevs: log.debug('zpool.present::%s::creating', name) # execute zpool.create mod_res = __salt__['zpool.create']( *vdevs, force=config['force'], properties=properties, filesystem_properties=filesystem_properties ) ret['result'] = mod_res['created'] if ret['result']: ret['changes'][name] = 'created' ret['comment'] = 'storage pool {0} was created'.format(name) elif 'error' in mod_res: ret['comment'] = mod_res['error'] else: ret['comment'] = 'could not create storage pool {0}'.format(name) # give up, we cannot import the pool and we do not have a layout to create it if not ret['result'] and not vdevs: ret['comment'] = 'storage pool {0} was not imported, no (valid) layout specified for creation'.format(name) return ret
ensure storage pool is present on the system name : string name of storage pool properties : dict optional set of properties to set for the storage pool filesystem_properties : dict optional set of filesystem properties to set for the storage pool (creation only) layout: dict disk layout to use if the pool does not exist (creation only) config : dict fine grain control over this state .. note:: The following configuration properties can be toggled in the config parameter. - import (true) - try to import the pool before creating it if absent - import_dirs (None) - specify additional locations to scan for devices on import (comma-seperated) - device_dir (None, SunOS=/dev/dsk, Linux=/dev) - specify device directory to prepend for none absolute device paths - force (false) - try to force the import or creation .. note:: It is no longer needed to give a unique name to each top-level vdev, the old layout format is still supported but no longer recommended. .. code-block:: yaml - mirror: - /tmp/vdisk3 - /tmp/vdisk2 - mirror: - /tmp/vdisk0 - /tmp/vdisk1 The above yaml will always result in the following zpool create: .. code-block:: bash zpool create mypool mirror /tmp/vdisk3 /tmp/vdisk2 mirror /tmp/vdisk0 /tmp/vdisk1 .. warning:: The legacy format is also still supported but not recommended, because ID's inside the layout dict must be unique they need to have a suffix. .. code-block:: yaml mirror-0: /tmp/vdisk3 /tmp/vdisk2 mirror-1: /tmp/vdisk0 /tmp/vdisk1 .. warning:: Pay attention to the order of your dict! .. code-block:: yaml - mirror: - /tmp/vdisk0 - /tmp/vdisk1 - /tmp/vdisk2 The above will result in the following zpool create: .. code-block:: bash zpool create mypool mirror /tmp/vdisk0 /tmp/vdisk1 /tmp/vdisk2 Creating a 3-way mirror! While you probably expect it to be mirror root vdev with 2 devices + a root vdev of 1 device!
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zpool.py#L170-L381
[ "def _layout_to_vdev(layout, device_dir=None):\n '''\n Turn the layout data into usable vdevs spedcification\n\n We need to support 2 ways of passing the layout:\n\n .. code::\n layout_new:\n - mirror:\n - disk0\n - disk1\n - mirror:\n - disk2\n - disk3\n\n .. code:\n layout_legacy:\n mirror-0:\n disk0\n disk1\n mirror-1:\n disk2\n disk3\n\n '''\n vdevs = []\n\n # NOTE: check device_dir exists\n if device_dir and not os.path.exists(device_dir):\n device_dir = None\n\n # NOTE: handle list of OrderedDicts (new layout)\n if isinstance(layout, list):\n # NOTE: parse each vdev as a tiny layout and just append\n for vdev in layout:\n if isinstance(vdev, OrderedDict):\n vdevs.extend(_layout_to_vdev(vdev, device_dir))\n else:\n if device_dir and vdev[0] != '/':\n vdev = os.path.join(device_dir, vdev)\n vdevs.append(vdev)\n\n # NOTE: handle nested OrderedDict (legacy layout)\n # this is also used to parse the nested OrderedDicts\n # from the new layout\n elif isinstance(layout, OrderedDict):\n for vdev in layout:\n # NOTE: extract the vdev type and disks in the vdev\n vdev_type = vdev.split('-')[0]\n vdev_disk = layout[vdev]\n\n # NOTE: skip appending the dummy type 'disk'\n if vdev_type != 'disk':\n vdevs.append(vdev_type)\n\n # NOTE: ensure the disks are a list (legacy layout are not)\n if not isinstance(vdev_disk, list):\n vdev_disk = vdev_disk.split(' ')\n\n # NOTE: also append the actualy disks behind the type\n # also prepend device_dir to disks if required\n for disk in vdev_disk:\n if device_dir and disk[0] != '/':\n disk = os.path.join(device_dir, disk)\n vdevs.append(disk)\n\n # NOTE: we got invalid data for layout\n else:\n vdevs = None\n\n return vdevs\n" ]
# -*- coding: utf-8 -*- ''' States for managing zpools :maintainer: Jorge Schrauwen <sjorge@blackdot.be> :maturity: new :depends: salt.utils.zfs, salt.modules.zpool :platform: smartos, illumos, solaris, freebsd, linux .. versionadded:: 2016.3.0 .. versionchanged:: 2018.3.1 Big refactor to remove duplicate code, better type converions and improved consistancy in output. .. code-block:: yaml oldpool: zpool.absent: - export: true newpool: zpool.present: - config: import: false force: true - properties: comment: salty storage pool - layout: - mirror: - /dev/disk0 - /dev/disk1 - mirror: - /dev/disk2 - /dev/disk3 partitionpool: zpool.present: - config: import: false force: true - properties: comment: disk partition salty storage pool ashift: '12' feature@lz4_compress: enabled - filesystem_properties: compression: lz4 atime: on relatime: on - layout: - /dev/disk/by-uuid/3e43ce94-77af-4f52-a91b-6cdbb0b0f41b simplepool: zpool.present: - config: import: false force: true - properties: comment: another salty storage pool - layout: - /dev/disk0 - /dev/disk1 .. warning:: The layout will never be updated, it will only be used at time of creation. It's a whole lot of work to figure out if a devices needs to be detached, removed, etc. This is best done by the sysadmin on a case per case basis. Filesystem properties are also not updated, this should be managed by the zfs state module. ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import os import logging # Import Salt libs from salt.utils.odict import OrderedDict log = logging.getLogger(__name__) # Define the state's virtual name __virtualname__ = 'zpool' def __virtual__(): ''' Provides zpool state ''' if __grains__['zfs_support']: return __virtualname__ else: return False, 'The zpool state cannot be loaded: zfs not supported' def _layout_to_vdev(layout, device_dir=None): ''' Turn the layout data into usable vdevs spedcification We need to support 2 ways of passing the layout: .. code:: layout_new: - mirror: - disk0 - disk1 - mirror: - disk2 - disk3 .. code: layout_legacy: mirror-0: disk0 disk1 mirror-1: disk2 disk3 ''' vdevs = [] # NOTE: check device_dir exists if device_dir and not os.path.exists(device_dir): device_dir = None # NOTE: handle list of OrderedDicts (new layout) if isinstance(layout, list): # NOTE: parse each vdev as a tiny layout and just append for vdev in layout: if isinstance(vdev, OrderedDict): vdevs.extend(_layout_to_vdev(vdev, device_dir)) else: if device_dir and vdev[0] != '/': vdev = os.path.join(device_dir, vdev) vdevs.append(vdev) # NOTE: handle nested OrderedDict (legacy layout) # this is also used to parse the nested OrderedDicts # from the new layout elif isinstance(layout, OrderedDict): for vdev in layout: # NOTE: extract the vdev type and disks in the vdev vdev_type = vdev.split('-')[0] vdev_disk = layout[vdev] # NOTE: skip appending the dummy type 'disk' if vdev_type != 'disk': vdevs.append(vdev_type) # NOTE: ensure the disks are a list (legacy layout are not) if not isinstance(vdev_disk, list): vdev_disk = vdev_disk.split(' ') # NOTE: also append the actualy disks behind the type # also prepend device_dir to disks if required for disk in vdev_disk: if device_dir and disk[0] != '/': disk = os.path.join(device_dir, disk) vdevs.append(disk) # NOTE: we got invalid data for layout else: vdevs = None return vdevs def absent(name, export=False, force=False): ''' ensure storage pool is absent on the system name : string name of storage pool export : boolean export instread of destroy the zpool if present force : boolean force destroy or export ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} # log configuration log.debug('zpool.absent::%s::config::force = %s', name, force) log.debug('zpool.absent::%s::config::export = %s', name, export) # ensure the pool is absent if __salt__['zpool.exists'](name): # looks like we need to do some work mod_res = {} ret['result'] = False # NOTE: handle test if __opts__['test']: ret['result'] = True # NOTE: try to export the pool elif export: mod_res = __salt__['zpool.export'](name, force=force) ret['result'] = mod_res['exported'] # NOTE: try to destroy the pool else: mod_res = __salt__['zpool.destroy'](name, force=force) ret['result'] = mod_res['destroyed'] if ret['result']: # update the changes and comment ret['changes'][name] = 'exported' if export else 'destroyed' ret['comment'] = 'storage pool {0} was {1}'.format(name, ret['changes'][name]) elif 'error' in mod_res: ret['comment'] = mod_res['error'] else: # we are looking good ret['result'] = True ret['comment'] = 'storage pool {0} is absent'.format(name) return ret # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/states/zpool.py
absent
python
def absent(name, export=False, force=False): ''' ensure storage pool is absent on the system name : string name of storage pool export : boolean export instread of destroy the zpool if present force : boolean force destroy or export ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} # log configuration log.debug('zpool.absent::%s::config::force = %s', name, force) log.debug('zpool.absent::%s::config::export = %s', name, export) # ensure the pool is absent if __salt__['zpool.exists'](name): # looks like we need to do some work mod_res = {} ret['result'] = False # NOTE: handle test if __opts__['test']: ret['result'] = True # NOTE: try to export the pool elif export: mod_res = __salt__['zpool.export'](name, force=force) ret['result'] = mod_res['exported'] # NOTE: try to destroy the pool else: mod_res = __salt__['zpool.destroy'](name, force=force) ret['result'] = mod_res['destroyed'] if ret['result']: # update the changes and comment ret['changes'][name] = 'exported' if export else 'destroyed' ret['comment'] = 'storage pool {0} was {1}'.format(name, ret['changes'][name]) elif 'error' in mod_res: ret['comment'] = mod_res['error'] else: # we are looking good ret['result'] = True ret['comment'] = 'storage pool {0} is absent'.format(name) return ret
ensure storage pool is absent on the system name : string name of storage pool export : boolean export instread of destroy the zpool if present force : boolean force destroy or export
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zpool.py#L384-L434
null
# -*- coding: utf-8 -*- ''' States for managing zpools :maintainer: Jorge Schrauwen <sjorge@blackdot.be> :maturity: new :depends: salt.utils.zfs, salt.modules.zpool :platform: smartos, illumos, solaris, freebsd, linux .. versionadded:: 2016.3.0 .. versionchanged:: 2018.3.1 Big refactor to remove duplicate code, better type converions and improved consistancy in output. .. code-block:: yaml oldpool: zpool.absent: - export: true newpool: zpool.present: - config: import: false force: true - properties: comment: salty storage pool - layout: - mirror: - /dev/disk0 - /dev/disk1 - mirror: - /dev/disk2 - /dev/disk3 partitionpool: zpool.present: - config: import: false force: true - properties: comment: disk partition salty storage pool ashift: '12' feature@lz4_compress: enabled - filesystem_properties: compression: lz4 atime: on relatime: on - layout: - /dev/disk/by-uuid/3e43ce94-77af-4f52-a91b-6cdbb0b0f41b simplepool: zpool.present: - config: import: false force: true - properties: comment: another salty storage pool - layout: - /dev/disk0 - /dev/disk1 .. warning:: The layout will never be updated, it will only be used at time of creation. It's a whole lot of work to figure out if a devices needs to be detached, removed, etc. This is best done by the sysadmin on a case per case basis. Filesystem properties are also not updated, this should be managed by the zfs state module. ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import os import logging # Import Salt libs from salt.utils.odict import OrderedDict log = logging.getLogger(__name__) # Define the state's virtual name __virtualname__ = 'zpool' def __virtual__(): ''' Provides zpool state ''' if __grains__['zfs_support']: return __virtualname__ else: return False, 'The zpool state cannot be loaded: zfs not supported' def _layout_to_vdev(layout, device_dir=None): ''' Turn the layout data into usable vdevs spedcification We need to support 2 ways of passing the layout: .. code:: layout_new: - mirror: - disk0 - disk1 - mirror: - disk2 - disk3 .. code: layout_legacy: mirror-0: disk0 disk1 mirror-1: disk2 disk3 ''' vdevs = [] # NOTE: check device_dir exists if device_dir and not os.path.exists(device_dir): device_dir = None # NOTE: handle list of OrderedDicts (new layout) if isinstance(layout, list): # NOTE: parse each vdev as a tiny layout and just append for vdev in layout: if isinstance(vdev, OrderedDict): vdevs.extend(_layout_to_vdev(vdev, device_dir)) else: if device_dir and vdev[0] != '/': vdev = os.path.join(device_dir, vdev) vdevs.append(vdev) # NOTE: handle nested OrderedDict (legacy layout) # this is also used to parse the nested OrderedDicts # from the new layout elif isinstance(layout, OrderedDict): for vdev in layout: # NOTE: extract the vdev type and disks in the vdev vdev_type = vdev.split('-')[0] vdev_disk = layout[vdev] # NOTE: skip appending the dummy type 'disk' if vdev_type != 'disk': vdevs.append(vdev_type) # NOTE: ensure the disks are a list (legacy layout are not) if not isinstance(vdev_disk, list): vdev_disk = vdev_disk.split(' ') # NOTE: also append the actualy disks behind the type # also prepend device_dir to disks if required for disk in vdev_disk: if device_dir and disk[0] != '/': disk = os.path.join(device_dir, disk) vdevs.append(disk) # NOTE: we got invalid data for layout else: vdevs = None return vdevs def present(name, properties=None, filesystem_properties=None, layout=None, config=None): ''' ensure storage pool is present on the system name : string name of storage pool properties : dict optional set of properties to set for the storage pool filesystem_properties : dict optional set of filesystem properties to set for the storage pool (creation only) layout: dict disk layout to use if the pool does not exist (creation only) config : dict fine grain control over this state .. note:: The following configuration properties can be toggled in the config parameter. - import (true) - try to import the pool before creating it if absent - import_dirs (None) - specify additional locations to scan for devices on import (comma-seperated) - device_dir (None, SunOS=/dev/dsk, Linux=/dev) - specify device directory to prepend for none absolute device paths - force (false) - try to force the import or creation .. note:: It is no longer needed to give a unique name to each top-level vdev, the old layout format is still supported but no longer recommended. .. code-block:: yaml - mirror: - /tmp/vdisk3 - /tmp/vdisk2 - mirror: - /tmp/vdisk0 - /tmp/vdisk1 The above yaml will always result in the following zpool create: .. code-block:: bash zpool create mypool mirror /tmp/vdisk3 /tmp/vdisk2 mirror /tmp/vdisk0 /tmp/vdisk1 .. warning:: The legacy format is also still supported but not recommended, because ID's inside the layout dict must be unique they need to have a suffix. .. code-block:: yaml mirror-0: /tmp/vdisk3 /tmp/vdisk2 mirror-1: /tmp/vdisk0 /tmp/vdisk1 .. warning:: Pay attention to the order of your dict! .. code-block:: yaml - mirror: - /tmp/vdisk0 - /tmp/vdisk1 - /tmp/vdisk2 The above will result in the following zpool create: .. code-block:: bash zpool create mypool mirror /tmp/vdisk0 /tmp/vdisk1 /tmp/vdisk2 Creating a 3-way mirror! While you probably expect it to be mirror root vdev with 2 devices + a root vdev of 1 device! ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} # config defaults default_config = { 'import': True, 'import_dirs': None, 'device_dir': None, 'force': False } if __grains__['kernel'] == 'SunOS': default_config['device_dir'] = '/dev/dsk' elif __grains__['kernel'] == 'Linux': default_config['device_dir'] = '/dev' # merge state config if config: default_config.update(config) config = default_config # ensure properties are zfs values if properties: properties = __utils__['zfs.from_auto_dict'](properties) elif properties is None: properties = {} if filesystem_properties: filesystem_properties = __utils__['zfs.from_auto_dict'](filesystem_properties) elif filesystem_properties is None: filesystem_properties = {} # parse layout vdevs = _layout_to_vdev(layout, config['device_dir']) if vdevs: vdevs.insert(0, name) # log configuration log.debug('zpool.present::%s::config - %s', name, config) log.debug('zpool.present::%s::vdevs - %s', name, vdevs) log.debug('zpool.present::%s::properties - %s', name, properties) log.debug('zpool.present::%s::filesystem_properties - %s', name, filesystem_properties) # ensure the pool is present ret['result'] = False # don't do anything because this is a test if __opts__['test']: ret['result'] = True if __salt__['zpool.exists'](name): ret['changes'][name] = 'uptodate' else: ret['changes'][name] = 'imported' if config['import'] else 'created' ret['comment'] = 'storage pool {0} was {1}'.format(name, ret['changes'][name]) # update pool elif __salt__['zpool.exists'](name): ret['result'] = True # fetch current pool properties properties_current = __salt__['zpool.get'](name, parsable=True) # build list of properties to update properties_update = [] if properties: for prop in properties: # skip unexisting properties if prop not in properties_current: log.warning('zpool.present::%s::update - unknown property: %s', name, prop) continue # compare current and wanted value if properties_current[prop] != properties[prop]: properties_update.append(prop) # update pool properties for prop in properties_update: res = __salt__['zpool.set'](name, prop, properties[prop]) if res['set']: if name not in ret['changes']: ret['changes'][name] = {} ret['changes'][name][prop] = properties[prop] else: ret['result'] = False if ret['comment'] == '': ret['comment'] = 'The following properties were not updated:' ret['comment'] = '{0} {1}'.format(ret['comment'], prop) if ret['result']: ret['comment'] = 'properties updated' if ret['changes'] else 'no update needed' # import or create the pool (at least try to anyway) else: # import pool if config['import']: mod_res = __salt__['zpool.import']( name, force=config['force'], dir=config['import_dirs'], ) ret['result'] = mod_res['imported'] if ret['result']: ret['changes'][name] = 'imported' ret['comment'] = 'storage pool {0} was imported'.format(name) # create pool if not ret['result'] and vdevs: log.debug('zpool.present::%s::creating', name) # execute zpool.create mod_res = __salt__['zpool.create']( *vdevs, force=config['force'], properties=properties, filesystem_properties=filesystem_properties ) ret['result'] = mod_res['created'] if ret['result']: ret['changes'][name] = 'created' ret['comment'] = 'storage pool {0} was created'.format(name) elif 'error' in mod_res: ret['comment'] = mod_res['error'] else: ret['comment'] = 'could not create storage pool {0}'.format(name) # give up, we cannot import the pool and we do not have a layout to create it if not ret['result'] and not vdevs: ret['comment'] = 'storage pool {0} was not imported, no (valid) layout specified for creation'.format(name) return ret # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/utils/systemd.py
booted
python
def booted(context=None): ''' Return True if the system was booted with systemd, False otherwise. If the loader context dict ``__context__`` is passed, this function will set the ``salt.utils.systemd.booted`` key to represent if systemd is running and keep the logic below from needing to be run again during the same salt run. ''' contextkey = 'salt.utils.systemd.booted' if isinstance(context, dict): # Can't put this if block on the same line as the above if block, # because it willl break the elif below. if contextkey in context: return context[contextkey] elif context is not None: raise SaltInvocationError('context must be a dictionary if passed') try: # This check does the same as sd_booted() from libsystemd-daemon: # http://www.freedesktop.org/software/systemd/man/sd_booted.html ret = bool(os.stat('/run/systemd/system')) except OSError: ret = False try: context[contextkey] = ret except TypeError: pass return ret
Return True if the system was booted with systemd, False otherwise. If the loader context dict ``__context__`` is passed, this function will set the ``salt.utils.systemd.booted`` key to represent if systemd is running and keep the logic below from needing to be run again during the same salt run.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/systemd.py#L19-L47
null
# -*- coding: utf-8 -*- ''' Contains systemd related help files ''' # import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import re import subprocess # Import Salt libs from salt.exceptions import SaltInvocationError import salt.utils.stringutils log = logging.getLogger(__name__) def version(context=None): ''' Attempts to run systemctl --version. Returns None if unable to determine version. ''' contextkey = 'salt.utils.systemd.version' if isinstance(context, dict): # Can't put this if block on the same line as the above if block, # because it will break the elif below. if contextkey in context: return context[contextkey] elif context is not None: raise SaltInvocationError('context must be a dictionary if passed') stdout = subprocess.Popen( ['systemctl', '--version'], close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] outstr = salt.utils.stringutils.to_str(stdout) try: ret = int(re.search(r'\w+ ([0-9]+)', outstr.splitlines()[0]).group(1)) except (AttributeError, IndexError, ValueError): log.error( 'Unable to determine systemd version from systemctl ' '--version, output follows:\n%s', outstr ) return None else: try: context[contextkey] = ret except TypeError: pass return ret def has_scope(context=None): ''' Scopes were introduced in systemd 205, this function returns a boolean which is true when the minion is systemd-booted and running systemd>=205. ''' if not booted(context): return False _sd_version = version(context) if _sd_version is None: return False return _sd_version >= 205
saltstack/salt
salt/utils/systemd.py
version
python
def version(context=None): ''' Attempts to run systemctl --version. Returns None if unable to determine version. ''' contextkey = 'salt.utils.systemd.version' if isinstance(context, dict): # Can't put this if block on the same line as the above if block, # because it will break the elif below. if contextkey in context: return context[contextkey] elif context is not None: raise SaltInvocationError('context must be a dictionary if passed') stdout = subprocess.Popen( ['systemctl', '--version'], close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] outstr = salt.utils.stringutils.to_str(stdout) try: ret = int(re.search(r'\w+ ([0-9]+)', outstr.splitlines()[0]).group(1)) except (AttributeError, IndexError, ValueError): log.error( 'Unable to determine systemd version from systemctl ' '--version, output follows:\n%s', outstr ) return None else: try: context[contextkey] = ret except TypeError: pass return ret
Attempts to run systemctl --version. Returns None if unable to determine version.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/systemd.py#L50-L81
[ "def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n" ]
# -*- coding: utf-8 -*- ''' Contains systemd related help files ''' # import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import re import subprocess # Import Salt libs from salt.exceptions import SaltInvocationError import salt.utils.stringutils log = logging.getLogger(__name__) def booted(context=None): ''' Return True if the system was booted with systemd, False otherwise. If the loader context dict ``__context__`` is passed, this function will set the ``salt.utils.systemd.booted`` key to represent if systemd is running and keep the logic below from needing to be run again during the same salt run. ''' contextkey = 'salt.utils.systemd.booted' if isinstance(context, dict): # Can't put this if block on the same line as the above if block, # because it willl break the elif below. if contextkey in context: return context[contextkey] elif context is not None: raise SaltInvocationError('context must be a dictionary if passed') try: # This check does the same as sd_booted() from libsystemd-daemon: # http://www.freedesktop.org/software/systemd/man/sd_booted.html ret = bool(os.stat('/run/systemd/system')) except OSError: ret = False try: context[contextkey] = ret except TypeError: pass return ret def has_scope(context=None): ''' Scopes were introduced in systemd 205, this function returns a boolean which is true when the minion is systemd-booted and running systemd>=205. ''' if not booted(context): return False _sd_version = version(context) if _sd_version is None: return False return _sd_version >= 205
saltstack/salt
salt/utils/systemd.py
has_scope
python
def has_scope(context=None): ''' Scopes were introduced in systemd 205, this function returns a boolean which is true when the minion is systemd-booted and running systemd>=205. ''' if not booted(context): return False _sd_version = version(context) if _sd_version is None: return False return _sd_version >= 205
Scopes were introduced in systemd 205, this function returns a boolean which is true when the minion is systemd-booted and running systemd>=205.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/systemd.py#L84-L94
[ "def version(context=None):\n '''\n Attempts to run systemctl --version. Returns None if unable to determine\n version.\n '''\n contextkey = 'salt.utils.systemd.version'\n if isinstance(context, dict):\n # Can't put this if block on the same line as the above if block,\n # because it will break the elif below.\n if contextkey in context:\n return context[contextkey]\n elif context is not None:\n raise SaltInvocationError('context must be a dictionary if passed')\n stdout = subprocess.Popen(\n ['systemctl', '--version'],\n close_fds=True,\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0]\n outstr = salt.utils.stringutils.to_str(stdout)\n try:\n ret = int(re.search(r'\\w+ ([0-9]+)', outstr.splitlines()[0]).group(1))\n except (AttributeError, IndexError, ValueError):\n log.error(\n 'Unable to determine systemd version from systemctl '\n '--version, output follows:\\n%s', outstr\n )\n return None\n else:\n try:\n context[contextkey] = ret\n except TypeError:\n pass\n return ret\n", "def booted(context=None):\n '''\n Return True if the system was booted with systemd, False otherwise. If the\n loader context dict ``__context__`` is passed, this function will set the\n ``salt.utils.systemd.booted`` key to represent if systemd is running and\n keep the logic below from needing to be run again during the same salt run.\n '''\n contextkey = 'salt.utils.systemd.booted'\n if isinstance(context, dict):\n # Can't put this if block on the same line as the above if block,\n # because it willl break the elif below.\n if contextkey in context:\n return context[contextkey]\n elif context is not None:\n raise SaltInvocationError('context must be a dictionary if passed')\n\n try:\n # This check does the same as sd_booted() from libsystemd-daemon:\n # http://www.freedesktop.org/software/systemd/man/sd_booted.html\n ret = bool(os.stat('/run/systemd/system'))\n except OSError:\n ret = False\n\n try:\n context[contextkey] = ret\n except TypeError:\n pass\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Contains systemd related help files ''' # import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import re import subprocess # Import Salt libs from salt.exceptions import SaltInvocationError import salt.utils.stringutils log = logging.getLogger(__name__) def booted(context=None): ''' Return True if the system was booted with systemd, False otherwise. If the loader context dict ``__context__`` is passed, this function will set the ``salt.utils.systemd.booted`` key to represent if systemd is running and keep the logic below from needing to be run again during the same salt run. ''' contextkey = 'salt.utils.systemd.booted' if isinstance(context, dict): # Can't put this if block on the same line as the above if block, # because it willl break the elif below. if contextkey in context: return context[contextkey] elif context is not None: raise SaltInvocationError('context must be a dictionary if passed') try: # This check does the same as sd_booted() from libsystemd-daemon: # http://www.freedesktop.org/software/systemd/man/sd_booted.html ret = bool(os.stat('/run/systemd/system')) except OSError: ret = False try: context[contextkey] = ret except TypeError: pass return ret def version(context=None): ''' Attempts to run systemctl --version. Returns None if unable to determine version. ''' contextkey = 'salt.utils.systemd.version' if isinstance(context, dict): # Can't put this if block on the same line as the above if block, # because it will break the elif below. if contextkey in context: return context[contextkey] elif context is not None: raise SaltInvocationError('context must be a dictionary if passed') stdout = subprocess.Popen( ['systemctl', '--version'], close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] outstr = salt.utils.stringutils.to_str(stdout) try: ret = int(re.search(r'\w+ ([0-9]+)', outstr.splitlines()[0]).group(1)) except (AttributeError, IndexError, ValueError): log.error( 'Unable to determine systemd version from systemctl ' '--version, output follows:\n%s', outstr ) return None else: try: context[contextkey] = ret except TypeError: pass return ret
saltstack/salt
salt/returners/postgres_local_cache.py
_get_conn
python
def _get_conn(): ''' Return a postgres connection. ''' try: conn = psycopg2.connect( host=__opts__['master_job_cache.postgres.host'], user=__opts__['master_job_cache.postgres.user'], password=__opts__['master_job_cache.postgres.passwd'], database=__opts__['master_job_cache.postgres.db'], port=__opts__['master_job_cache.postgres.port']) except psycopg2.OperationalError: log.error('Could not connect to SQL server: %s', sys.exc_info()[0]) return None return conn
Return a postgres connection.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/postgres_local_cache.py#L139-L153
null
# -*- coding: utf-8 -*- ''' Use a postgresql server for the master job cache. This helps the job cache to cope with scale. .. note:: There are three PostgreSQL returners. Any can function as an external :ref:`master job cache <external-job-cache>`. but each has different features. SaltStack recommends :mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with a version of PostgreSQL that has the appropriate native binary JSON types. Otherwise, review :mod:`returners.postgres <salt.returners.postgres>` and :mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>` to see which module best suits your particular needs. :maintainer: gjredelinghuys@gmail.com :maturity: Stable :depends: psycopg2 :platform: all To enable this returner the minion will need the psycopg2 installed and the following values configured in the master config: .. code-block:: yaml master_job_cache: postgres_local_cache master_job_cache.postgres.host: 'salt' master_job_cache.postgres.user: 'salt' master_job_cache.postgres.passwd: 'salt' master_job_cache.postgres.db: 'salt' master_job_cache.postgres.port: 5432 Running the following command as the postgres user should create the database correctly: .. code-block:: sql psql << EOF CREATE ROLE salt WITH PASSWORD 'salt'; CREATE DATABASE salt WITH OWNER salt; EOF In case the postgres database is a remote host, you'll need this command also: .. code-block:: sql ALTER ROLE salt WITH LOGIN; and then: .. code-block:: sql psql -h localhost -U salt << EOF -- -- Table structure for table 'jids' -- DROP TABLE IF EXISTS jids; CREATE TABLE jids ( jid varchar(20) PRIMARY KEY, started TIMESTAMP WITH TIME ZONE DEFAULT now(), tgt_type text NOT NULL, cmd text NOT NULL, tgt text NOT NULL, kwargs text NOT NULL, ret text NOT NULL, username text NOT NULL, arg text NOT NULL, fun text NOT NULL ); -- -- Table structure for table 'salt_returns' -- -- note that 'success' must not have NOT NULL constraint, since -- some functions don't provide it. DROP TABLE IF EXISTS salt_returns; CREATE TABLE salt_returns ( added TIMESTAMP WITH TIME ZONE DEFAULT now(), fun text NOT NULL, jid varchar(20) NOT NULL, return text NOT NULL, id text NOT NULL, success boolean ); CREATE INDEX ON salt_returns (added); CREATE INDEX ON salt_returns (id); CREATE INDEX ON salt_returns (jid); CREATE INDEX ON salt_returns (fun); DROP TABLE IF EXISTS salt_events; CREATE TABLE salt_events ( id SERIAL, tag text NOT NULL, data text NOT NULL, alter_time TIMESTAMP WITH TIME ZONE DEFAULT now(), master_id text NOT NULL ); CREATE INDEX ON salt_events (tag); CREATE INDEX ON salt_events (data); CREATE INDEX ON salt_events (id); CREATE INDEX ON salt_events (master_id); EOF Required python modules: psycopg2 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import re import sys # Import salt libs import salt.utils.jid import salt.utils.json from salt.ext import six # Import third party libs try: import psycopg2 HAS_POSTGRES = True except ImportError: HAS_POSTGRES = False log = logging.getLogger(__name__) __virtualname__ = 'postgres_local_cache' def __virtual__(): if not HAS_POSTGRES: return (False, 'Could not import psycopg2; postges_local_cache disabled') return __virtualname__ def _close_conn(conn): ''' Close the postgres connection. ''' conn.commit() conn.close() def _format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': salt.utils.json.loads(job.get('arg', '[]')), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} # TODO: Add Metadata support when it is merged from develop return ret def _format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret def _gen_jid(cur): ''' Generate an unique job id ''' jid = salt.utils.jid.gen_jid(__opts__) sql = '''SELECT jid FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() if not data: return jid return None def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid). So do what you have to do to make sure that stays the case ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() if passed_jid is None: jid = _gen_jid(cur) else: jid = passed_jid while not jid: log.info("jid clash, generating a new one") jid = _gen_jid(cur) cur.close() conn.close() return jid def returner(load): ''' Return data to a postgres server ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, return, id, success) VALUES (%s, %s, %s, %s, %s)''' try: ret = six.text_type(load['return']) except UnicodeDecodeError: ret = str(load['return']) job_ret = {'return': ret} if 'retcode' in load: job_ret['retcode'] = load['retcode'] if 'success' in load: job_ret['success'] = load['success'] cur.execute( sql, ( load['fun'], load['jid'], salt.utils.json.dumps(job_ret), load['id'], load.get('success'), ) ) _close_conn(conn) def event_return(events): ''' Return event to a postgres server Require that configuration be enabled via 'event_return' option in master config. ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() for event in events: tag = event.get('tag', '') data = event.get('data', '') sql = '''INSERT INTO salt_events (tag, data, master_id) VALUES (%s, %s, %s)''' cur.execute(sql, (tag, salt.utils.json.dumps(data), __opts__['id'])) _close_conn(conn) def save_load(jid, clear_load, minions=None): ''' Save the load to the specified jid id ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO jids ''' \ '''(jid, started, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun) ''' \ '''VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)''' cur.execute( sql, ( jid, salt.utils.jid.jid_to_time(jid), six.text_type(clear_load.get("tgt_type")), six.text_type(clear_load.get("cmd")), six.text_type(clear_load.get("tgt")), six.text_type(clear_load.get("kwargs")), six.text_type(clear_load.get("ret")), six.text_type(clear_load.get("user")), six.text_type(salt.utils.json.dumps(clear_load.get("arg"))), six.text_type(clear_load.get("fun")), ) ) # TODO: Add Metadata support when it is merged from develop _close_conn(conn) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def _escape_jid(jid): ''' Do proper formatting of the jid ''' jid = six.text_type(jid) jid = re.sub(r"'*", "", jid) return jid def _build_dict(data): ''' Rebuild dict ''' result = {} # TODO: Add Metadata support when it is merged from develop result["jid"] = data[0] result["tgt_type"] = data[1] result["cmd"] = data[2] result["tgt"] = data[3] result["kwargs"] = data[4] result["ret"] = data[5] result["user"] = data[6] result["arg"] = data[7] result["fun"] = data[8] return result def get_load(jid): ''' Return the load data that marks a specified jid ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT jid, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchone() if data: return _build_dict(data) _close_conn(conn) return {} def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT id, return FROM salt_returns WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() ret = {} if data: for minion, full_ret in data: ret_data = salt.utils.json.loads(full_ret) if not isinstance(ret_data, dict) or 'return' not in ret_data: # Convert the old format in which the return contains the only return data to the # new that is dict containing 'return' and optionally 'retcode' and 'success'. ret_data = {'return': ret_data} ret[minion] = ret_data _close_conn(conn) return ret def get_jids(): ''' Return a list of all job ids For master job cache this also formats the output and returns a string ''' conn = _get_conn() cur = conn.cursor() sql = '''SELECT ''' \ '''jid, tgt_type, cmd, tgt, kwargs, ret, username, arg, fun ''' \ '''FROM jids''' if __opts__['keep_jobs'] != 0: sql = sql + " WHERE started > NOW() - INTERVAL '" \ + six.text_type(__opts__['keep_jobs']) + "' HOUR" cur.execute(sql) ret = {} data = cur.fetchone() while data: data_dict = _build_dict(data) ret[data_dict["jid"]] = \ _format_jid_instance(data_dict["jid"], data_dict) data = cur.fetchone() cur.close() conn.close() return ret def clean_old_jobs(): ''' Clean out the old jobs from the job cache ''' return
saltstack/salt
salt/returners/postgres_local_cache.py
_format_job_instance
python
def _format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': salt.utils.json.loads(job.get('arg', '[]')), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} # TODO: Add Metadata support when it is merged from develop return ret
Format the job instance correctly
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/postgres_local_cache.py#L164-L175
null
# -*- coding: utf-8 -*- ''' Use a postgresql server for the master job cache. This helps the job cache to cope with scale. .. note:: There are three PostgreSQL returners. Any can function as an external :ref:`master job cache <external-job-cache>`. but each has different features. SaltStack recommends :mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with a version of PostgreSQL that has the appropriate native binary JSON types. Otherwise, review :mod:`returners.postgres <salt.returners.postgres>` and :mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>` to see which module best suits your particular needs. :maintainer: gjredelinghuys@gmail.com :maturity: Stable :depends: psycopg2 :platform: all To enable this returner the minion will need the psycopg2 installed and the following values configured in the master config: .. code-block:: yaml master_job_cache: postgres_local_cache master_job_cache.postgres.host: 'salt' master_job_cache.postgres.user: 'salt' master_job_cache.postgres.passwd: 'salt' master_job_cache.postgres.db: 'salt' master_job_cache.postgres.port: 5432 Running the following command as the postgres user should create the database correctly: .. code-block:: sql psql << EOF CREATE ROLE salt WITH PASSWORD 'salt'; CREATE DATABASE salt WITH OWNER salt; EOF In case the postgres database is a remote host, you'll need this command also: .. code-block:: sql ALTER ROLE salt WITH LOGIN; and then: .. code-block:: sql psql -h localhost -U salt << EOF -- -- Table structure for table 'jids' -- DROP TABLE IF EXISTS jids; CREATE TABLE jids ( jid varchar(20) PRIMARY KEY, started TIMESTAMP WITH TIME ZONE DEFAULT now(), tgt_type text NOT NULL, cmd text NOT NULL, tgt text NOT NULL, kwargs text NOT NULL, ret text NOT NULL, username text NOT NULL, arg text NOT NULL, fun text NOT NULL ); -- -- Table structure for table 'salt_returns' -- -- note that 'success' must not have NOT NULL constraint, since -- some functions don't provide it. DROP TABLE IF EXISTS salt_returns; CREATE TABLE salt_returns ( added TIMESTAMP WITH TIME ZONE DEFAULT now(), fun text NOT NULL, jid varchar(20) NOT NULL, return text NOT NULL, id text NOT NULL, success boolean ); CREATE INDEX ON salt_returns (added); CREATE INDEX ON salt_returns (id); CREATE INDEX ON salt_returns (jid); CREATE INDEX ON salt_returns (fun); DROP TABLE IF EXISTS salt_events; CREATE TABLE salt_events ( id SERIAL, tag text NOT NULL, data text NOT NULL, alter_time TIMESTAMP WITH TIME ZONE DEFAULT now(), master_id text NOT NULL ); CREATE INDEX ON salt_events (tag); CREATE INDEX ON salt_events (data); CREATE INDEX ON salt_events (id); CREATE INDEX ON salt_events (master_id); EOF Required python modules: psycopg2 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import re import sys # Import salt libs import salt.utils.jid import salt.utils.json from salt.ext import six # Import third party libs try: import psycopg2 HAS_POSTGRES = True except ImportError: HAS_POSTGRES = False log = logging.getLogger(__name__) __virtualname__ = 'postgres_local_cache' def __virtual__(): if not HAS_POSTGRES: return (False, 'Could not import psycopg2; postges_local_cache disabled') return __virtualname__ def _get_conn(): ''' Return a postgres connection. ''' try: conn = psycopg2.connect( host=__opts__['master_job_cache.postgres.host'], user=__opts__['master_job_cache.postgres.user'], password=__opts__['master_job_cache.postgres.passwd'], database=__opts__['master_job_cache.postgres.db'], port=__opts__['master_job_cache.postgres.port']) except psycopg2.OperationalError: log.error('Could not connect to SQL server: %s', sys.exc_info()[0]) return None return conn def _close_conn(conn): ''' Close the postgres connection. ''' conn.commit() conn.close() def _format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret def _gen_jid(cur): ''' Generate an unique job id ''' jid = salt.utils.jid.gen_jid(__opts__) sql = '''SELECT jid FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() if not data: return jid return None def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid). So do what you have to do to make sure that stays the case ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() if passed_jid is None: jid = _gen_jid(cur) else: jid = passed_jid while not jid: log.info("jid clash, generating a new one") jid = _gen_jid(cur) cur.close() conn.close() return jid def returner(load): ''' Return data to a postgres server ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, return, id, success) VALUES (%s, %s, %s, %s, %s)''' try: ret = six.text_type(load['return']) except UnicodeDecodeError: ret = str(load['return']) job_ret = {'return': ret} if 'retcode' in load: job_ret['retcode'] = load['retcode'] if 'success' in load: job_ret['success'] = load['success'] cur.execute( sql, ( load['fun'], load['jid'], salt.utils.json.dumps(job_ret), load['id'], load.get('success'), ) ) _close_conn(conn) def event_return(events): ''' Return event to a postgres server Require that configuration be enabled via 'event_return' option in master config. ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() for event in events: tag = event.get('tag', '') data = event.get('data', '') sql = '''INSERT INTO salt_events (tag, data, master_id) VALUES (%s, %s, %s)''' cur.execute(sql, (tag, salt.utils.json.dumps(data), __opts__['id'])) _close_conn(conn) def save_load(jid, clear_load, minions=None): ''' Save the load to the specified jid id ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO jids ''' \ '''(jid, started, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun) ''' \ '''VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)''' cur.execute( sql, ( jid, salt.utils.jid.jid_to_time(jid), six.text_type(clear_load.get("tgt_type")), six.text_type(clear_load.get("cmd")), six.text_type(clear_load.get("tgt")), six.text_type(clear_load.get("kwargs")), six.text_type(clear_load.get("ret")), six.text_type(clear_load.get("user")), six.text_type(salt.utils.json.dumps(clear_load.get("arg"))), six.text_type(clear_load.get("fun")), ) ) # TODO: Add Metadata support when it is merged from develop _close_conn(conn) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def _escape_jid(jid): ''' Do proper formatting of the jid ''' jid = six.text_type(jid) jid = re.sub(r"'*", "", jid) return jid def _build_dict(data): ''' Rebuild dict ''' result = {} # TODO: Add Metadata support when it is merged from develop result["jid"] = data[0] result["tgt_type"] = data[1] result["cmd"] = data[2] result["tgt"] = data[3] result["kwargs"] = data[4] result["ret"] = data[5] result["user"] = data[6] result["arg"] = data[7] result["fun"] = data[8] return result def get_load(jid): ''' Return the load data that marks a specified jid ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT jid, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchone() if data: return _build_dict(data) _close_conn(conn) return {} def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT id, return FROM salt_returns WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() ret = {} if data: for minion, full_ret in data: ret_data = salt.utils.json.loads(full_ret) if not isinstance(ret_data, dict) or 'return' not in ret_data: # Convert the old format in which the return contains the only return data to the # new that is dict containing 'return' and optionally 'retcode' and 'success'. ret_data = {'return': ret_data} ret[minion] = ret_data _close_conn(conn) return ret def get_jids(): ''' Return a list of all job ids For master job cache this also formats the output and returns a string ''' conn = _get_conn() cur = conn.cursor() sql = '''SELECT ''' \ '''jid, tgt_type, cmd, tgt, kwargs, ret, username, arg, fun ''' \ '''FROM jids''' if __opts__['keep_jobs'] != 0: sql = sql + " WHERE started > NOW() - INTERVAL '" \ + six.text_type(__opts__['keep_jobs']) + "' HOUR" cur.execute(sql) ret = {} data = cur.fetchone() while data: data_dict = _build_dict(data) ret[data_dict["jid"]] = \ _format_jid_instance(data_dict["jid"], data_dict) data = cur.fetchone() cur.close() conn.close() return ret def clean_old_jobs(): ''' Clean out the old jobs from the job cache ''' return
saltstack/salt
salt/returners/postgres_local_cache.py
_gen_jid
python
def _gen_jid(cur): ''' Generate an unique job id ''' jid = salt.utils.jid.gen_jid(__opts__) sql = '''SELECT jid FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() if not data: return jid return None
Generate an unique job id
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/postgres_local_cache.py#L187-L197
[ "def gen_jid(opts=None):\n '''\n Generate a jid\n '''\n if opts is None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'The `opts` argument was not passed into salt.utils.jid.gen_jid(). '\n 'This will be required starting in {version}.'\n )\n opts = {}\n global LAST_JID_DATETIME # pylint: disable=global-statement\n\n if opts.get('utc_jid', False):\n jid_dt = datetime.datetime.utcnow()\n else:\n jid_dt = datetime.datetime.now()\n if not opts.get('unique_jid', False):\n return '{0:%Y%m%d%H%M%S%f}'.format(jid_dt)\n if LAST_JID_DATETIME and LAST_JID_DATETIME >= jid_dt:\n jid_dt = LAST_JID_DATETIME + datetime.timedelta(microseconds=1)\n LAST_JID_DATETIME = jid_dt\n return '{0:%Y%m%d%H%M%S%f}_{1}'.format(jid_dt, os.getpid())\n" ]
# -*- coding: utf-8 -*- ''' Use a postgresql server for the master job cache. This helps the job cache to cope with scale. .. note:: There are three PostgreSQL returners. Any can function as an external :ref:`master job cache <external-job-cache>`. but each has different features. SaltStack recommends :mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with a version of PostgreSQL that has the appropriate native binary JSON types. Otherwise, review :mod:`returners.postgres <salt.returners.postgres>` and :mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>` to see which module best suits your particular needs. :maintainer: gjredelinghuys@gmail.com :maturity: Stable :depends: psycopg2 :platform: all To enable this returner the minion will need the psycopg2 installed and the following values configured in the master config: .. code-block:: yaml master_job_cache: postgres_local_cache master_job_cache.postgres.host: 'salt' master_job_cache.postgres.user: 'salt' master_job_cache.postgres.passwd: 'salt' master_job_cache.postgres.db: 'salt' master_job_cache.postgres.port: 5432 Running the following command as the postgres user should create the database correctly: .. code-block:: sql psql << EOF CREATE ROLE salt WITH PASSWORD 'salt'; CREATE DATABASE salt WITH OWNER salt; EOF In case the postgres database is a remote host, you'll need this command also: .. code-block:: sql ALTER ROLE salt WITH LOGIN; and then: .. code-block:: sql psql -h localhost -U salt << EOF -- -- Table structure for table 'jids' -- DROP TABLE IF EXISTS jids; CREATE TABLE jids ( jid varchar(20) PRIMARY KEY, started TIMESTAMP WITH TIME ZONE DEFAULT now(), tgt_type text NOT NULL, cmd text NOT NULL, tgt text NOT NULL, kwargs text NOT NULL, ret text NOT NULL, username text NOT NULL, arg text NOT NULL, fun text NOT NULL ); -- -- Table structure for table 'salt_returns' -- -- note that 'success' must not have NOT NULL constraint, since -- some functions don't provide it. DROP TABLE IF EXISTS salt_returns; CREATE TABLE salt_returns ( added TIMESTAMP WITH TIME ZONE DEFAULT now(), fun text NOT NULL, jid varchar(20) NOT NULL, return text NOT NULL, id text NOT NULL, success boolean ); CREATE INDEX ON salt_returns (added); CREATE INDEX ON salt_returns (id); CREATE INDEX ON salt_returns (jid); CREATE INDEX ON salt_returns (fun); DROP TABLE IF EXISTS salt_events; CREATE TABLE salt_events ( id SERIAL, tag text NOT NULL, data text NOT NULL, alter_time TIMESTAMP WITH TIME ZONE DEFAULT now(), master_id text NOT NULL ); CREATE INDEX ON salt_events (tag); CREATE INDEX ON salt_events (data); CREATE INDEX ON salt_events (id); CREATE INDEX ON salt_events (master_id); EOF Required python modules: psycopg2 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import re import sys # Import salt libs import salt.utils.jid import salt.utils.json from salt.ext import six # Import third party libs try: import psycopg2 HAS_POSTGRES = True except ImportError: HAS_POSTGRES = False log = logging.getLogger(__name__) __virtualname__ = 'postgres_local_cache' def __virtual__(): if not HAS_POSTGRES: return (False, 'Could not import psycopg2; postges_local_cache disabled') return __virtualname__ def _get_conn(): ''' Return a postgres connection. ''' try: conn = psycopg2.connect( host=__opts__['master_job_cache.postgres.host'], user=__opts__['master_job_cache.postgres.user'], password=__opts__['master_job_cache.postgres.passwd'], database=__opts__['master_job_cache.postgres.db'], port=__opts__['master_job_cache.postgres.port']) except psycopg2.OperationalError: log.error('Could not connect to SQL server: %s', sys.exc_info()[0]) return None return conn def _close_conn(conn): ''' Close the postgres connection. ''' conn.commit() conn.close() def _format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': salt.utils.json.loads(job.get('arg', '[]')), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} # TODO: Add Metadata support when it is merged from develop return ret def _format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid). So do what you have to do to make sure that stays the case ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() if passed_jid is None: jid = _gen_jid(cur) else: jid = passed_jid while not jid: log.info("jid clash, generating a new one") jid = _gen_jid(cur) cur.close() conn.close() return jid def returner(load): ''' Return data to a postgres server ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, return, id, success) VALUES (%s, %s, %s, %s, %s)''' try: ret = six.text_type(load['return']) except UnicodeDecodeError: ret = str(load['return']) job_ret = {'return': ret} if 'retcode' in load: job_ret['retcode'] = load['retcode'] if 'success' in load: job_ret['success'] = load['success'] cur.execute( sql, ( load['fun'], load['jid'], salt.utils.json.dumps(job_ret), load['id'], load.get('success'), ) ) _close_conn(conn) def event_return(events): ''' Return event to a postgres server Require that configuration be enabled via 'event_return' option in master config. ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() for event in events: tag = event.get('tag', '') data = event.get('data', '') sql = '''INSERT INTO salt_events (tag, data, master_id) VALUES (%s, %s, %s)''' cur.execute(sql, (tag, salt.utils.json.dumps(data), __opts__['id'])) _close_conn(conn) def save_load(jid, clear_load, minions=None): ''' Save the load to the specified jid id ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO jids ''' \ '''(jid, started, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun) ''' \ '''VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)''' cur.execute( sql, ( jid, salt.utils.jid.jid_to_time(jid), six.text_type(clear_load.get("tgt_type")), six.text_type(clear_load.get("cmd")), six.text_type(clear_load.get("tgt")), six.text_type(clear_load.get("kwargs")), six.text_type(clear_load.get("ret")), six.text_type(clear_load.get("user")), six.text_type(salt.utils.json.dumps(clear_load.get("arg"))), six.text_type(clear_load.get("fun")), ) ) # TODO: Add Metadata support when it is merged from develop _close_conn(conn) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def _escape_jid(jid): ''' Do proper formatting of the jid ''' jid = six.text_type(jid) jid = re.sub(r"'*", "", jid) return jid def _build_dict(data): ''' Rebuild dict ''' result = {} # TODO: Add Metadata support when it is merged from develop result["jid"] = data[0] result["tgt_type"] = data[1] result["cmd"] = data[2] result["tgt"] = data[3] result["kwargs"] = data[4] result["ret"] = data[5] result["user"] = data[6] result["arg"] = data[7] result["fun"] = data[8] return result def get_load(jid): ''' Return the load data that marks a specified jid ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT jid, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchone() if data: return _build_dict(data) _close_conn(conn) return {} def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT id, return FROM salt_returns WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() ret = {} if data: for minion, full_ret in data: ret_data = salt.utils.json.loads(full_ret) if not isinstance(ret_data, dict) or 'return' not in ret_data: # Convert the old format in which the return contains the only return data to the # new that is dict containing 'return' and optionally 'retcode' and 'success'. ret_data = {'return': ret_data} ret[minion] = ret_data _close_conn(conn) return ret def get_jids(): ''' Return a list of all job ids For master job cache this also formats the output and returns a string ''' conn = _get_conn() cur = conn.cursor() sql = '''SELECT ''' \ '''jid, tgt_type, cmd, tgt, kwargs, ret, username, arg, fun ''' \ '''FROM jids''' if __opts__['keep_jobs'] != 0: sql = sql + " WHERE started > NOW() - INTERVAL '" \ + six.text_type(__opts__['keep_jobs']) + "' HOUR" cur.execute(sql) ret = {} data = cur.fetchone() while data: data_dict = _build_dict(data) ret[data_dict["jid"]] = \ _format_jid_instance(data_dict["jid"], data_dict) data = cur.fetchone() cur.close() conn.close() return ret def clean_old_jobs(): ''' Clean out the old jobs from the job cache ''' return
saltstack/salt
salt/returners/postgres_local_cache.py
prep_jid
python
def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid). So do what you have to do to make sure that stays the case ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() if passed_jid is None: jid = _gen_jid(cur) else: jid = passed_jid while not jid: log.info("jid clash, generating a new one") jid = _gen_jid(cur) cur.close() conn.close() return jid
Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid). So do what you have to do to make sure that stays the case
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/postgres_local_cache.py#L200-L221
[ "def _get_conn():\n '''\n Return a postgres connection.\n '''\n try:\n conn = psycopg2.connect(\n host=__opts__['master_job_cache.postgres.host'],\n user=__opts__['master_job_cache.postgres.user'],\n password=__opts__['master_job_cache.postgres.passwd'],\n database=__opts__['master_job_cache.postgres.db'],\n port=__opts__['master_job_cache.postgres.port'])\n except psycopg2.OperationalError:\n log.error('Could not connect to SQL server: %s', sys.exc_info()[0])\n return None\n return conn\n", "def _gen_jid(cur):\n '''\n Generate an unique job id\n '''\n jid = salt.utils.jid.gen_jid(__opts__)\n sql = '''SELECT jid FROM jids WHERE jid = %s'''\n cur.execute(sql, (jid,))\n data = cur.fetchall()\n if not data:\n return jid\n return None\n" ]
# -*- coding: utf-8 -*- ''' Use a postgresql server for the master job cache. This helps the job cache to cope with scale. .. note:: There are three PostgreSQL returners. Any can function as an external :ref:`master job cache <external-job-cache>`. but each has different features. SaltStack recommends :mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with a version of PostgreSQL that has the appropriate native binary JSON types. Otherwise, review :mod:`returners.postgres <salt.returners.postgres>` and :mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>` to see which module best suits your particular needs. :maintainer: gjredelinghuys@gmail.com :maturity: Stable :depends: psycopg2 :platform: all To enable this returner the minion will need the psycopg2 installed and the following values configured in the master config: .. code-block:: yaml master_job_cache: postgres_local_cache master_job_cache.postgres.host: 'salt' master_job_cache.postgres.user: 'salt' master_job_cache.postgres.passwd: 'salt' master_job_cache.postgres.db: 'salt' master_job_cache.postgres.port: 5432 Running the following command as the postgres user should create the database correctly: .. code-block:: sql psql << EOF CREATE ROLE salt WITH PASSWORD 'salt'; CREATE DATABASE salt WITH OWNER salt; EOF In case the postgres database is a remote host, you'll need this command also: .. code-block:: sql ALTER ROLE salt WITH LOGIN; and then: .. code-block:: sql psql -h localhost -U salt << EOF -- -- Table structure for table 'jids' -- DROP TABLE IF EXISTS jids; CREATE TABLE jids ( jid varchar(20) PRIMARY KEY, started TIMESTAMP WITH TIME ZONE DEFAULT now(), tgt_type text NOT NULL, cmd text NOT NULL, tgt text NOT NULL, kwargs text NOT NULL, ret text NOT NULL, username text NOT NULL, arg text NOT NULL, fun text NOT NULL ); -- -- Table structure for table 'salt_returns' -- -- note that 'success' must not have NOT NULL constraint, since -- some functions don't provide it. DROP TABLE IF EXISTS salt_returns; CREATE TABLE salt_returns ( added TIMESTAMP WITH TIME ZONE DEFAULT now(), fun text NOT NULL, jid varchar(20) NOT NULL, return text NOT NULL, id text NOT NULL, success boolean ); CREATE INDEX ON salt_returns (added); CREATE INDEX ON salt_returns (id); CREATE INDEX ON salt_returns (jid); CREATE INDEX ON salt_returns (fun); DROP TABLE IF EXISTS salt_events; CREATE TABLE salt_events ( id SERIAL, tag text NOT NULL, data text NOT NULL, alter_time TIMESTAMP WITH TIME ZONE DEFAULT now(), master_id text NOT NULL ); CREATE INDEX ON salt_events (tag); CREATE INDEX ON salt_events (data); CREATE INDEX ON salt_events (id); CREATE INDEX ON salt_events (master_id); EOF Required python modules: psycopg2 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import re import sys # Import salt libs import salt.utils.jid import salt.utils.json from salt.ext import six # Import third party libs try: import psycopg2 HAS_POSTGRES = True except ImportError: HAS_POSTGRES = False log = logging.getLogger(__name__) __virtualname__ = 'postgres_local_cache' def __virtual__(): if not HAS_POSTGRES: return (False, 'Could not import psycopg2; postges_local_cache disabled') return __virtualname__ def _get_conn(): ''' Return a postgres connection. ''' try: conn = psycopg2.connect( host=__opts__['master_job_cache.postgres.host'], user=__opts__['master_job_cache.postgres.user'], password=__opts__['master_job_cache.postgres.passwd'], database=__opts__['master_job_cache.postgres.db'], port=__opts__['master_job_cache.postgres.port']) except psycopg2.OperationalError: log.error('Could not connect to SQL server: %s', sys.exc_info()[0]) return None return conn def _close_conn(conn): ''' Close the postgres connection. ''' conn.commit() conn.close() def _format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': salt.utils.json.loads(job.get('arg', '[]')), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} # TODO: Add Metadata support when it is merged from develop return ret def _format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret def _gen_jid(cur): ''' Generate an unique job id ''' jid = salt.utils.jid.gen_jid(__opts__) sql = '''SELECT jid FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() if not data: return jid return None def returner(load): ''' Return data to a postgres server ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, return, id, success) VALUES (%s, %s, %s, %s, %s)''' try: ret = six.text_type(load['return']) except UnicodeDecodeError: ret = str(load['return']) job_ret = {'return': ret} if 'retcode' in load: job_ret['retcode'] = load['retcode'] if 'success' in load: job_ret['success'] = load['success'] cur.execute( sql, ( load['fun'], load['jid'], salt.utils.json.dumps(job_ret), load['id'], load.get('success'), ) ) _close_conn(conn) def event_return(events): ''' Return event to a postgres server Require that configuration be enabled via 'event_return' option in master config. ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() for event in events: tag = event.get('tag', '') data = event.get('data', '') sql = '''INSERT INTO salt_events (tag, data, master_id) VALUES (%s, %s, %s)''' cur.execute(sql, (tag, salt.utils.json.dumps(data), __opts__['id'])) _close_conn(conn) def save_load(jid, clear_load, minions=None): ''' Save the load to the specified jid id ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO jids ''' \ '''(jid, started, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun) ''' \ '''VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)''' cur.execute( sql, ( jid, salt.utils.jid.jid_to_time(jid), six.text_type(clear_load.get("tgt_type")), six.text_type(clear_load.get("cmd")), six.text_type(clear_load.get("tgt")), six.text_type(clear_load.get("kwargs")), six.text_type(clear_load.get("ret")), six.text_type(clear_load.get("user")), six.text_type(salt.utils.json.dumps(clear_load.get("arg"))), six.text_type(clear_load.get("fun")), ) ) # TODO: Add Metadata support when it is merged from develop _close_conn(conn) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def _escape_jid(jid): ''' Do proper formatting of the jid ''' jid = six.text_type(jid) jid = re.sub(r"'*", "", jid) return jid def _build_dict(data): ''' Rebuild dict ''' result = {} # TODO: Add Metadata support when it is merged from develop result["jid"] = data[0] result["tgt_type"] = data[1] result["cmd"] = data[2] result["tgt"] = data[3] result["kwargs"] = data[4] result["ret"] = data[5] result["user"] = data[6] result["arg"] = data[7] result["fun"] = data[8] return result def get_load(jid): ''' Return the load data that marks a specified jid ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT jid, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchone() if data: return _build_dict(data) _close_conn(conn) return {} def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT id, return FROM salt_returns WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() ret = {} if data: for minion, full_ret in data: ret_data = salt.utils.json.loads(full_ret) if not isinstance(ret_data, dict) or 'return' not in ret_data: # Convert the old format in which the return contains the only return data to the # new that is dict containing 'return' and optionally 'retcode' and 'success'. ret_data = {'return': ret_data} ret[minion] = ret_data _close_conn(conn) return ret def get_jids(): ''' Return a list of all job ids For master job cache this also formats the output and returns a string ''' conn = _get_conn() cur = conn.cursor() sql = '''SELECT ''' \ '''jid, tgt_type, cmd, tgt, kwargs, ret, username, arg, fun ''' \ '''FROM jids''' if __opts__['keep_jobs'] != 0: sql = sql + " WHERE started > NOW() - INTERVAL '" \ + six.text_type(__opts__['keep_jobs']) + "' HOUR" cur.execute(sql) ret = {} data = cur.fetchone() while data: data_dict = _build_dict(data) ret[data_dict["jid"]] = \ _format_jid_instance(data_dict["jid"], data_dict) data = cur.fetchone() cur.close() conn.close() return ret def clean_old_jobs(): ''' Clean out the old jobs from the job cache ''' return
saltstack/salt
salt/returners/postgres_local_cache.py
returner
python
def returner(load): ''' Return data to a postgres server ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, return, id, success) VALUES (%s, %s, %s, %s, %s)''' try: ret = six.text_type(load['return']) except UnicodeDecodeError: ret = str(load['return']) job_ret = {'return': ret} if 'retcode' in load: job_ret['retcode'] = load['retcode'] if 'success' in load: job_ret['success'] = load['success'] cur.execute( sql, ( load['fun'], load['jid'], salt.utils.json.dumps(job_ret), load['id'], load.get('success'), ) ) _close_conn(conn)
Return data to a postgres server
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/postgres_local_cache.py#L224-L253
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def _get_conn():\n '''\n Return a postgres connection.\n '''\n try:\n conn = psycopg2.connect(\n host=__opts__['master_job_cache.postgres.host'],\n user=__opts__['master_job_cache.postgres.user'],\n password=__opts__['master_job_cache.postgres.passwd'],\n database=__opts__['master_job_cache.postgres.db'],\n port=__opts__['master_job_cache.postgres.port'])\n except psycopg2.OperationalError:\n log.error('Could not connect to SQL server: %s', sys.exc_info()[0])\n return None\n return conn\n", "def _close_conn(conn):\n '''\n Close the postgres connection.\n '''\n conn.commit()\n conn.close()\n" ]
# -*- coding: utf-8 -*- ''' Use a postgresql server for the master job cache. This helps the job cache to cope with scale. .. note:: There are three PostgreSQL returners. Any can function as an external :ref:`master job cache <external-job-cache>`. but each has different features. SaltStack recommends :mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with a version of PostgreSQL that has the appropriate native binary JSON types. Otherwise, review :mod:`returners.postgres <salt.returners.postgres>` and :mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>` to see which module best suits your particular needs. :maintainer: gjredelinghuys@gmail.com :maturity: Stable :depends: psycopg2 :platform: all To enable this returner the minion will need the psycopg2 installed and the following values configured in the master config: .. code-block:: yaml master_job_cache: postgres_local_cache master_job_cache.postgres.host: 'salt' master_job_cache.postgres.user: 'salt' master_job_cache.postgres.passwd: 'salt' master_job_cache.postgres.db: 'salt' master_job_cache.postgres.port: 5432 Running the following command as the postgres user should create the database correctly: .. code-block:: sql psql << EOF CREATE ROLE salt WITH PASSWORD 'salt'; CREATE DATABASE salt WITH OWNER salt; EOF In case the postgres database is a remote host, you'll need this command also: .. code-block:: sql ALTER ROLE salt WITH LOGIN; and then: .. code-block:: sql psql -h localhost -U salt << EOF -- -- Table structure for table 'jids' -- DROP TABLE IF EXISTS jids; CREATE TABLE jids ( jid varchar(20) PRIMARY KEY, started TIMESTAMP WITH TIME ZONE DEFAULT now(), tgt_type text NOT NULL, cmd text NOT NULL, tgt text NOT NULL, kwargs text NOT NULL, ret text NOT NULL, username text NOT NULL, arg text NOT NULL, fun text NOT NULL ); -- -- Table structure for table 'salt_returns' -- -- note that 'success' must not have NOT NULL constraint, since -- some functions don't provide it. DROP TABLE IF EXISTS salt_returns; CREATE TABLE salt_returns ( added TIMESTAMP WITH TIME ZONE DEFAULT now(), fun text NOT NULL, jid varchar(20) NOT NULL, return text NOT NULL, id text NOT NULL, success boolean ); CREATE INDEX ON salt_returns (added); CREATE INDEX ON salt_returns (id); CREATE INDEX ON salt_returns (jid); CREATE INDEX ON salt_returns (fun); DROP TABLE IF EXISTS salt_events; CREATE TABLE salt_events ( id SERIAL, tag text NOT NULL, data text NOT NULL, alter_time TIMESTAMP WITH TIME ZONE DEFAULT now(), master_id text NOT NULL ); CREATE INDEX ON salt_events (tag); CREATE INDEX ON salt_events (data); CREATE INDEX ON salt_events (id); CREATE INDEX ON salt_events (master_id); EOF Required python modules: psycopg2 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import re import sys # Import salt libs import salt.utils.jid import salt.utils.json from salt.ext import six # Import third party libs try: import psycopg2 HAS_POSTGRES = True except ImportError: HAS_POSTGRES = False log = logging.getLogger(__name__) __virtualname__ = 'postgres_local_cache' def __virtual__(): if not HAS_POSTGRES: return (False, 'Could not import psycopg2; postges_local_cache disabled') return __virtualname__ def _get_conn(): ''' Return a postgres connection. ''' try: conn = psycopg2.connect( host=__opts__['master_job_cache.postgres.host'], user=__opts__['master_job_cache.postgres.user'], password=__opts__['master_job_cache.postgres.passwd'], database=__opts__['master_job_cache.postgres.db'], port=__opts__['master_job_cache.postgres.port']) except psycopg2.OperationalError: log.error('Could not connect to SQL server: %s', sys.exc_info()[0]) return None return conn def _close_conn(conn): ''' Close the postgres connection. ''' conn.commit() conn.close() def _format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': salt.utils.json.loads(job.get('arg', '[]')), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} # TODO: Add Metadata support when it is merged from develop return ret def _format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret def _gen_jid(cur): ''' Generate an unique job id ''' jid = salt.utils.jid.gen_jid(__opts__) sql = '''SELECT jid FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() if not data: return jid return None def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid). So do what you have to do to make sure that stays the case ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() if passed_jid is None: jid = _gen_jid(cur) else: jid = passed_jid while not jid: log.info("jid clash, generating a new one") jid = _gen_jid(cur) cur.close() conn.close() return jid def event_return(events): ''' Return event to a postgres server Require that configuration be enabled via 'event_return' option in master config. ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() for event in events: tag = event.get('tag', '') data = event.get('data', '') sql = '''INSERT INTO salt_events (tag, data, master_id) VALUES (%s, %s, %s)''' cur.execute(sql, (tag, salt.utils.json.dumps(data), __opts__['id'])) _close_conn(conn) def save_load(jid, clear_load, minions=None): ''' Save the load to the specified jid id ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO jids ''' \ '''(jid, started, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun) ''' \ '''VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)''' cur.execute( sql, ( jid, salt.utils.jid.jid_to_time(jid), six.text_type(clear_load.get("tgt_type")), six.text_type(clear_load.get("cmd")), six.text_type(clear_load.get("tgt")), six.text_type(clear_load.get("kwargs")), six.text_type(clear_load.get("ret")), six.text_type(clear_load.get("user")), six.text_type(salt.utils.json.dumps(clear_load.get("arg"))), six.text_type(clear_load.get("fun")), ) ) # TODO: Add Metadata support when it is merged from develop _close_conn(conn) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def _escape_jid(jid): ''' Do proper formatting of the jid ''' jid = six.text_type(jid) jid = re.sub(r"'*", "", jid) return jid def _build_dict(data): ''' Rebuild dict ''' result = {} # TODO: Add Metadata support when it is merged from develop result["jid"] = data[0] result["tgt_type"] = data[1] result["cmd"] = data[2] result["tgt"] = data[3] result["kwargs"] = data[4] result["ret"] = data[5] result["user"] = data[6] result["arg"] = data[7] result["fun"] = data[8] return result def get_load(jid): ''' Return the load data that marks a specified jid ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT jid, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchone() if data: return _build_dict(data) _close_conn(conn) return {} def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT id, return FROM salt_returns WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() ret = {} if data: for minion, full_ret in data: ret_data = salt.utils.json.loads(full_ret) if not isinstance(ret_data, dict) or 'return' not in ret_data: # Convert the old format in which the return contains the only return data to the # new that is dict containing 'return' and optionally 'retcode' and 'success'. ret_data = {'return': ret_data} ret[minion] = ret_data _close_conn(conn) return ret def get_jids(): ''' Return a list of all job ids For master job cache this also formats the output and returns a string ''' conn = _get_conn() cur = conn.cursor() sql = '''SELECT ''' \ '''jid, tgt_type, cmd, tgt, kwargs, ret, username, arg, fun ''' \ '''FROM jids''' if __opts__['keep_jobs'] != 0: sql = sql + " WHERE started > NOW() - INTERVAL '" \ + six.text_type(__opts__['keep_jobs']) + "' HOUR" cur.execute(sql) ret = {} data = cur.fetchone() while data: data_dict = _build_dict(data) ret[data_dict["jid"]] = \ _format_jid_instance(data_dict["jid"], data_dict) data = cur.fetchone() cur.close() conn.close() return ret def clean_old_jobs(): ''' Clean out the old jobs from the job cache ''' return
saltstack/salt
salt/returners/postgres_local_cache.py
event_return
python
def event_return(events): ''' Return event to a postgres server Require that configuration be enabled via 'event_return' option in master config. ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() for event in events: tag = event.get('tag', '') data = event.get('data', '') sql = '''INSERT INTO salt_events (tag, data, master_id) VALUES (%s, %s, %s)''' cur.execute(sql, (tag, salt.utils.json.dumps(data), __opts__['id'])) _close_conn(conn)
Return event to a postgres server Require that configuration be enabled via 'event_return' option in master config.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/postgres_local_cache.py#L256-L274
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def _get_conn():\n '''\n Return a postgres connection.\n '''\n try:\n conn = psycopg2.connect(\n host=__opts__['master_job_cache.postgres.host'],\n user=__opts__['master_job_cache.postgres.user'],\n password=__opts__['master_job_cache.postgres.passwd'],\n database=__opts__['master_job_cache.postgres.db'],\n port=__opts__['master_job_cache.postgres.port'])\n except psycopg2.OperationalError:\n log.error('Could not connect to SQL server: %s', sys.exc_info()[0])\n return None\n return conn\n", "def _close_conn(conn):\n '''\n Close the postgres connection.\n '''\n conn.commit()\n conn.close()\n" ]
# -*- coding: utf-8 -*- ''' Use a postgresql server for the master job cache. This helps the job cache to cope with scale. .. note:: There are three PostgreSQL returners. Any can function as an external :ref:`master job cache <external-job-cache>`. but each has different features. SaltStack recommends :mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with a version of PostgreSQL that has the appropriate native binary JSON types. Otherwise, review :mod:`returners.postgres <salt.returners.postgres>` and :mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>` to see which module best suits your particular needs. :maintainer: gjredelinghuys@gmail.com :maturity: Stable :depends: psycopg2 :platform: all To enable this returner the minion will need the psycopg2 installed and the following values configured in the master config: .. code-block:: yaml master_job_cache: postgres_local_cache master_job_cache.postgres.host: 'salt' master_job_cache.postgres.user: 'salt' master_job_cache.postgres.passwd: 'salt' master_job_cache.postgres.db: 'salt' master_job_cache.postgres.port: 5432 Running the following command as the postgres user should create the database correctly: .. code-block:: sql psql << EOF CREATE ROLE salt WITH PASSWORD 'salt'; CREATE DATABASE salt WITH OWNER salt; EOF In case the postgres database is a remote host, you'll need this command also: .. code-block:: sql ALTER ROLE salt WITH LOGIN; and then: .. code-block:: sql psql -h localhost -U salt << EOF -- -- Table structure for table 'jids' -- DROP TABLE IF EXISTS jids; CREATE TABLE jids ( jid varchar(20) PRIMARY KEY, started TIMESTAMP WITH TIME ZONE DEFAULT now(), tgt_type text NOT NULL, cmd text NOT NULL, tgt text NOT NULL, kwargs text NOT NULL, ret text NOT NULL, username text NOT NULL, arg text NOT NULL, fun text NOT NULL ); -- -- Table structure for table 'salt_returns' -- -- note that 'success' must not have NOT NULL constraint, since -- some functions don't provide it. DROP TABLE IF EXISTS salt_returns; CREATE TABLE salt_returns ( added TIMESTAMP WITH TIME ZONE DEFAULT now(), fun text NOT NULL, jid varchar(20) NOT NULL, return text NOT NULL, id text NOT NULL, success boolean ); CREATE INDEX ON salt_returns (added); CREATE INDEX ON salt_returns (id); CREATE INDEX ON salt_returns (jid); CREATE INDEX ON salt_returns (fun); DROP TABLE IF EXISTS salt_events; CREATE TABLE salt_events ( id SERIAL, tag text NOT NULL, data text NOT NULL, alter_time TIMESTAMP WITH TIME ZONE DEFAULT now(), master_id text NOT NULL ); CREATE INDEX ON salt_events (tag); CREATE INDEX ON salt_events (data); CREATE INDEX ON salt_events (id); CREATE INDEX ON salt_events (master_id); EOF Required python modules: psycopg2 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import re import sys # Import salt libs import salt.utils.jid import salt.utils.json from salt.ext import six # Import third party libs try: import psycopg2 HAS_POSTGRES = True except ImportError: HAS_POSTGRES = False log = logging.getLogger(__name__) __virtualname__ = 'postgres_local_cache' def __virtual__(): if not HAS_POSTGRES: return (False, 'Could not import psycopg2; postges_local_cache disabled') return __virtualname__ def _get_conn(): ''' Return a postgres connection. ''' try: conn = psycopg2.connect( host=__opts__['master_job_cache.postgres.host'], user=__opts__['master_job_cache.postgres.user'], password=__opts__['master_job_cache.postgres.passwd'], database=__opts__['master_job_cache.postgres.db'], port=__opts__['master_job_cache.postgres.port']) except psycopg2.OperationalError: log.error('Could not connect to SQL server: %s', sys.exc_info()[0]) return None return conn def _close_conn(conn): ''' Close the postgres connection. ''' conn.commit() conn.close() def _format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': salt.utils.json.loads(job.get('arg', '[]')), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} # TODO: Add Metadata support when it is merged from develop return ret def _format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret def _gen_jid(cur): ''' Generate an unique job id ''' jid = salt.utils.jid.gen_jid(__opts__) sql = '''SELECT jid FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() if not data: return jid return None def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid). So do what you have to do to make sure that stays the case ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() if passed_jid is None: jid = _gen_jid(cur) else: jid = passed_jid while not jid: log.info("jid clash, generating a new one") jid = _gen_jid(cur) cur.close() conn.close() return jid def returner(load): ''' Return data to a postgres server ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, return, id, success) VALUES (%s, %s, %s, %s, %s)''' try: ret = six.text_type(load['return']) except UnicodeDecodeError: ret = str(load['return']) job_ret = {'return': ret} if 'retcode' in load: job_ret['retcode'] = load['retcode'] if 'success' in load: job_ret['success'] = load['success'] cur.execute( sql, ( load['fun'], load['jid'], salt.utils.json.dumps(job_ret), load['id'], load.get('success'), ) ) _close_conn(conn) def save_load(jid, clear_load, minions=None): ''' Save the load to the specified jid id ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO jids ''' \ '''(jid, started, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun) ''' \ '''VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)''' cur.execute( sql, ( jid, salt.utils.jid.jid_to_time(jid), six.text_type(clear_load.get("tgt_type")), six.text_type(clear_load.get("cmd")), six.text_type(clear_load.get("tgt")), six.text_type(clear_load.get("kwargs")), six.text_type(clear_load.get("ret")), six.text_type(clear_load.get("user")), six.text_type(salt.utils.json.dumps(clear_load.get("arg"))), six.text_type(clear_load.get("fun")), ) ) # TODO: Add Metadata support when it is merged from develop _close_conn(conn) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def _escape_jid(jid): ''' Do proper formatting of the jid ''' jid = six.text_type(jid) jid = re.sub(r"'*", "", jid) return jid def _build_dict(data): ''' Rebuild dict ''' result = {} # TODO: Add Metadata support when it is merged from develop result["jid"] = data[0] result["tgt_type"] = data[1] result["cmd"] = data[2] result["tgt"] = data[3] result["kwargs"] = data[4] result["ret"] = data[5] result["user"] = data[6] result["arg"] = data[7] result["fun"] = data[8] return result def get_load(jid): ''' Return the load data that marks a specified jid ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT jid, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchone() if data: return _build_dict(data) _close_conn(conn) return {} def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT id, return FROM salt_returns WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() ret = {} if data: for minion, full_ret in data: ret_data = salt.utils.json.loads(full_ret) if not isinstance(ret_data, dict) or 'return' not in ret_data: # Convert the old format in which the return contains the only return data to the # new that is dict containing 'return' and optionally 'retcode' and 'success'. ret_data = {'return': ret_data} ret[minion] = ret_data _close_conn(conn) return ret def get_jids(): ''' Return a list of all job ids For master job cache this also formats the output and returns a string ''' conn = _get_conn() cur = conn.cursor() sql = '''SELECT ''' \ '''jid, tgt_type, cmd, tgt, kwargs, ret, username, arg, fun ''' \ '''FROM jids''' if __opts__['keep_jobs'] != 0: sql = sql + " WHERE started > NOW() - INTERVAL '" \ + six.text_type(__opts__['keep_jobs']) + "' HOUR" cur.execute(sql) ret = {} data = cur.fetchone() while data: data_dict = _build_dict(data) ret[data_dict["jid"]] = \ _format_jid_instance(data_dict["jid"], data_dict) data = cur.fetchone() cur.close() conn.close() return ret def clean_old_jobs(): ''' Clean out the old jobs from the job cache ''' return
saltstack/salt
salt/returners/postgres_local_cache.py
save_load
python
def save_load(jid, clear_load, minions=None): ''' Save the load to the specified jid id ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO jids ''' \ '''(jid, started, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun) ''' \ '''VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)''' cur.execute( sql, ( jid, salt.utils.jid.jid_to_time(jid), six.text_type(clear_load.get("tgt_type")), six.text_type(clear_load.get("cmd")), six.text_type(clear_load.get("tgt")), six.text_type(clear_load.get("kwargs")), six.text_type(clear_load.get("ret")), six.text_type(clear_load.get("user")), six.text_type(salt.utils.json.dumps(clear_load.get("arg"))), six.text_type(clear_load.get("fun")), ) ) # TODO: Add Metadata support when it is merged from develop _close_conn(conn)
Save the load to the specified jid id
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/postgres_local_cache.py#L277-L306
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def _get_conn():\n '''\n Return a postgres connection.\n '''\n try:\n conn = psycopg2.connect(\n host=__opts__['master_job_cache.postgres.host'],\n user=__opts__['master_job_cache.postgres.user'],\n password=__opts__['master_job_cache.postgres.passwd'],\n database=__opts__['master_job_cache.postgres.db'],\n port=__opts__['master_job_cache.postgres.port'])\n except psycopg2.OperationalError:\n log.error('Could not connect to SQL server: %s', sys.exc_info()[0])\n return None\n return conn\n", "def _close_conn(conn):\n '''\n Close the postgres connection.\n '''\n conn.commit()\n conn.close()\n", "def jid_to_time(jid):\n '''\n Convert a salt job id into the time when the job was invoked\n '''\n jid = six.text_type(jid)\n if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'):\n return ''\n year = jid[:4]\n month = jid[4:6]\n day = jid[6:8]\n hour = jid[8:10]\n minute = jid[10:12]\n second = jid[12:14]\n micro = jid[14:20]\n\n ret = '{0}, {1} {2} {3}:{4}:{5}.{6}'.format(year,\n months[int(month)],\n day,\n hour,\n minute,\n second,\n micro)\n return ret\n", "def _escape_jid(jid):\n '''\n Do proper formatting of the jid\n '''\n jid = six.text_type(jid)\n jid = re.sub(r\"'*\", \"\", jid)\n return jid\n" ]
# -*- coding: utf-8 -*- ''' Use a postgresql server for the master job cache. This helps the job cache to cope with scale. .. note:: There are three PostgreSQL returners. Any can function as an external :ref:`master job cache <external-job-cache>`. but each has different features. SaltStack recommends :mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with a version of PostgreSQL that has the appropriate native binary JSON types. Otherwise, review :mod:`returners.postgres <salt.returners.postgres>` and :mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>` to see which module best suits your particular needs. :maintainer: gjredelinghuys@gmail.com :maturity: Stable :depends: psycopg2 :platform: all To enable this returner the minion will need the psycopg2 installed and the following values configured in the master config: .. code-block:: yaml master_job_cache: postgres_local_cache master_job_cache.postgres.host: 'salt' master_job_cache.postgres.user: 'salt' master_job_cache.postgres.passwd: 'salt' master_job_cache.postgres.db: 'salt' master_job_cache.postgres.port: 5432 Running the following command as the postgres user should create the database correctly: .. code-block:: sql psql << EOF CREATE ROLE salt WITH PASSWORD 'salt'; CREATE DATABASE salt WITH OWNER salt; EOF In case the postgres database is a remote host, you'll need this command also: .. code-block:: sql ALTER ROLE salt WITH LOGIN; and then: .. code-block:: sql psql -h localhost -U salt << EOF -- -- Table structure for table 'jids' -- DROP TABLE IF EXISTS jids; CREATE TABLE jids ( jid varchar(20) PRIMARY KEY, started TIMESTAMP WITH TIME ZONE DEFAULT now(), tgt_type text NOT NULL, cmd text NOT NULL, tgt text NOT NULL, kwargs text NOT NULL, ret text NOT NULL, username text NOT NULL, arg text NOT NULL, fun text NOT NULL ); -- -- Table structure for table 'salt_returns' -- -- note that 'success' must not have NOT NULL constraint, since -- some functions don't provide it. DROP TABLE IF EXISTS salt_returns; CREATE TABLE salt_returns ( added TIMESTAMP WITH TIME ZONE DEFAULT now(), fun text NOT NULL, jid varchar(20) NOT NULL, return text NOT NULL, id text NOT NULL, success boolean ); CREATE INDEX ON salt_returns (added); CREATE INDEX ON salt_returns (id); CREATE INDEX ON salt_returns (jid); CREATE INDEX ON salt_returns (fun); DROP TABLE IF EXISTS salt_events; CREATE TABLE salt_events ( id SERIAL, tag text NOT NULL, data text NOT NULL, alter_time TIMESTAMP WITH TIME ZONE DEFAULT now(), master_id text NOT NULL ); CREATE INDEX ON salt_events (tag); CREATE INDEX ON salt_events (data); CREATE INDEX ON salt_events (id); CREATE INDEX ON salt_events (master_id); EOF Required python modules: psycopg2 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import re import sys # Import salt libs import salt.utils.jid import salt.utils.json from salt.ext import six # Import third party libs try: import psycopg2 HAS_POSTGRES = True except ImportError: HAS_POSTGRES = False log = logging.getLogger(__name__) __virtualname__ = 'postgres_local_cache' def __virtual__(): if not HAS_POSTGRES: return (False, 'Could not import psycopg2; postges_local_cache disabled') return __virtualname__ def _get_conn(): ''' Return a postgres connection. ''' try: conn = psycopg2.connect( host=__opts__['master_job_cache.postgres.host'], user=__opts__['master_job_cache.postgres.user'], password=__opts__['master_job_cache.postgres.passwd'], database=__opts__['master_job_cache.postgres.db'], port=__opts__['master_job_cache.postgres.port']) except psycopg2.OperationalError: log.error('Could not connect to SQL server: %s', sys.exc_info()[0]) return None return conn def _close_conn(conn): ''' Close the postgres connection. ''' conn.commit() conn.close() def _format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': salt.utils.json.loads(job.get('arg', '[]')), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} # TODO: Add Metadata support when it is merged from develop return ret def _format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret def _gen_jid(cur): ''' Generate an unique job id ''' jid = salt.utils.jid.gen_jid(__opts__) sql = '''SELECT jid FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() if not data: return jid return None def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid). So do what you have to do to make sure that stays the case ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() if passed_jid is None: jid = _gen_jid(cur) else: jid = passed_jid while not jid: log.info("jid clash, generating a new one") jid = _gen_jid(cur) cur.close() conn.close() return jid def returner(load): ''' Return data to a postgres server ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, return, id, success) VALUES (%s, %s, %s, %s, %s)''' try: ret = six.text_type(load['return']) except UnicodeDecodeError: ret = str(load['return']) job_ret = {'return': ret} if 'retcode' in load: job_ret['retcode'] = load['retcode'] if 'success' in load: job_ret['success'] = load['success'] cur.execute( sql, ( load['fun'], load['jid'], salt.utils.json.dumps(job_ret), load['id'], load.get('success'), ) ) _close_conn(conn) def event_return(events): ''' Return event to a postgres server Require that configuration be enabled via 'event_return' option in master config. ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() for event in events: tag = event.get('tag', '') data = event.get('data', '') sql = '''INSERT INTO salt_events (tag, data, master_id) VALUES (%s, %s, %s)''' cur.execute(sql, (tag, salt.utils.json.dumps(data), __opts__['id'])) _close_conn(conn) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def _escape_jid(jid): ''' Do proper formatting of the jid ''' jid = six.text_type(jid) jid = re.sub(r"'*", "", jid) return jid def _build_dict(data): ''' Rebuild dict ''' result = {} # TODO: Add Metadata support when it is merged from develop result["jid"] = data[0] result["tgt_type"] = data[1] result["cmd"] = data[2] result["tgt"] = data[3] result["kwargs"] = data[4] result["ret"] = data[5] result["user"] = data[6] result["arg"] = data[7] result["fun"] = data[8] return result def get_load(jid): ''' Return the load data that marks a specified jid ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT jid, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchone() if data: return _build_dict(data) _close_conn(conn) return {} def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT id, return FROM salt_returns WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() ret = {} if data: for minion, full_ret in data: ret_data = salt.utils.json.loads(full_ret) if not isinstance(ret_data, dict) or 'return' not in ret_data: # Convert the old format in which the return contains the only return data to the # new that is dict containing 'return' and optionally 'retcode' and 'success'. ret_data = {'return': ret_data} ret[minion] = ret_data _close_conn(conn) return ret def get_jids(): ''' Return a list of all job ids For master job cache this also formats the output and returns a string ''' conn = _get_conn() cur = conn.cursor() sql = '''SELECT ''' \ '''jid, tgt_type, cmd, tgt, kwargs, ret, username, arg, fun ''' \ '''FROM jids''' if __opts__['keep_jobs'] != 0: sql = sql + " WHERE started > NOW() - INTERVAL '" \ + six.text_type(__opts__['keep_jobs']) + "' HOUR" cur.execute(sql) ret = {} data = cur.fetchone() while data: data_dict = _build_dict(data) ret[data_dict["jid"]] = \ _format_jid_instance(data_dict["jid"], data_dict) data = cur.fetchone() cur.close() conn.close() return ret def clean_old_jobs(): ''' Clean out the old jobs from the job cache ''' return
saltstack/salt
salt/returners/postgres_local_cache.py
_escape_jid
python
def _escape_jid(jid): ''' Do proper formatting of the jid ''' jid = six.text_type(jid) jid = re.sub(r"'*", "", jid) return jid
Do proper formatting of the jid
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/postgres_local_cache.py#L316-L322
null
# -*- coding: utf-8 -*- ''' Use a postgresql server for the master job cache. This helps the job cache to cope with scale. .. note:: There are three PostgreSQL returners. Any can function as an external :ref:`master job cache <external-job-cache>`. but each has different features. SaltStack recommends :mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with a version of PostgreSQL that has the appropriate native binary JSON types. Otherwise, review :mod:`returners.postgres <salt.returners.postgres>` and :mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>` to see which module best suits your particular needs. :maintainer: gjredelinghuys@gmail.com :maturity: Stable :depends: psycopg2 :platform: all To enable this returner the minion will need the psycopg2 installed and the following values configured in the master config: .. code-block:: yaml master_job_cache: postgres_local_cache master_job_cache.postgres.host: 'salt' master_job_cache.postgres.user: 'salt' master_job_cache.postgres.passwd: 'salt' master_job_cache.postgres.db: 'salt' master_job_cache.postgres.port: 5432 Running the following command as the postgres user should create the database correctly: .. code-block:: sql psql << EOF CREATE ROLE salt WITH PASSWORD 'salt'; CREATE DATABASE salt WITH OWNER salt; EOF In case the postgres database is a remote host, you'll need this command also: .. code-block:: sql ALTER ROLE salt WITH LOGIN; and then: .. code-block:: sql psql -h localhost -U salt << EOF -- -- Table structure for table 'jids' -- DROP TABLE IF EXISTS jids; CREATE TABLE jids ( jid varchar(20) PRIMARY KEY, started TIMESTAMP WITH TIME ZONE DEFAULT now(), tgt_type text NOT NULL, cmd text NOT NULL, tgt text NOT NULL, kwargs text NOT NULL, ret text NOT NULL, username text NOT NULL, arg text NOT NULL, fun text NOT NULL ); -- -- Table structure for table 'salt_returns' -- -- note that 'success' must not have NOT NULL constraint, since -- some functions don't provide it. DROP TABLE IF EXISTS salt_returns; CREATE TABLE salt_returns ( added TIMESTAMP WITH TIME ZONE DEFAULT now(), fun text NOT NULL, jid varchar(20) NOT NULL, return text NOT NULL, id text NOT NULL, success boolean ); CREATE INDEX ON salt_returns (added); CREATE INDEX ON salt_returns (id); CREATE INDEX ON salt_returns (jid); CREATE INDEX ON salt_returns (fun); DROP TABLE IF EXISTS salt_events; CREATE TABLE salt_events ( id SERIAL, tag text NOT NULL, data text NOT NULL, alter_time TIMESTAMP WITH TIME ZONE DEFAULT now(), master_id text NOT NULL ); CREATE INDEX ON salt_events (tag); CREATE INDEX ON salt_events (data); CREATE INDEX ON salt_events (id); CREATE INDEX ON salt_events (master_id); EOF Required python modules: psycopg2 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import re import sys # Import salt libs import salt.utils.jid import salt.utils.json from salt.ext import six # Import third party libs try: import psycopg2 HAS_POSTGRES = True except ImportError: HAS_POSTGRES = False log = logging.getLogger(__name__) __virtualname__ = 'postgres_local_cache' def __virtual__(): if not HAS_POSTGRES: return (False, 'Could not import psycopg2; postges_local_cache disabled') return __virtualname__ def _get_conn(): ''' Return a postgres connection. ''' try: conn = psycopg2.connect( host=__opts__['master_job_cache.postgres.host'], user=__opts__['master_job_cache.postgres.user'], password=__opts__['master_job_cache.postgres.passwd'], database=__opts__['master_job_cache.postgres.db'], port=__opts__['master_job_cache.postgres.port']) except psycopg2.OperationalError: log.error('Could not connect to SQL server: %s', sys.exc_info()[0]) return None return conn def _close_conn(conn): ''' Close the postgres connection. ''' conn.commit() conn.close() def _format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': salt.utils.json.loads(job.get('arg', '[]')), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} # TODO: Add Metadata support when it is merged from develop return ret def _format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret def _gen_jid(cur): ''' Generate an unique job id ''' jid = salt.utils.jid.gen_jid(__opts__) sql = '''SELECT jid FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() if not data: return jid return None def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid). So do what you have to do to make sure that stays the case ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() if passed_jid is None: jid = _gen_jid(cur) else: jid = passed_jid while not jid: log.info("jid clash, generating a new one") jid = _gen_jid(cur) cur.close() conn.close() return jid def returner(load): ''' Return data to a postgres server ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, return, id, success) VALUES (%s, %s, %s, %s, %s)''' try: ret = six.text_type(load['return']) except UnicodeDecodeError: ret = str(load['return']) job_ret = {'return': ret} if 'retcode' in load: job_ret['retcode'] = load['retcode'] if 'success' in load: job_ret['success'] = load['success'] cur.execute( sql, ( load['fun'], load['jid'], salt.utils.json.dumps(job_ret), load['id'], load.get('success'), ) ) _close_conn(conn) def event_return(events): ''' Return event to a postgres server Require that configuration be enabled via 'event_return' option in master config. ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() for event in events: tag = event.get('tag', '') data = event.get('data', '') sql = '''INSERT INTO salt_events (tag, data, master_id) VALUES (%s, %s, %s)''' cur.execute(sql, (tag, salt.utils.json.dumps(data), __opts__['id'])) _close_conn(conn) def save_load(jid, clear_load, minions=None): ''' Save the load to the specified jid id ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO jids ''' \ '''(jid, started, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun) ''' \ '''VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)''' cur.execute( sql, ( jid, salt.utils.jid.jid_to_time(jid), six.text_type(clear_load.get("tgt_type")), six.text_type(clear_load.get("cmd")), six.text_type(clear_load.get("tgt")), six.text_type(clear_load.get("kwargs")), six.text_type(clear_load.get("ret")), six.text_type(clear_load.get("user")), six.text_type(salt.utils.json.dumps(clear_load.get("arg"))), six.text_type(clear_load.get("fun")), ) ) # TODO: Add Metadata support when it is merged from develop _close_conn(conn) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def _build_dict(data): ''' Rebuild dict ''' result = {} # TODO: Add Metadata support when it is merged from develop result["jid"] = data[0] result["tgt_type"] = data[1] result["cmd"] = data[2] result["tgt"] = data[3] result["kwargs"] = data[4] result["ret"] = data[5] result["user"] = data[6] result["arg"] = data[7] result["fun"] = data[8] return result def get_load(jid): ''' Return the load data that marks a specified jid ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT jid, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchone() if data: return _build_dict(data) _close_conn(conn) return {} def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT id, return FROM salt_returns WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() ret = {} if data: for minion, full_ret in data: ret_data = salt.utils.json.loads(full_ret) if not isinstance(ret_data, dict) or 'return' not in ret_data: # Convert the old format in which the return contains the only return data to the # new that is dict containing 'return' and optionally 'retcode' and 'success'. ret_data = {'return': ret_data} ret[minion] = ret_data _close_conn(conn) return ret def get_jids(): ''' Return a list of all job ids For master job cache this also formats the output and returns a string ''' conn = _get_conn() cur = conn.cursor() sql = '''SELECT ''' \ '''jid, tgt_type, cmd, tgt, kwargs, ret, username, arg, fun ''' \ '''FROM jids''' if __opts__['keep_jobs'] != 0: sql = sql + " WHERE started > NOW() - INTERVAL '" \ + six.text_type(__opts__['keep_jobs']) + "' HOUR" cur.execute(sql) ret = {} data = cur.fetchone() while data: data_dict = _build_dict(data) ret[data_dict["jid"]] = \ _format_jid_instance(data_dict["jid"], data_dict) data = cur.fetchone() cur.close() conn.close() return ret def clean_old_jobs(): ''' Clean out the old jobs from the job cache ''' return
saltstack/salt
salt/returners/postgres_local_cache.py
_build_dict
python
def _build_dict(data): ''' Rebuild dict ''' result = {} # TODO: Add Metadata support when it is merged from develop result["jid"] = data[0] result["tgt_type"] = data[1] result["cmd"] = data[2] result["tgt"] = data[3] result["kwargs"] = data[4] result["ret"] = data[5] result["user"] = data[6] result["arg"] = data[7] result["fun"] = data[8] return result
Rebuild dict
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/postgres_local_cache.py#L325-L340
null
# -*- coding: utf-8 -*- ''' Use a postgresql server for the master job cache. This helps the job cache to cope with scale. .. note:: There are three PostgreSQL returners. Any can function as an external :ref:`master job cache <external-job-cache>`. but each has different features. SaltStack recommends :mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with a version of PostgreSQL that has the appropriate native binary JSON types. Otherwise, review :mod:`returners.postgres <salt.returners.postgres>` and :mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>` to see which module best suits your particular needs. :maintainer: gjredelinghuys@gmail.com :maturity: Stable :depends: psycopg2 :platform: all To enable this returner the minion will need the psycopg2 installed and the following values configured in the master config: .. code-block:: yaml master_job_cache: postgres_local_cache master_job_cache.postgres.host: 'salt' master_job_cache.postgres.user: 'salt' master_job_cache.postgres.passwd: 'salt' master_job_cache.postgres.db: 'salt' master_job_cache.postgres.port: 5432 Running the following command as the postgres user should create the database correctly: .. code-block:: sql psql << EOF CREATE ROLE salt WITH PASSWORD 'salt'; CREATE DATABASE salt WITH OWNER salt; EOF In case the postgres database is a remote host, you'll need this command also: .. code-block:: sql ALTER ROLE salt WITH LOGIN; and then: .. code-block:: sql psql -h localhost -U salt << EOF -- -- Table structure for table 'jids' -- DROP TABLE IF EXISTS jids; CREATE TABLE jids ( jid varchar(20) PRIMARY KEY, started TIMESTAMP WITH TIME ZONE DEFAULT now(), tgt_type text NOT NULL, cmd text NOT NULL, tgt text NOT NULL, kwargs text NOT NULL, ret text NOT NULL, username text NOT NULL, arg text NOT NULL, fun text NOT NULL ); -- -- Table structure for table 'salt_returns' -- -- note that 'success' must not have NOT NULL constraint, since -- some functions don't provide it. DROP TABLE IF EXISTS salt_returns; CREATE TABLE salt_returns ( added TIMESTAMP WITH TIME ZONE DEFAULT now(), fun text NOT NULL, jid varchar(20) NOT NULL, return text NOT NULL, id text NOT NULL, success boolean ); CREATE INDEX ON salt_returns (added); CREATE INDEX ON salt_returns (id); CREATE INDEX ON salt_returns (jid); CREATE INDEX ON salt_returns (fun); DROP TABLE IF EXISTS salt_events; CREATE TABLE salt_events ( id SERIAL, tag text NOT NULL, data text NOT NULL, alter_time TIMESTAMP WITH TIME ZONE DEFAULT now(), master_id text NOT NULL ); CREATE INDEX ON salt_events (tag); CREATE INDEX ON salt_events (data); CREATE INDEX ON salt_events (id); CREATE INDEX ON salt_events (master_id); EOF Required python modules: psycopg2 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import re import sys # Import salt libs import salt.utils.jid import salt.utils.json from salt.ext import six # Import third party libs try: import psycopg2 HAS_POSTGRES = True except ImportError: HAS_POSTGRES = False log = logging.getLogger(__name__) __virtualname__ = 'postgres_local_cache' def __virtual__(): if not HAS_POSTGRES: return (False, 'Could not import psycopg2; postges_local_cache disabled') return __virtualname__ def _get_conn(): ''' Return a postgres connection. ''' try: conn = psycopg2.connect( host=__opts__['master_job_cache.postgres.host'], user=__opts__['master_job_cache.postgres.user'], password=__opts__['master_job_cache.postgres.passwd'], database=__opts__['master_job_cache.postgres.db'], port=__opts__['master_job_cache.postgres.port']) except psycopg2.OperationalError: log.error('Could not connect to SQL server: %s', sys.exc_info()[0]) return None return conn def _close_conn(conn): ''' Close the postgres connection. ''' conn.commit() conn.close() def _format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': salt.utils.json.loads(job.get('arg', '[]')), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} # TODO: Add Metadata support when it is merged from develop return ret def _format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret def _gen_jid(cur): ''' Generate an unique job id ''' jid = salt.utils.jid.gen_jid(__opts__) sql = '''SELECT jid FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() if not data: return jid return None def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid). So do what you have to do to make sure that stays the case ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() if passed_jid is None: jid = _gen_jid(cur) else: jid = passed_jid while not jid: log.info("jid clash, generating a new one") jid = _gen_jid(cur) cur.close() conn.close() return jid def returner(load): ''' Return data to a postgres server ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, return, id, success) VALUES (%s, %s, %s, %s, %s)''' try: ret = six.text_type(load['return']) except UnicodeDecodeError: ret = str(load['return']) job_ret = {'return': ret} if 'retcode' in load: job_ret['retcode'] = load['retcode'] if 'success' in load: job_ret['success'] = load['success'] cur.execute( sql, ( load['fun'], load['jid'], salt.utils.json.dumps(job_ret), load['id'], load.get('success'), ) ) _close_conn(conn) def event_return(events): ''' Return event to a postgres server Require that configuration be enabled via 'event_return' option in master config. ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() for event in events: tag = event.get('tag', '') data = event.get('data', '') sql = '''INSERT INTO salt_events (tag, data, master_id) VALUES (%s, %s, %s)''' cur.execute(sql, (tag, salt.utils.json.dumps(data), __opts__['id'])) _close_conn(conn) def save_load(jid, clear_load, minions=None): ''' Save the load to the specified jid id ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO jids ''' \ '''(jid, started, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun) ''' \ '''VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)''' cur.execute( sql, ( jid, salt.utils.jid.jid_to_time(jid), six.text_type(clear_load.get("tgt_type")), six.text_type(clear_load.get("cmd")), six.text_type(clear_load.get("tgt")), six.text_type(clear_load.get("kwargs")), six.text_type(clear_load.get("ret")), six.text_type(clear_load.get("user")), six.text_type(salt.utils.json.dumps(clear_load.get("arg"))), six.text_type(clear_load.get("fun")), ) ) # TODO: Add Metadata support when it is merged from develop _close_conn(conn) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def _escape_jid(jid): ''' Do proper formatting of the jid ''' jid = six.text_type(jid) jid = re.sub(r"'*", "", jid) return jid def get_load(jid): ''' Return the load data that marks a specified jid ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT jid, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchone() if data: return _build_dict(data) _close_conn(conn) return {} def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT id, return FROM salt_returns WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() ret = {} if data: for minion, full_ret in data: ret_data = salt.utils.json.loads(full_ret) if not isinstance(ret_data, dict) or 'return' not in ret_data: # Convert the old format in which the return contains the only return data to the # new that is dict containing 'return' and optionally 'retcode' and 'success'. ret_data = {'return': ret_data} ret[minion] = ret_data _close_conn(conn) return ret def get_jids(): ''' Return a list of all job ids For master job cache this also formats the output and returns a string ''' conn = _get_conn() cur = conn.cursor() sql = '''SELECT ''' \ '''jid, tgt_type, cmd, tgt, kwargs, ret, username, arg, fun ''' \ '''FROM jids''' if __opts__['keep_jobs'] != 0: sql = sql + " WHERE started > NOW() - INTERVAL '" \ + six.text_type(__opts__['keep_jobs']) + "' HOUR" cur.execute(sql) ret = {} data = cur.fetchone() while data: data_dict = _build_dict(data) ret[data_dict["jid"]] = \ _format_jid_instance(data_dict["jid"], data_dict) data = cur.fetchone() cur.close() conn.close() return ret def clean_old_jobs(): ''' Clean out the old jobs from the job cache ''' return
saltstack/salt
salt/returners/postgres_local_cache.py
get_load
python
def get_load(jid): ''' Return the load data that marks a specified jid ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT jid, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchone() if data: return _build_dict(data) _close_conn(conn) return {}
Return the load data that marks a specified jid
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/postgres_local_cache.py#L343-L359
[ "def _get_conn():\n '''\n Return a postgres connection.\n '''\n try:\n conn = psycopg2.connect(\n host=__opts__['master_job_cache.postgres.host'],\n user=__opts__['master_job_cache.postgres.user'],\n password=__opts__['master_job_cache.postgres.passwd'],\n database=__opts__['master_job_cache.postgres.db'],\n port=__opts__['master_job_cache.postgres.port'])\n except psycopg2.OperationalError:\n log.error('Could not connect to SQL server: %s', sys.exc_info()[0])\n return None\n return conn\n", "def _close_conn(conn):\n '''\n Close the postgres connection.\n '''\n conn.commit()\n conn.close()\n", "def _escape_jid(jid):\n '''\n Do proper formatting of the jid\n '''\n jid = six.text_type(jid)\n jid = re.sub(r\"'*\", \"\", jid)\n return jid\n", "def _build_dict(data):\n '''\n Rebuild dict\n '''\n result = {}\n # TODO: Add Metadata support when it is merged from develop\n result[\"jid\"] = data[0]\n result[\"tgt_type\"] = data[1]\n result[\"cmd\"] = data[2]\n result[\"tgt\"] = data[3]\n result[\"kwargs\"] = data[4]\n result[\"ret\"] = data[5]\n result[\"user\"] = data[6]\n result[\"arg\"] = data[7]\n result[\"fun\"] = data[8]\n return result\n" ]
# -*- coding: utf-8 -*- ''' Use a postgresql server for the master job cache. This helps the job cache to cope with scale. .. note:: There are three PostgreSQL returners. Any can function as an external :ref:`master job cache <external-job-cache>`. but each has different features. SaltStack recommends :mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with a version of PostgreSQL that has the appropriate native binary JSON types. Otherwise, review :mod:`returners.postgres <salt.returners.postgres>` and :mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>` to see which module best suits your particular needs. :maintainer: gjredelinghuys@gmail.com :maturity: Stable :depends: psycopg2 :platform: all To enable this returner the minion will need the psycopg2 installed and the following values configured in the master config: .. code-block:: yaml master_job_cache: postgres_local_cache master_job_cache.postgres.host: 'salt' master_job_cache.postgres.user: 'salt' master_job_cache.postgres.passwd: 'salt' master_job_cache.postgres.db: 'salt' master_job_cache.postgres.port: 5432 Running the following command as the postgres user should create the database correctly: .. code-block:: sql psql << EOF CREATE ROLE salt WITH PASSWORD 'salt'; CREATE DATABASE salt WITH OWNER salt; EOF In case the postgres database is a remote host, you'll need this command also: .. code-block:: sql ALTER ROLE salt WITH LOGIN; and then: .. code-block:: sql psql -h localhost -U salt << EOF -- -- Table structure for table 'jids' -- DROP TABLE IF EXISTS jids; CREATE TABLE jids ( jid varchar(20) PRIMARY KEY, started TIMESTAMP WITH TIME ZONE DEFAULT now(), tgt_type text NOT NULL, cmd text NOT NULL, tgt text NOT NULL, kwargs text NOT NULL, ret text NOT NULL, username text NOT NULL, arg text NOT NULL, fun text NOT NULL ); -- -- Table structure for table 'salt_returns' -- -- note that 'success' must not have NOT NULL constraint, since -- some functions don't provide it. DROP TABLE IF EXISTS salt_returns; CREATE TABLE salt_returns ( added TIMESTAMP WITH TIME ZONE DEFAULT now(), fun text NOT NULL, jid varchar(20) NOT NULL, return text NOT NULL, id text NOT NULL, success boolean ); CREATE INDEX ON salt_returns (added); CREATE INDEX ON salt_returns (id); CREATE INDEX ON salt_returns (jid); CREATE INDEX ON salt_returns (fun); DROP TABLE IF EXISTS salt_events; CREATE TABLE salt_events ( id SERIAL, tag text NOT NULL, data text NOT NULL, alter_time TIMESTAMP WITH TIME ZONE DEFAULT now(), master_id text NOT NULL ); CREATE INDEX ON salt_events (tag); CREATE INDEX ON salt_events (data); CREATE INDEX ON salt_events (id); CREATE INDEX ON salt_events (master_id); EOF Required python modules: psycopg2 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import re import sys # Import salt libs import salt.utils.jid import salt.utils.json from salt.ext import six # Import third party libs try: import psycopg2 HAS_POSTGRES = True except ImportError: HAS_POSTGRES = False log = logging.getLogger(__name__) __virtualname__ = 'postgres_local_cache' def __virtual__(): if not HAS_POSTGRES: return (False, 'Could not import psycopg2; postges_local_cache disabled') return __virtualname__ def _get_conn(): ''' Return a postgres connection. ''' try: conn = psycopg2.connect( host=__opts__['master_job_cache.postgres.host'], user=__opts__['master_job_cache.postgres.user'], password=__opts__['master_job_cache.postgres.passwd'], database=__opts__['master_job_cache.postgres.db'], port=__opts__['master_job_cache.postgres.port']) except psycopg2.OperationalError: log.error('Could not connect to SQL server: %s', sys.exc_info()[0]) return None return conn def _close_conn(conn): ''' Close the postgres connection. ''' conn.commit() conn.close() def _format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': salt.utils.json.loads(job.get('arg', '[]')), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} # TODO: Add Metadata support when it is merged from develop return ret def _format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret def _gen_jid(cur): ''' Generate an unique job id ''' jid = salt.utils.jid.gen_jid(__opts__) sql = '''SELECT jid FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() if not data: return jid return None def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid). So do what you have to do to make sure that stays the case ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() if passed_jid is None: jid = _gen_jid(cur) else: jid = passed_jid while not jid: log.info("jid clash, generating a new one") jid = _gen_jid(cur) cur.close() conn.close() return jid def returner(load): ''' Return data to a postgres server ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, return, id, success) VALUES (%s, %s, %s, %s, %s)''' try: ret = six.text_type(load['return']) except UnicodeDecodeError: ret = str(load['return']) job_ret = {'return': ret} if 'retcode' in load: job_ret['retcode'] = load['retcode'] if 'success' in load: job_ret['success'] = load['success'] cur.execute( sql, ( load['fun'], load['jid'], salt.utils.json.dumps(job_ret), load['id'], load.get('success'), ) ) _close_conn(conn) def event_return(events): ''' Return event to a postgres server Require that configuration be enabled via 'event_return' option in master config. ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() for event in events: tag = event.get('tag', '') data = event.get('data', '') sql = '''INSERT INTO salt_events (tag, data, master_id) VALUES (%s, %s, %s)''' cur.execute(sql, (tag, salt.utils.json.dumps(data), __opts__['id'])) _close_conn(conn) def save_load(jid, clear_load, minions=None): ''' Save the load to the specified jid id ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO jids ''' \ '''(jid, started, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun) ''' \ '''VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)''' cur.execute( sql, ( jid, salt.utils.jid.jid_to_time(jid), six.text_type(clear_load.get("tgt_type")), six.text_type(clear_load.get("cmd")), six.text_type(clear_load.get("tgt")), six.text_type(clear_load.get("kwargs")), six.text_type(clear_load.get("ret")), six.text_type(clear_load.get("user")), six.text_type(salt.utils.json.dumps(clear_load.get("arg"))), six.text_type(clear_load.get("fun")), ) ) # TODO: Add Metadata support when it is merged from develop _close_conn(conn) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def _escape_jid(jid): ''' Do proper formatting of the jid ''' jid = six.text_type(jid) jid = re.sub(r"'*", "", jid) return jid def _build_dict(data): ''' Rebuild dict ''' result = {} # TODO: Add Metadata support when it is merged from develop result["jid"] = data[0] result["tgt_type"] = data[1] result["cmd"] = data[2] result["tgt"] = data[3] result["kwargs"] = data[4] result["ret"] = data[5] result["user"] = data[6] result["arg"] = data[7] result["fun"] = data[8] return result def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT id, return FROM salt_returns WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() ret = {} if data: for minion, full_ret in data: ret_data = salt.utils.json.loads(full_ret) if not isinstance(ret_data, dict) or 'return' not in ret_data: # Convert the old format in which the return contains the only return data to the # new that is dict containing 'return' and optionally 'retcode' and 'success'. ret_data = {'return': ret_data} ret[minion] = ret_data _close_conn(conn) return ret def get_jids(): ''' Return a list of all job ids For master job cache this also formats the output and returns a string ''' conn = _get_conn() cur = conn.cursor() sql = '''SELECT ''' \ '''jid, tgt_type, cmd, tgt, kwargs, ret, username, arg, fun ''' \ '''FROM jids''' if __opts__['keep_jobs'] != 0: sql = sql + " WHERE started > NOW() - INTERVAL '" \ + six.text_type(__opts__['keep_jobs']) + "' HOUR" cur.execute(sql) ret = {} data = cur.fetchone() while data: data_dict = _build_dict(data) ret[data_dict["jid"]] = \ _format_jid_instance(data_dict["jid"], data_dict) data = cur.fetchone() cur.close() conn.close() return ret def clean_old_jobs(): ''' Clean out the old jobs from the job cache ''' return
saltstack/salt
salt/returners/postgres_local_cache.py
get_jid
python
def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT id, return FROM salt_returns WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() ret = {} if data: for minion, full_ret in data: ret_data = salt.utils.json.loads(full_ret) if not isinstance(ret_data, dict) or 'return' not in ret_data: # Convert the old format in which the return contains the only return data to the # new that is dict containing 'return' and optionally 'retcode' and 'success'. ret_data = {'return': ret_data} ret[minion] = ret_data _close_conn(conn) return ret
Return the information returned when the specified job id was executed
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/postgres_local_cache.py#L362-L385
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n", "def _get_conn():\n '''\n Return a postgres connection.\n '''\n try:\n conn = psycopg2.connect(\n host=__opts__['master_job_cache.postgres.host'],\n user=__opts__['master_job_cache.postgres.user'],\n password=__opts__['master_job_cache.postgres.passwd'],\n database=__opts__['master_job_cache.postgres.db'],\n port=__opts__['master_job_cache.postgres.port'])\n except psycopg2.OperationalError:\n log.error('Could not connect to SQL server: %s', sys.exc_info()[0])\n return None\n return conn\n", "def _close_conn(conn):\n '''\n Close the postgres connection.\n '''\n conn.commit()\n conn.close()\n", "def _escape_jid(jid):\n '''\n Do proper formatting of the jid\n '''\n jid = six.text_type(jid)\n jid = re.sub(r\"'*\", \"\", jid)\n return jid\n" ]
# -*- coding: utf-8 -*- ''' Use a postgresql server for the master job cache. This helps the job cache to cope with scale. .. note:: There are three PostgreSQL returners. Any can function as an external :ref:`master job cache <external-job-cache>`. but each has different features. SaltStack recommends :mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with a version of PostgreSQL that has the appropriate native binary JSON types. Otherwise, review :mod:`returners.postgres <salt.returners.postgres>` and :mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>` to see which module best suits your particular needs. :maintainer: gjredelinghuys@gmail.com :maturity: Stable :depends: psycopg2 :platform: all To enable this returner the minion will need the psycopg2 installed and the following values configured in the master config: .. code-block:: yaml master_job_cache: postgres_local_cache master_job_cache.postgres.host: 'salt' master_job_cache.postgres.user: 'salt' master_job_cache.postgres.passwd: 'salt' master_job_cache.postgres.db: 'salt' master_job_cache.postgres.port: 5432 Running the following command as the postgres user should create the database correctly: .. code-block:: sql psql << EOF CREATE ROLE salt WITH PASSWORD 'salt'; CREATE DATABASE salt WITH OWNER salt; EOF In case the postgres database is a remote host, you'll need this command also: .. code-block:: sql ALTER ROLE salt WITH LOGIN; and then: .. code-block:: sql psql -h localhost -U salt << EOF -- -- Table structure for table 'jids' -- DROP TABLE IF EXISTS jids; CREATE TABLE jids ( jid varchar(20) PRIMARY KEY, started TIMESTAMP WITH TIME ZONE DEFAULT now(), tgt_type text NOT NULL, cmd text NOT NULL, tgt text NOT NULL, kwargs text NOT NULL, ret text NOT NULL, username text NOT NULL, arg text NOT NULL, fun text NOT NULL ); -- -- Table structure for table 'salt_returns' -- -- note that 'success' must not have NOT NULL constraint, since -- some functions don't provide it. DROP TABLE IF EXISTS salt_returns; CREATE TABLE salt_returns ( added TIMESTAMP WITH TIME ZONE DEFAULT now(), fun text NOT NULL, jid varchar(20) NOT NULL, return text NOT NULL, id text NOT NULL, success boolean ); CREATE INDEX ON salt_returns (added); CREATE INDEX ON salt_returns (id); CREATE INDEX ON salt_returns (jid); CREATE INDEX ON salt_returns (fun); DROP TABLE IF EXISTS salt_events; CREATE TABLE salt_events ( id SERIAL, tag text NOT NULL, data text NOT NULL, alter_time TIMESTAMP WITH TIME ZONE DEFAULT now(), master_id text NOT NULL ); CREATE INDEX ON salt_events (tag); CREATE INDEX ON salt_events (data); CREATE INDEX ON salt_events (id); CREATE INDEX ON salt_events (master_id); EOF Required python modules: psycopg2 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import re import sys # Import salt libs import salt.utils.jid import salt.utils.json from salt.ext import six # Import third party libs try: import psycopg2 HAS_POSTGRES = True except ImportError: HAS_POSTGRES = False log = logging.getLogger(__name__) __virtualname__ = 'postgres_local_cache' def __virtual__(): if not HAS_POSTGRES: return (False, 'Could not import psycopg2; postges_local_cache disabled') return __virtualname__ def _get_conn(): ''' Return a postgres connection. ''' try: conn = psycopg2.connect( host=__opts__['master_job_cache.postgres.host'], user=__opts__['master_job_cache.postgres.user'], password=__opts__['master_job_cache.postgres.passwd'], database=__opts__['master_job_cache.postgres.db'], port=__opts__['master_job_cache.postgres.port']) except psycopg2.OperationalError: log.error('Could not connect to SQL server: %s', sys.exc_info()[0]) return None return conn def _close_conn(conn): ''' Close the postgres connection. ''' conn.commit() conn.close() def _format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': salt.utils.json.loads(job.get('arg', '[]')), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} # TODO: Add Metadata support when it is merged from develop return ret def _format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret def _gen_jid(cur): ''' Generate an unique job id ''' jid = salt.utils.jid.gen_jid(__opts__) sql = '''SELECT jid FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() if not data: return jid return None def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid). So do what you have to do to make sure that stays the case ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() if passed_jid is None: jid = _gen_jid(cur) else: jid = passed_jid while not jid: log.info("jid clash, generating a new one") jid = _gen_jid(cur) cur.close() conn.close() return jid def returner(load): ''' Return data to a postgres server ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, return, id, success) VALUES (%s, %s, %s, %s, %s)''' try: ret = six.text_type(load['return']) except UnicodeDecodeError: ret = str(load['return']) job_ret = {'return': ret} if 'retcode' in load: job_ret['retcode'] = load['retcode'] if 'success' in load: job_ret['success'] = load['success'] cur.execute( sql, ( load['fun'], load['jid'], salt.utils.json.dumps(job_ret), load['id'], load.get('success'), ) ) _close_conn(conn) def event_return(events): ''' Return event to a postgres server Require that configuration be enabled via 'event_return' option in master config. ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() for event in events: tag = event.get('tag', '') data = event.get('data', '') sql = '''INSERT INTO salt_events (tag, data, master_id) VALUES (%s, %s, %s)''' cur.execute(sql, (tag, salt.utils.json.dumps(data), __opts__['id'])) _close_conn(conn) def save_load(jid, clear_load, minions=None): ''' Save the load to the specified jid id ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO jids ''' \ '''(jid, started, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun) ''' \ '''VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)''' cur.execute( sql, ( jid, salt.utils.jid.jid_to_time(jid), six.text_type(clear_load.get("tgt_type")), six.text_type(clear_load.get("cmd")), six.text_type(clear_load.get("tgt")), six.text_type(clear_load.get("kwargs")), six.text_type(clear_load.get("ret")), six.text_type(clear_load.get("user")), six.text_type(salt.utils.json.dumps(clear_load.get("arg"))), six.text_type(clear_load.get("fun")), ) ) # TODO: Add Metadata support when it is merged from develop _close_conn(conn) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def _escape_jid(jid): ''' Do proper formatting of the jid ''' jid = six.text_type(jid) jid = re.sub(r"'*", "", jid) return jid def _build_dict(data): ''' Rebuild dict ''' result = {} # TODO: Add Metadata support when it is merged from develop result["jid"] = data[0] result["tgt_type"] = data[1] result["cmd"] = data[2] result["tgt"] = data[3] result["kwargs"] = data[4] result["ret"] = data[5] result["user"] = data[6] result["arg"] = data[7] result["fun"] = data[8] return result def get_load(jid): ''' Return the load data that marks a specified jid ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT jid, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchone() if data: return _build_dict(data) _close_conn(conn) return {} def get_jids(): ''' Return a list of all job ids For master job cache this also formats the output and returns a string ''' conn = _get_conn() cur = conn.cursor() sql = '''SELECT ''' \ '''jid, tgt_type, cmd, tgt, kwargs, ret, username, arg, fun ''' \ '''FROM jids''' if __opts__['keep_jobs'] != 0: sql = sql + " WHERE started > NOW() - INTERVAL '" \ + six.text_type(__opts__['keep_jobs']) + "' HOUR" cur.execute(sql) ret = {} data = cur.fetchone() while data: data_dict = _build_dict(data) ret[data_dict["jid"]] = \ _format_jid_instance(data_dict["jid"], data_dict) data = cur.fetchone() cur.close() conn.close() return ret def clean_old_jobs(): ''' Clean out the old jobs from the job cache ''' return
saltstack/salt
salt/returners/postgres_local_cache.py
get_jids
python
def get_jids(): ''' Return a list of all job ids For master job cache this also formats the output and returns a string ''' conn = _get_conn() cur = conn.cursor() sql = '''SELECT ''' \ '''jid, tgt_type, cmd, tgt, kwargs, ret, username, arg, fun ''' \ '''FROM jids''' if __opts__['keep_jobs'] != 0: sql = sql + " WHERE started > NOW() - INTERVAL '" \ + six.text_type(__opts__['keep_jobs']) + "' HOUR" cur.execute(sql) ret = {} data = cur.fetchone() while data: data_dict = _build_dict(data) ret[data_dict["jid"]] = \ _format_jid_instance(data_dict["jid"], data_dict) data = cur.fetchone() cur.close() conn.close() return ret
Return a list of all job ids For master job cache this also formats the output and returns a string
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/postgres_local_cache.py#L388-L412
[ "def _get_conn():\n '''\n Return a postgres connection.\n '''\n try:\n conn = psycopg2.connect(\n host=__opts__['master_job_cache.postgres.host'],\n user=__opts__['master_job_cache.postgres.user'],\n password=__opts__['master_job_cache.postgres.passwd'],\n database=__opts__['master_job_cache.postgres.db'],\n port=__opts__['master_job_cache.postgres.port'])\n except psycopg2.OperationalError:\n log.error('Could not connect to SQL server: %s', sys.exc_info()[0])\n return None\n return conn\n", "def _format_jid_instance(jid, job):\n '''\n Format the jid correctly\n '''\n ret = _format_job_instance(job)\n ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)})\n return ret\n", "def _build_dict(data):\n '''\n Rebuild dict\n '''\n result = {}\n # TODO: Add Metadata support when it is merged from develop\n result[\"jid\"] = data[0]\n result[\"tgt_type\"] = data[1]\n result[\"cmd\"] = data[2]\n result[\"tgt\"] = data[3]\n result[\"kwargs\"] = data[4]\n result[\"ret\"] = data[5]\n result[\"user\"] = data[6]\n result[\"arg\"] = data[7]\n result[\"fun\"] = data[8]\n return result\n" ]
# -*- coding: utf-8 -*- ''' Use a postgresql server for the master job cache. This helps the job cache to cope with scale. .. note:: There are three PostgreSQL returners. Any can function as an external :ref:`master job cache <external-job-cache>`. but each has different features. SaltStack recommends :mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with a version of PostgreSQL that has the appropriate native binary JSON types. Otherwise, review :mod:`returners.postgres <salt.returners.postgres>` and :mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>` to see which module best suits your particular needs. :maintainer: gjredelinghuys@gmail.com :maturity: Stable :depends: psycopg2 :platform: all To enable this returner the minion will need the psycopg2 installed and the following values configured in the master config: .. code-block:: yaml master_job_cache: postgres_local_cache master_job_cache.postgres.host: 'salt' master_job_cache.postgres.user: 'salt' master_job_cache.postgres.passwd: 'salt' master_job_cache.postgres.db: 'salt' master_job_cache.postgres.port: 5432 Running the following command as the postgres user should create the database correctly: .. code-block:: sql psql << EOF CREATE ROLE salt WITH PASSWORD 'salt'; CREATE DATABASE salt WITH OWNER salt; EOF In case the postgres database is a remote host, you'll need this command also: .. code-block:: sql ALTER ROLE salt WITH LOGIN; and then: .. code-block:: sql psql -h localhost -U salt << EOF -- -- Table structure for table 'jids' -- DROP TABLE IF EXISTS jids; CREATE TABLE jids ( jid varchar(20) PRIMARY KEY, started TIMESTAMP WITH TIME ZONE DEFAULT now(), tgt_type text NOT NULL, cmd text NOT NULL, tgt text NOT NULL, kwargs text NOT NULL, ret text NOT NULL, username text NOT NULL, arg text NOT NULL, fun text NOT NULL ); -- -- Table structure for table 'salt_returns' -- -- note that 'success' must not have NOT NULL constraint, since -- some functions don't provide it. DROP TABLE IF EXISTS salt_returns; CREATE TABLE salt_returns ( added TIMESTAMP WITH TIME ZONE DEFAULT now(), fun text NOT NULL, jid varchar(20) NOT NULL, return text NOT NULL, id text NOT NULL, success boolean ); CREATE INDEX ON salt_returns (added); CREATE INDEX ON salt_returns (id); CREATE INDEX ON salt_returns (jid); CREATE INDEX ON salt_returns (fun); DROP TABLE IF EXISTS salt_events; CREATE TABLE salt_events ( id SERIAL, tag text NOT NULL, data text NOT NULL, alter_time TIMESTAMP WITH TIME ZONE DEFAULT now(), master_id text NOT NULL ); CREATE INDEX ON salt_events (tag); CREATE INDEX ON salt_events (data); CREATE INDEX ON salt_events (id); CREATE INDEX ON salt_events (master_id); EOF Required python modules: psycopg2 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import re import sys # Import salt libs import salt.utils.jid import salt.utils.json from salt.ext import six # Import third party libs try: import psycopg2 HAS_POSTGRES = True except ImportError: HAS_POSTGRES = False log = logging.getLogger(__name__) __virtualname__ = 'postgres_local_cache' def __virtual__(): if not HAS_POSTGRES: return (False, 'Could not import psycopg2; postges_local_cache disabled') return __virtualname__ def _get_conn(): ''' Return a postgres connection. ''' try: conn = psycopg2.connect( host=__opts__['master_job_cache.postgres.host'], user=__opts__['master_job_cache.postgres.user'], password=__opts__['master_job_cache.postgres.passwd'], database=__opts__['master_job_cache.postgres.db'], port=__opts__['master_job_cache.postgres.port']) except psycopg2.OperationalError: log.error('Could not connect to SQL server: %s', sys.exc_info()[0]) return None return conn def _close_conn(conn): ''' Close the postgres connection. ''' conn.commit() conn.close() def _format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': salt.utils.json.loads(job.get('arg', '[]')), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} # TODO: Add Metadata support when it is merged from develop return ret def _format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret def _gen_jid(cur): ''' Generate an unique job id ''' jid = salt.utils.jid.gen_jid(__opts__) sql = '''SELECT jid FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() if not data: return jid return None def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid). So do what you have to do to make sure that stays the case ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() if passed_jid is None: jid = _gen_jid(cur) else: jid = passed_jid while not jid: log.info("jid clash, generating a new one") jid = _gen_jid(cur) cur.close() conn.close() return jid def returner(load): ''' Return data to a postgres server ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, return, id, success) VALUES (%s, %s, %s, %s, %s)''' try: ret = six.text_type(load['return']) except UnicodeDecodeError: ret = str(load['return']) job_ret = {'return': ret} if 'retcode' in load: job_ret['retcode'] = load['retcode'] if 'success' in load: job_ret['success'] = load['success'] cur.execute( sql, ( load['fun'], load['jid'], salt.utils.json.dumps(job_ret), load['id'], load.get('success'), ) ) _close_conn(conn) def event_return(events): ''' Return event to a postgres server Require that configuration be enabled via 'event_return' option in master config. ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() for event in events: tag = event.get('tag', '') data = event.get('data', '') sql = '''INSERT INTO salt_events (tag, data, master_id) VALUES (%s, %s, %s)''' cur.execute(sql, (tag, salt.utils.json.dumps(data), __opts__['id'])) _close_conn(conn) def save_load(jid, clear_load, minions=None): ''' Save the load to the specified jid id ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO jids ''' \ '''(jid, started, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun) ''' \ '''VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)''' cur.execute( sql, ( jid, salt.utils.jid.jid_to_time(jid), six.text_type(clear_load.get("tgt_type")), six.text_type(clear_load.get("cmd")), six.text_type(clear_load.get("tgt")), six.text_type(clear_load.get("kwargs")), six.text_type(clear_load.get("ret")), six.text_type(clear_load.get("user")), six.text_type(salt.utils.json.dumps(clear_load.get("arg"))), six.text_type(clear_load.get("fun")), ) ) # TODO: Add Metadata support when it is merged from develop _close_conn(conn) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def _escape_jid(jid): ''' Do proper formatting of the jid ''' jid = six.text_type(jid) jid = re.sub(r"'*", "", jid) return jid def _build_dict(data): ''' Rebuild dict ''' result = {} # TODO: Add Metadata support when it is merged from develop result["jid"] = data[0] result["tgt_type"] = data[1] result["cmd"] = data[2] result["tgt"] = data[3] result["kwargs"] = data[4] result["ret"] = data[5] result["user"] = data[6] result["arg"] = data[7] result["fun"] = data[8] return result def get_load(jid): ''' Return the load data that marks a specified jid ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT jid, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchone() if data: return _build_dict(data) _close_conn(conn) return {} def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT id, return FROM salt_returns WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() ret = {} if data: for minion, full_ret in data: ret_data = salt.utils.json.loads(full_ret) if not isinstance(ret_data, dict) or 'return' not in ret_data: # Convert the old format in which the return contains the only return data to the # new that is dict containing 'return' and optionally 'retcode' and 'success'. ret_data = {'return': ret_data} ret[minion] = ret_data _close_conn(conn) return ret def clean_old_jobs(): ''' Clean out the old jobs from the job cache ''' return
saltstack/salt
salt/modules/aix_shadow.py
login_failures
python
def login_failures(user): ''' Query for all accounts which have 3 or more login failures. CLI Example: .. code-block:: bash salt <minion_id> shadow.login_failures ALL ''' cmd = 'lsuser -a unsuccessful_login_count {0}'.format(user) cmd += " | grep -E 'unsuccessful_login_count=([3-9]|[0-9][0-9]+)'" out = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=True) ret = [] lines = out['stdout'].splitlines() for line in lines: ret.append(line.split()[0]) return ret
Query for all accounts which have 3 or more login failures. CLI Example: .. code-block:: bash salt <minion_id> shadow.login_failures ALL
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aix_shadow.py#L32-L54
null
# -*- coding: utf-8 -*- ''' Manage account locks on AIX systems .. versionadded:: 2018.3.0 :depends: none ''' from __future__ import absolute_import, print_function, unicode_literals # Import python librarie import logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'shadow' def __virtual__(): ''' Only load if kernel is AIX ''' if __grains__['kernel'] == 'AIX': return __virtualname__ return (False, 'The aix_shadow execution module failed to load: ' 'only available on AIX systems.') def locked(user): ''' Query for all accounts which are flagged as locked. CLI Example: .. code-block:: bash salt <minion_id> shadow.locked ALL ''' cmd = 'lsuser -a account_locked {0}'.format(user) cmd += ' | grep "account_locked=true"' out = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=True) ret = [] lines = out['stdout'].splitlines() for line in lines: ret.append(line.split()[0]) return ret def unlock(user): ''' Unlock user for locked account CLI Example: .. code-block:: bash salt <minion_id> shadow.unlock user ''' cmd = 'chuser account_locked=false {0} | ' \ 'chsec -f /etc/security/lastlog -a "unsuccessful_login_count=0" -s {0}'.format(user) ret = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=True) return ret
saltstack/salt
salt/modules/aix_shadow.py
unlock
python
def unlock(user): ''' Unlock user for locked account CLI Example: .. code-block:: bash salt <minion_id> shadow.unlock user ''' cmd = 'chuser account_locked=false {0} | ' \ 'chsec -f /etc/security/lastlog -a "unsuccessful_login_count=0" -s {0}'.format(user) ret = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=True) return ret
Unlock user for locked account CLI Example: .. code-block:: bash salt <minion_id> shadow.unlock user
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aix_shadow.py#L81-L96
null
# -*- coding: utf-8 -*- ''' Manage account locks on AIX systems .. versionadded:: 2018.3.0 :depends: none ''' from __future__ import absolute_import, print_function, unicode_literals # Import python librarie import logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'shadow' def __virtual__(): ''' Only load if kernel is AIX ''' if __grains__['kernel'] == 'AIX': return __virtualname__ return (False, 'The aix_shadow execution module failed to load: ' 'only available on AIX systems.') def login_failures(user): ''' Query for all accounts which have 3 or more login failures. CLI Example: .. code-block:: bash salt <minion_id> shadow.login_failures ALL ''' cmd = 'lsuser -a unsuccessful_login_count {0}'.format(user) cmd += " | grep -E 'unsuccessful_login_count=([3-9]|[0-9][0-9]+)'" out = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=True) ret = [] lines = out['stdout'].splitlines() for line in lines: ret.append(line.split()[0]) return ret def locked(user): ''' Query for all accounts which are flagged as locked. CLI Example: .. code-block:: bash salt <minion_id> shadow.locked ALL ''' cmd = 'lsuser -a account_locked {0}'.format(user) cmd += ' | grep "account_locked=true"' out = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=True) ret = [] lines = out['stdout'].splitlines() for line in lines: ret.append(line.split()[0]) return ret
saltstack/salt
salt/states/opsgenie.py
create_alert
python
def create_alert(name=None, api_key=None, reason=None, action_type="Create"): ''' Create an alert in OpsGenie. Example usage with Salt's requisites and other global state arguments could be found above. Required Parameters: api_key It's the API Key you've copied while adding integration in OpsGenie. reason It will be used as alert's default message in OpsGenie. Optional Parameters: name It will be used as alert's alias. If you want to use the close functionality you must provide name field for both states like in above case. action_type OpsGenie supports the default values Create/Close for action_type. You can customize this field with OpsGenie's custom actions for other purposes like adding notes or acknowledging alerts. ''' _, _, _, values = inspect.getargvalues(inspect.currentframe()) log.info("Arguments values: %s", values) ret = { 'result': '', 'name': '', 'changes': '', 'comment': '' } if api_key is None or reason is None: raise salt.exceptions.SaltInvocationError( 'API Key or Reason cannot be None.') if __opts__['test'] is True: ret[ 'comment'] = 'Test: {0} alert request will be processed ' \ 'using the API Key="{1}".'.format(action_type, api_key) # Return ``None`` when running with ``test=true``. ret['result'] = None return ret response_status_code, response_text = __salt__['opsgenie.post_data']( api_key=api_key, name=name, reason=reason, action_type=action_type ) if 200 <= response_status_code < 300: log.info( "POST Request has succeeded with message: %s status code: %s", response_text, response_status_code) ret[ 'comment'] = 'Test: {0} alert request will be processed' \ ' using the API Key="{1}".'.format( action_type, api_key) ret['result'] = True else: log.error( "POST Request has failed with error: %s status code: %s", response_text, response_status_code) ret['result'] = False return ret
Create an alert in OpsGenie. Example usage with Salt's requisites and other global state arguments could be found above. Required Parameters: api_key It's the API Key you've copied while adding integration in OpsGenie. reason It will be used as alert's default message in OpsGenie. Optional Parameters: name It will be used as alert's alias. If you want to use the close functionality you must provide name field for both states like in above case. action_type OpsGenie supports the default values Create/Close for action_type. You can customize this field with OpsGenie's custom actions for other purposes like adding notes or acknowledging alerts.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/opsgenie.py#L46-L119
null
# -*- coding: utf-8 -*- ''' Create/Close an alert in OpsGenie ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. versionadded:: 2018.3.0 This state is useful for creating or closing alerts in OpsGenie during state runs. .. code-block:: yaml used_space: disk.status: - name: / - maximum: 79% - minimum: 20% opsgenie_create_action_sender: opsgenie.create_alert: - api_key: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - reason: 'Disk capacity is out of designated range.' - name: disk.status - onfail: - disk: used_space opsgenie_close_action_sender: opsgenie.close_alert: - api_key: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - name: disk.status - require: - disk: used_space ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import inspect # Import Salt libs import salt.exceptions log = logging.getLogger(__name__) def close_alert(name=None, api_key=None, reason="Conditions are met.", action_type="Close"): ''' Close an alert in OpsGenie. It's a wrapper function for create_alert. Example usage with Salt's requisites and other global state arguments could be found above. Required Parameters: name It will be used as alert's alias. If you want to use the close functionality you must provide name field for both states like in above case. Optional Parameters: api_key It's the API Key you've copied while adding integration in OpsGenie. reason It will be used as alert's default message in OpsGenie. action_type OpsGenie supports the default values Create/Close for action_type. You can customize this field with OpsGenie's custom actions for other purposes like adding notes or acknowledging alerts. ''' if name is None: raise salt.exceptions.SaltInvocationError( 'Name cannot be None.') return create_alert(name, api_key, reason, action_type)
saltstack/salt
salt/states/opsgenie.py
close_alert
python
def close_alert(name=None, api_key=None, reason="Conditions are met.", action_type="Close"): ''' Close an alert in OpsGenie. It's a wrapper function for create_alert. Example usage with Salt's requisites and other global state arguments could be found above. Required Parameters: name It will be used as alert's alias. If you want to use the close functionality you must provide name field for both states like in above case. Optional Parameters: api_key It's the API Key you've copied while adding integration in OpsGenie. reason It will be used as alert's default message in OpsGenie. action_type OpsGenie supports the default values Create/Close for action_type. You can customize this field with OpsGenie's custom actions for other purposes like adding notes or acknowledging alerts. ''' if name is None: raise salt.exceptions.SaltInvocationError( 'Name cannot be None.') return create_alert(name, api_key, reason, action_type)
Close an alert in OpsGenie. It's a wrapper function for create_alert. Example usage with Salt's requisites and other global state arguments could be found above. Required Parameters: name It will be used as alert's alias. If you want to use the close functionality you must provide name field for both states like in above case. Optional Parameters: api_key It's the API Key you've copied while adding integration in OpsGenie. reason It will be used as alert's default message in OpsGenie. action_type OpsGenie supports the default values Create/Close for action_type. You can customize this field with OpsGenie's custom actions for other purposes like adding notes or acknowledging alerts.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/opsgenie.py#L122-L153
[ "def create_alert(name=None, api_key=None, reason=None, action_type=\"Create\"):\n '''\n Create an alert in OpsGenie. Example usage with Salt's requisites and other\n global state arguments could be found above.\n\n Required Parameters:\n\n api_key\n It's the API Key you've copied while adding integration in OpsGenie.\n\n reason\n It will be used as alert's default message in OpsGenie.\n\n Optional Parameters:\n\n name\n It will be used as alert's alias. If you want to use the close\n functionality you must provide name field for both states like\n in above case.\n\n action_type\n OpsGenie supports the default values Create/Close for action_type.\n You can customize this field with OpsGenie's custom actions for\n other purposes like adding notes or acknowledging alerts.\n '''\n\n _, _, _, values = inspect.getargvalues(inspect.currentframe())\n log.info(\"Arguments values: %s\", values)\n\n ret = {\n 'result': '',\n 'name': '',\n 'changes': '',\n 'comment': ''\n }\n\n if api_key is None or reason is None:\n raise salt.exceptions.SaltInvocationError(\n 'API Key or Reason cannot be None.')\n\n if __opts__['test'] is True:\n ret[\n 'comment'] = 'Test: {0} alert request will be processed ' \\\n 'using the API Key=\"{1}\".'.format(action_type, api_key)\n\n # Return ``None`` when running with ``test=true``.\n ret['result'] = None\n\n return ret\n\n response_status_code, response_text = __salt__['opsgenie.post_data'](\n api_key=api_key,\n name=name,\n reason=reason,\n action_type=action_type\n )\n\n if 200 <= response_status_code < 300:\n log.info(\n \"POST Request has succeeded with message: %s status code: %s\",\n response_text, response_status_code)\n ret[\n 'comment'] = 'Test: {0} alert request will be processed' \\\n ' using the API Key=\"{1}\".'.format(\n action_type,\n api_key)\n ret['result'] = True\n else:\n log.error(\n \"POST Request has failed with error: %s status code: %s\",\n response_text, response_status_code)\n ret['result'] = False\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Create/Close an alert in OpsGenie ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. versionadded:: 2018.3.0 This state is useful for creating or closing alerts in OpsGenie during state runs. .. code-block:: yaml used_space: disk.status: - name: / - maximum: 79% - minimum: 20% opsgenie_create_action_sender: opsgenie.create_alert: - api_key: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - reason: 'Disk capacity is out of designated range.' - name: disk.status - onfail: - disk: used_space opsgenie_close_action_sender: opsgenie.close_alert: - api_key: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - name: disk.status - require: - disk: used_space ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import inspect # Import Salt libs import salt.exceptions log = logging.getLogger(__name__) def create_alert(name=None, api_key=None, reason=None, action_type="Create"): ''' Create an alert in OpsGenie. Example usage with Salt's requisites and other global state arguments could be found above. Required Parameters: api_key It's the API Key you've copied while adding integration in OpsGenie. reason It will be used as alert's default message in OpsGenie. Optional Parameters: name It will be used as alert's alias. If you want to use the close functionality you must provide name field for both states like in above case. action_type OpsGenie supports the default values Create/Close for action_type. You can customize this field with OpsGenie's custom actions for other purposes like adding notes or acknowledging alerts. ''' _, _, _, values = inspect.getargvalues(inspect.currentframe()) log.info("Arguments values: %s", values) ret = { 'result': '', 'name': '', 'changes': '', 'comment': '' } if api_key is None or reason is None: raise salt.exceptions.SaltInvocationError( 'API Key or Reason cannot be None.') if __opts__['test'] is True: ret[ 'comment'] = 'Test: {0} alert request will be processed ' \ 'using the API Key="{1}".'.format(action_type, api_key) # Return ``None`` when running with ``test=true``. ret['result'] = None return ret response_status_code, response_text = __salt__['opsgenie.post_data']( api_key=api_key, name=name, reason=reason, action_type=action_type ) if 200 <= response_status_code < 300: log.info( "POST Request has succeeded with message: %s status code: %s", response_text, response_status_code) ret[ 'comment'] = 'Test: {0} alert request will be processed' \ ' using the API Key="{1}".'.format( action_type, api_key) ret['result'] = True else: log.error( "POST Request has failed with error: %s status code: %s", response_text, response_status_code) ret['result'] = False return ret
saltstack/salt
salt/states/probes.py
_expand_probes
python
def _expand_probes(probes, defaults): ''' Updates the probes dictionary with different levels of default values. ''' expected_probes = {} for probe_name, probe_test in six.iteritems(probes): if probe_name not in expected_probes.keys(): expected_probes[probe_name] = {} probe_defaults = probe_test.pop('defaults', {}) for test_name, test_details in six.iteritems(probe_test): test_defaults = test_details.pop('defaults', {}) expected_test_details = deepcopy(defaults) # copy first the general defaults expected_test_details.update(probe_defaults) # update with more specific defaults if any expected_test_details.update(test_defaults) # update with the most specific defaults if possible expected_test_details.update(test_details) # update with the actual config of the test if test_name not in expected_probes[probe_name].keys(): expected_probes[probe_name][test_name] = expected_test_details return expected_probes
Updates the probes dictionary with different levels of default values.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/probes.py#L84-L105
null
# -*- coding: utf-8 -*- ''' Network Probes =============== Configure RPM (JunOS)/SLA (Cisco) probes on the device via NAPALM proxy. :codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com> :maturity: new :depends: napalm :platform: unix Dependencies ------------ - :mod:`napalm probes management module <salt.modules.napalm_probes>` .. versionadded: 2016.11.0 ''' from __future__ import absolute_import # python std lib import logging log = logging.getLogger(__name__) from copy import deepcopy # salt modules from salt.utils.json import loads, dumps from salt.ext import six # import NAPALM utils import salt.utils.napalm # ---------------------------------------------------------------------------------------------------------------------- # state properties # ---------------------------------------------------------------------------------------------------------------------- __virtualname__ = 'probes' # ---------------------------------------------------------------------------------------------------------------------- # global variables # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # property functions # ---------------------------------------------------------------------------------------------------------------------- def __virtual__(): ''' NAPALM library must be installed for this module to work and run in a (proxy) minion. ''' return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__) # ---------------------------------------------------------------------------------------------------------------------- # helper functions -- will not be exported # ---------------------------------------------------------------------------------------------------------------------- def _default_ret(name): ''' Returns a default structure of the dictionary to be returned as output of the state functions. ''' return { 'name': name, 'result': False, 'changes': {}, 'comment': '' } def _retrieve_rpm_probes(): ''' Will retrieve the probes from the network device using salt module "probes" throught NAPALM proxy. ''' return __salt__['probes.config']() def _clean_probes(probes): ''' Will remove empty and useless values from the probes dictionary. ''' probes = _ordered_dict_to_dict(probes) # make sure we are working only with dict-type probes_copy = deepcopy(probes) for probe_name, probe_tests in six.iteritems(probes_copy): if not probe_tests: probes.pop(probe_name) continue for test_name, test_params in six.iteritems(probe_tests): if not test_params: probes[probe_name].pop(test_name) if not probes.get(probe_name): probes.pop(probe_name) return True def _compare_probes(configured_probes, expected_probes): ''' Compares configured probes on the device with the expected configuration and returns the differences. ''' new_probes = {} update_probes = {} remove_probes = {} # noth configured => configure with expected probes if not configured_probes: return { 'add': expected_probes } # noting expected => remove everything if not expected_probes: return { 'remove': configured_probes } configured_probes_keys_set = set(configured_probes.keys()) expected_probes_keys_set = set(expected_probes.keys()) new_probes_keys_set = expected_probes_keys_set - configured_probes_keys_set remove_probes_keys_set = configured_probes_keys_set - expected_probes_keys_set # new probes for probe_name in new_probes_keys_set: new_probes[probe_name] = expected_probes.pop(probe_name) # old probes, to be removed for probe_name in remove_probes_keys_set: remove_probes[probe_name] = configured_probes.pop(probe_name) # common probes for probe_name, probe_tests in six.iteritems(expected_probes): configured_probe_tests = configured_probes.get(probe_name, {}) configured_tests_keys_set = set(configured_probe_tests.keys()) expected_tests_keys_set = set(probe_tests.keys()) new_tests_keys_set = expected_tests_keys_set - configured_tests_keys_set remove_tests_keys_set = configured_tests_keys_set - expected_tests_keys_set # new tests for common probes for test_name in new_tests_keys_set: if probe_name not in new_probes.keys(): new_probes[probe_name] = {} new_probes[probe_name].update({ test_name: probe_tests.pop(test_name) }) # old tests for common probes for test_name in remove_tests_keys_set: if probe_name not in remove_probes.keys(): remove_probes[probe_name] = {} remove_probes[probe_name].update({ test_name: configured_probe_tests.pop(test_name) }) # common tests for common probes for test_name, test_params in six.iteritems(probe_tests): configured_test_params = configured_probe_tests.get(test_name, {}) # if test params are different, probe goes to update probes dict! if test_params != configured_test_params: if probe_name not in update_probes.keys(): update_probes[probe_name] = {} update_probes[probe_name].update({ test_name: test_params }) return { 'add': new_probes, 'update': update_probes, 'remove': remove_probes } def _ordered_dict_to_dict(probes): '''Mandatory to be dict type in order to be used in the NAPALM Jinja template.''' return loads(dumps(probes)) def _set_rpm_probes(probes): ''' Calls the Salt module "probes" to configure the probes on the device. ''' return __salt__['probes.set_probes']( _ordered_dict_to_dict(probes), # make sure this does not contain ordered dicts commit=False ) def _schedule_probes(probes): ''' Calls the Salt module "probes" to schedule the configured probes on the device. ''' return __salt__['probes.schedule_probes']( _ordered_dict_to_dict(probes), # make sure this does not contain ordered dicts commit=False ) def _delete_rpm_probes(probes): ''' Calls the Salt module "probes" to delete probes from the device. ''' return __salt__['probes.delete_probes']( _ordered_dict_to_dict(probes), # not mandatory, but let's make sure we catch all cases commit=False ) # ---------------------------------------------------------------------------------------------------------------------- # callable functions # ---------------------------------------------------------------------------------------------------------------------- def managed(name, probes, defaults=None): ''' Ensure the networks device is configured as specified in the state SLS file. Probes not specified will be removed, while probes not confiured as expected will trigger config updates. :param probes: Defines the probes as expected to be configured on the device. In order to ease the configuration and avoid repeating the same parameters for each probe, the next parameter (defaults) can be used, providing common characteristics. :param defaults: Specifies common parameters for the probes. SLS Example: .. code-block:: yaml rpmprobes: probes.managed: - probes: probe_name1: probe1_test1: source: 192.168.0.2 target: 192.168.0.1 probe1_test2: target: 172.17.17.1 probe1_test3: target: 8.8.8.8 probe_type: http-ping probe_name2: probe2_test1: test_interval: 100 - defaults: target: 10.10.10.10 probe_count: 15 test_interval: 3 probe_type: icmp-ping In the probes configuration, the only mandatory attribute is *target* (specified either in probes configuration, either in the defaults dictionary). All the other parameters will use the operating system defaults, if not provided: - ``source`` - Specifies the source IP Address to be used during the tests. If not specified will use the IP Address of the logical interface loopback0. - ``target`` - Destination IP Address. - ``probe_count`` - Total number of probes per test (1..15). System defaults: 1 on both JunOS & Cisco. - ``probe_interval`` - Delay between tests (0..86400 seconds). System defaults: 3 on JunOS, 5 on Cisco. - ``probe_type`` - Probe request type. Available options: - icmp-ping - tcp-ping - udp-ping Using the example configuration above, after running the state, on the device will be configured 4 probes, with the following properties: .. code-block:: yaml probe_name1: probe1_test1: source: 192.168.0.2 target: 192.168.0.1 probe_count: 15 test_interval: 3 probe_type: icmp-ping probe1_test2: target: 172.17.17.1 probe_count: 15 test_interval: 3 probe_type: icmp-ping probe1_test3: target: 8.8.8.8 probe_count: 15 test_interval: 3 probe_type: http-ping probe_name2: probe2_test1: target: 10.10.10.10 probe_count: 15 test_interval: 3 probe_type: icmp-ping ''' ret = _default_ret(name) result = True comment = '' rpm_probes_config = _retrieve_rpm_probes() # retrieves the RPM config from the device if not rpm_probes_config.get('result'): ret.update({ 'result': False, 'comment': 'Cannot retrieve configurtion of the probes from the device: {reason}'.format( reason=rpm_probes_config.get('comment') ) }) return ret # build expect probes config dictionary # using default values configured_probes = rpm_probes_config.get('out', {}) if not isinstance(defaults, dict): defaults = {} expected_probes = _expand_probes(probes, defaults) _clean_probes(configured_probes) # let's remove the unnecessary data from the configured probes _clean_probes(expected_probes) # also from the expected data # ----- Compare expected config with the existing config ----------------------------------------------------------> diff = _compare_probes(configured_probes, expected_probes) # compute the diff # <---- Compare expected config with the existing config ----------------------------------------------------------- # ----- Call set_probes and delete_probes as needed ---------------------------------------------------------------> add_probes = diff.get('add') update_probes = diff.get('update') remove_probes = diff.get('remove') changes = { 'added': _ordered_dict_to_dict(add_probes), 'updated': _ordered_dict_to_dict(update_probes), 'removed': _ordered_dict_to_dict(remove_probes) } ret.update({ 'changes': changes }) if __opts__['test'] is True: ret.update({ 'comment': 'Testing mode: configuration was not changed!', 'result': None }) return ret config_change_expected = False # to check if something changed and a commit would be needed if add_probes: added = _set_rpm_probes(add_probes) if added.get('result'): config_change_expected = True else: result = False comment += 'Cannot define new probes: {reason}\n'.format( reason=added.get('comment') ) if update_probes: updated = _set_rpm_probes(update_probes) if updated.get('result'): config_change_expected = True else: result = False comment += 'Cannot update probes: {reason}\n'.format( reason=updated.get('comment') ) if remove_probes: removed = _delete_rpm_probes(remove_probes) if removed.get('result'): config_change_expected = True else: result = False comment += 'Cannot remove probes! {reason}\n'.format( reason=removed.get('comment') ) # <---- Call set_probes and delete_probes as needed ---------------------------------------------------------------- # ----- Try to save changes ---------------------------------------------------------------------------------------> if config_change_expected: # if any changes expected, try to commit result, comment = __salt__['net.config_control']() # <---- Try to save changes ---------------------------------------------------------------------------------------- # ----- Try to schedule the probes --------------------------------------------------------------------------------> add_scheduled = _schedule_probes(add_probes) if add_scheduled.get('result'): # if able to load the template to schedule the probes, try to commit the scheduling data # (yes, a second commit is needed) # on devices such as Juniper, RPM probes do not need to be scheduled # therefore the template is empty and won't try to commit empty changes result, comment = __salt__['net.config_control']() if config_change_expected: if result and comment == '': # if any changes and was able to apply them comment = 'Probes updated successfully!' ret.update({ 'result': result, 'comment': comment }) return ret
saltstack/salt
salt/states/probes.py
_clean_probes
python
def _clean_probes(probes): ''' Will remove empty and useless values from the probes dictionary. ''' probes = _ordered_dict_to_dict(probes) # make sure we are working only with dict-type probes_copy = deepcopy(probes) for probe_name, probe_tests in six.iteritems(probes_copy): if not probe_tests: probes.pop(probe_name) continue for test_name, test_params in six.iteritems(probe_tests): if not test_params: probes[probe_name].pop(test_name) if not probes.get(probe_name): probes.pop(probe_name) return True
Will remove empty and useless values from the probes dictionary.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/probes.py#L108-L126
null
# -*- coding: utf-8 -*- ''' Network Probes =============== Configure RPM (JunOS)/SLA (Cisco) probes on the device via NAPALM proxy. :codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com> :maturity: new :depends: napalm :platform: unix Dependencies ------------ - :mod:`napalm probes management module <salt.modules.napalm_probes>` .. versionadded: 2016.11.0 ''' from __future__ import absolute_import # python std lib import logging log = logging.getLogger(__name__) from copy import deepcopy # salt modules from salt.utils.json import loads, dumps from salt.ext import six # import NAPALM utils import salt.utils.napalm # ---------------------------------------------------------------------------------------------------------------------- # state properties # ---------------------------------------------------------------------------------------------------------------------- __virtualname__ = 'probes' # ---------------------------------------------------------------------------------------------------------------------- # global variables # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # property functions # ---------------------------------------------------------------------------------------------------------------------- def __virtual__(): ''' NAPALM library must be installed for this module to work and run in a (proxy) minion. ''' return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__) # ---------------------------------------------------------------------------------------------------------------------- # helper functions -- will not be exported # ---------------------------------------------------------------------------------------------------------------------- def _default_ret(name): ''' Returns a default structure of the dictionary to be returned as output of the state functions. ''' return { 'name': name, 'result': False, 'changes': {}, 'comment': '' } def _retrieve_rpm_probes(): ''' Will retrieve the probes from the network device using salt module "probes" throught NAPALM proxy. ''' return __salt__['probes.config']() def _expand_probes(probes, defaults): ''' Updates the probes dictionary with different levels of default values. ''' expected_probes = {} for probe_name, probe_test in six.iteritems(probes): if probe_name not in expected_probes.keys(): expected_probes[probe_name] = {} probe_defaults = probe_test.pop('defaults', {}) for test_name, test_details in six.iteritems(probe_test): test_defaults = test_details.pop('defaults', {}) expected_test_details = deepcopy(defaults) # copy first the general defaults expected_test_details.update(probe_defaults) # update with more specific defaults if any expected_test_details.update(test_defaults) # update with the most specific defaults if possible expected_test_details.update(test_details) # update with the actual config of the test if test_name not in expected_probes[probe_name].keys(): expected_probes[probe_name][test_name] = expected_test_details return expected_probes def _compare_probes(configured_probes, expected_probes): ''' Compares configured probes on the device with the expected configuration and returns the differences. ''' new_probes = {} update_probes = {} remove_probes = {} # noth configured => configure with expected probes if not configured_probes: return { 'add': expected_probes } # noting expected => remove everything if not expected_probes: return { 'remove': configured_probes } configured_probes_keys_set = set(configured_probes.keys()) expected_probes_keys_set = set(expected_probes.keys()) new_probes_keys_set = expected_probes_keys_set - configured_probes_keys_set remove_probes_keys_set = configured_probes_keys_set - expected_probes_keys_set # new probes for probe_name in new_probes_keys_set: new_probes[probe_name] = expected_probes.pop(probe_name) # old probes, to be removed for probe_name in remove_probes_keys_set: remove_probes[probe_name] = configured_probes.pop(probe_name) # common probes for probe_name, probe_tests in six.iteritems(expected_probes): configured_probe_tests = configured_probes.get(probe_name, {}) configured_tests_keys_set = set(configured_probe_tests.keys()) expected_tests_keys_set = set(probe_tests.keys()) new_tests_keys_set = expected_tests_keys_set - configured_tests_keys_set remove_tests_keys_set = configured_tests_keys_set - expected_tests_keys_set # new tests for common probes for test_name in new_tests_keys_set: if probe_name not in new_probes.keys(): new_probes[probe_name] = {} new_probes[probe_name].update({ test_name: probe_tests.pop(test_name) }) # old tests for common probes for test_name in remove_tests_keys_set: if probe_name not in remove_probes.keys(): remove_probes[probe_name] = {} remove_probes[probe_name].update({ test_name: configured_probe_tests.pop(test_name) }) # common tests for common probes for test_name, test_params in six.iteritems(probe_tests): configured_test_params = configured_probe_tests.get(test_name, {}) # if test params are different, probe goes to update probes dict! if test_params != configured_test_params: if probe_name not in update_probes.keys(): update_probes[probe_name] = {} update_probes[probe_name].update({ test_name: test_params }) return { 'add': new_probes, 'update': update_probes, 'remove': remove_probes } def _ordered_dict_to_dict(probes): '''Mandatory to be dict type in order to be used in the NAPALM Jinja template.''' return loads(dumps(probes)) def _set_rpm_probes(probes): ''' Calls the Salt module "probes" to configure the probes on the device. ''' return __salt__['probes.set_probes']( _ordered_dict_to_dict(probes), # make sure this does not contain ordered dicts commit=False ) def _schedule_probes(probes): ''' Calls the Salt module "probes" to schedule the configured probes on the device. ''' return __salt__['probes.schedule_probes']( _ordered_dict_to_dict(probes), # make sure this does not contain ordered dicts commit=False ) def _delete_rpm_probes(probes): ''' Calls the Salt module "probes" to delete probes from the device. ''' return __salt__['probes.delete_probes']( _ordered_dict_to_dict(probes), # not mandatory, but let's make sure we catch all cases commit=False ) # ---------------------------------------------------------------------------------------------------------------------- # callable functions # ---------------------------------------------------------------------------------------------------------------------- def managed(name, probes, defaults=None): ''' Ensure the networks device is configured as specified in the state SLS file. Probes not specified will be removed, while probes not confiured as expected will trigger config updates. :param probes: Defines the probes as expected to be configured on the device. In order to ease the configuration and avoid repeating the same parameters for each probe, the next parameter (defaults) can be used, providing common characteristics. :param defaults: Specifies common parameters for the probes. SLS Example: .. code-block:: yaml rpmprobes: probes.managed: - probes: probe_name1: probe1_test1: source: 192.168.0.2 target: 192.168.0.1 probe1_test2: target: 172.17.17.1 probe1_test3: target: 8.8.8.8 probe_type: http-ping probe_name2: probe2_test1: test_interval: 100 - defaults: target: 10.10.10.10 probe_count: 15 test_interval: 3 probe_type: icmp-ping In the probes configuration, the only mandatory attribute is *target* (specified either in probes configuration, either in the defaults dictionary). All the other parameters will use the operating system defaults, if not provided: - ``source`` - Specifies the source IP Address to be used during the tests. If not specified will use the IP Address of the logical interface loopback0. - ``target`` - Destination IP Address. - ``probe_count`` - Total number of probes per test (1..15). System defaults: 1 on both JunOS & Cisco. - ``probe_interval`` - Delay between tests (0..86400 seconds). System defaults: 3 on JunOS, 5 on Cisco. - ``probe_type`` - Probe request type. Available options: - icmp-ping - tcp-ping - udp-ping Using the example configuration above, after running the state, on the device will be configured 4 probes, with the following properties: .. code-block:: yaml probe_name1: probe1_test1: source: 192.168.0.2 target: 192.168.0.1 probe_count: 15 test_interval: 3 probe_type: icmp-ping probe1_test2: target: 172.17.17.1 probe_count: 15 test_interval: 3 probe_type: icmp-ping probe1_test3: target: 8.8.8.8 probe_count: 15 test_interval: 3 probe_type: http-ping probe_name2: probe2_test1: target: 10.10.10.10 probe_count: 15 test_interval: 3 probe_type: icmp-ping ''' ret = _default_ret(name) result = True comment = '' rpm_probes_config = _retrieve_rpm_probes() # retrieves the RPM config from the device if not rpm_probes_config.get('result'): ret.update({ 'result': False, 'comment': 'Cannot retrieve configurtion of the probes from the device: {reason}'.format( reason=rpm_probes_config.get('comment') ) }) return ret # build expect probes config dictionary # using default values configured_probes = rpm_probes_config.get('out', {}) if not isinstance(defaults, dict): defaults = {} expected_probes = _expand_probes(probes, defaults) _clean_probes(configured_probes) # let's remove the unnecessary data from the configured probes _clean_probes(expected_probes) # also from the expected data # ----- Compare expected config with the existing config ----------------------------------------------------------> diff = _compare_probes(configured_probes, expected_probes) # compute the diff # <---- Compare expected config with the existing config ----------------------------------------------------------- # ----- Call set_probes and delete_probes as needed ---------------------------------------------------------------> add_probes = diff.get('add') update_probes = diff.get('update') remove_probes = diff.get('remove') changes = { 'added': _ordered_dict_to_dict(add_probes), 'updated': _ordered_dict_to_dict(update_probes), 'removed': _ordered_dict_to_dict(remove_probes) } ret.update({ 'changes': changes }) if __opts__['test'] is True: ret.update({ 'comment': 'Testing mode: configuration was not changed!', 'result': None }) return ret config_change_expected = False # to check if something changed and a commit would be needed if add_probes: added = _set_rpm_probes(add_probes) if added.get('result'): config_change_expected = True else: result = False comment += 'Cannot define new probes: {reason}\n'.format( reason=added.get('comment') ) if update_probes: updated = _set_rpm_probes(update_probes) if updated.get('result'): config_change_expected = True else: result = False comment += 'Cannot update probes: {reason}\n'.format( reason=updated.get('comment') ) if remove_probes: removed = _delete_rpm_probes(remove_probes) if removed.get('result'): config_change_expected = True else: result = False comment += 'Cannot remove probes! {reason}\n'.format( reason=removed.get('comment') ) # <---- Call set_probes and delete_probes as needed ---------------------------------------------------------------- # ----- Try to save changes ---------------------------------------------------------------------------------------> if config_change_expected: # if any changes expected, try to commit result, comment = __salt__['net.config_control']() # <---- Try to save changes ---------------------------------------------------------------------------------------- # ----- Try to schedule the probes --------------------------------------------------------------------------------> add_scheduled = _schedule_probes(add_probes) if add_scheduled.get('result'): # if able to load the template to schedule the probes, try to commit the scheduling data # (yes, a second commit is needed) # on devices such as Juniper, RPM probes do not need to be scheduled # therefore the template is empty and won't try to commit empty changes result, comment = __salt__['net.config_control']() if config_change_expected: if result and comment == '': # if any changes and was able to apply them comment = 'Probes updated successfully!' ret.update({ 'result': result, 'comment': comment }) return ret
saltstack/salt
salt/states/probes.py
_compare_probes
python
def _compare_probes(configured_probes, expected_probes): ''' Compares configured probes on the device with the expected configuration and returns the differences. ''' new_probes = {} update_probes = {} remove_probes = {} # noth configured => configure with expected probes if not configured_probes: return { 'add': expected_probes } # noting expected => remove everything if not expected_probes: return { 'remove': configured_probes } configured_probes_keys_set = set(configured_probes.keys()) expected_probes_keys_set = set(expected_probes.keys()) new_probes_keys_set = expected_probes_keys_set - configured_probes_keys_set remove_probes_keys_set = configured_probes_keys_set - expected_probes_keys_set # new probes for probe_name in new_probes_keys_set: new_probes[probe_name] = expected_probes.pop(probe_name) # old probes, to be removed for probe_name in remove_probes_keys_set: remove_probes[probe_name] = configured_probes.pop(probe_name) # common probes for probe_name, probe_tests in six.iteritems(expected_probes): configured_probe_tests = configured_probes.get(probe_name, {}) configured_tests_keys_set = set(configured_probe_tests.keys()) expected_tests_keys_set = set(probe_tests.keys()) new_tests_keys_set = expected_tests_keys_set - configured_tests_keys_set remove_tests_keys_set = configured_tests_keys_set - expected_tests_keys_set # new tests for common probes for test_name in new_tests_keys_set: if probe_name not in new_probes.keys(): new_probes[probe_name] = {} new_probes[probe_name].update({ test_name: probe_tests.pop(test_name) }) # old tests for common probes for test_name in remove_tests_keys_set: if probe_name not in remove_probes.keys(): remove_probes[probe_name] = {} remove_probes[probe_name].update({ test_name: configured_probe_tests.pop(test_name) }) # common tests for common probes for test_name, test_params in six.iteritems(probe_tests): configured_test_params = configured_probe_tests.get(test_name, {}) # if test params are different, probe goes to update probes dict! if test_params != configured_test_params: if probe_name not in update_probes.keys(): update_probes[probe_name] = {} update_probes[probe_name].update({ test_name: test_params }) return { 'add': new_probes, 'update': update_probes, 'remove': remove_probes }
Compares configured probes on the device with the expected configuration and returns the differences.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/probes.py#L129-L201
null
# -*- coding: utf-8 -*- ''' Network Probes =============== Configure RPM (JunOS)/SLA (Cisco) probes on the device via NAPALM proxy. :codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com> :maturity: new :depends: napalm :platform: unix Dependencies ------------ - :mod:`napalm probes management module <salt.modules.napalm_probes>` .. versionadded: 2016.11.0 ''' from __future__ import absolute_import # python std lib import logging log = logging.getLogger(__name__) from copy import deepcopy # salt modules from salt.utils.json import loads, dumps from salt.ext import six # import NAPALM utils import salt.utils.napalm # ---------------------------------------------------------------------------------------------------------------------- # state properties # ---------------------------------------------------------------------------------------------------------------------- __virtualname__ = 'probes' # ---------------------------------------------------------------------------------------------------------------------- # global variables # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # property functions # ---------------------------------------------------------------------------------------------------------------------- def __virtual__(): ''' NAPALM library must be installed for this module to work and run in a (proxy) minion. ''' return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__) # ---------------------------------------------------------------------------------------------------------------------- # helper functions -- will not be exported # ---------------------------------------------------------------------------------------------------------------------- def _default_ret(name): ''' Returns a default structure of the dictionary to be returned as output of the state functions. ''' return { 'name': name, 'result': False, 'changes': {}, 'comment': '' } def _retrieve_rpm_probes(): ''' Will retrieve the probes from the network device using salt module "probes" throught NAPALM proxy. ''' return __salt__['probes.config']() def _expand_probes(probes, defaults): ''' Updates the probes dictionary with different levels of default values. ''' expected_probes = {} for probe_name, probe_test in six.iteritems(probes): if probe_name not in expected_probes.keys(): expected_probes[probe_name] = {} probe_defaults = probe_test.pop('defaults', {}) for test_name, test_details in six.iteritems(probe_test): test_defaults = test_details.pop('defaults', {}) expected_test_details = deepcopy(defaults) # copy first the general defaults expected_test_details.update(probe_defaults) # update with more specific defaults if any expected_test_details.update(test_defaults) # update with the most specific defaults if possible expected_test_details.update(test_details) # update with the actual config of the test if test_name not in expected_probes[probe_name].keys(): expected_probes[probe_name][test_name] = expected_test_details return expected_probes def _clean_probes(probes): ''' Will remove empty and useless values from the probes dictionary. ''' probes = _ordered_dict_to_dict(probes) # make sure we are working only with dict-type probes_copy = deepcopy(probes) for probe_name, probe_tests in six.iteritems(probes_copy): if not probe_tests: probes.pop(probe_name) continue for test_name, test_params in six.iteritems(probe_tests): if not test_params: probes[probe_name].pop(test_name) if not probes.get(probe_name): probes.pop(probe_name) return True def _ordered_dict_to_dict(probes): '''Mandatory to be dict type in order to be used in the NAPALM Jinja template.''' return loads(dumps(probes)) def _set_rpm_probes(probes): ''' Calls the Salt module "probes" to configure the probes on the device. ''' return __salt__['probes.set_probes']( _ordered_dict_to_dict(probes), # make sure this does not contain ordered dicts commit=False ) def _schedule_probes(probes): ''' Calls the Salt module "probes" to schedule the configured probes on the device. ''' return __salt__['probes.schedule_probes']( _ordered_dict_to_dict(probes), # make sure this does not contain ordered dicts commit=False ) def _delete_rpm_probes(probes): ''' Calls the Salt module "probes" to delete probes from the device. ''' return __salt__['probes.delete_probes']( _ordered_dict_to_dict(probes), # not mandatory, but let's make sure we catch all cases commit=False ) # ---------------------------------------------------------------------------------------------------------------------- # callable functions # ---------------------------------------------------------------------------------------------------------------------- def managed(name, probes, defaults=None): ''' Ensure the networks device is configured as specified in the state SLS file. Probes not specified will be removed, while probes not confiured as expected will trigger config updates. :param probes: Defines the probes as expected to be configured on the device. In order to ease the configuration and avoid repeating the same parameters for each probe, the next parameter (defaults) can be used, providing common characteristics. :param defaults: Specifies common parameters for the probes. SLS Example: .. code-block:: yaml rpmprobes: probes.managed: - probes: probe_name1: probe1_test1: source: 192.168.0.2 target: 192.168.0.1 probe1_test2: target: 172.17.17.1 probe1_test3: target: 8.8.8.8 probe_type: http-ping probe_name2: probe2_test1: test_interval: 100 - defaults: target: 10.10.10.10 probe_count: 15 test_interval: 3 probe_type: icmp-ping In the probes configuration, the only mandatory attribute is *target* (specified either in probes configuration, either in the defaults dictionary). All the other parameters will use the operating system defaults, if not provided: - ``source`` - Specifies the source IP Address to be used during the tests. If not specified will use the IP Address of the logical interface loopback0. - ``target`` - Destination IP Address. - ``probe_count`` - Total number of probes per test (1..15). System defaults: 1 on both JunOS & Cisco. - ``probe_interval`` - Delay between tests (0..86400 seconds). System defaults: 3 on JunOS, 5 on Cisco. - ``probe_type`` - Probe request type. Available options: - icmp-ping - tcp-ping - udp-ping Using the example configuration above, after running the state, on the device will be configured 4 probes, with the following properties: .. code-block:: yaml probe_name1: probe1_test1: source: 192.168.0.2 target: 192.168.0.1 probe_count: 15 test_interval: 3 probe_type: icmp-ping probe1_test2: target: 172.17.17.1 probe_count: 15 test_interval: 3 probe_type: icmp-ping probe1_test3: target: 8.8.8.8 probe_count: 15 test_interval: 3 probe_type: http-ping probe_name2: probe2_test1: target: 10.10.10.10 probe_count: 15 test_interval: 3 probe_type: icmp-ping ''' ret = _default_ret(name) result = True comment = '' rpm_probes_config = _retrieve_rpm_probes() # retrieves the RPM config from the device if not rpm_probes_config.get('result'): ret.update({ 'result': False, 'comment': 'Cannot retrieve configurtion of the probes from the device: {reason}'.format( reason=rpm_probes_config.get('comment') ) }) return ret # build expect probes config dictionary # using default values configured_probes = rpm_probes_config.get('out', {}) if not isinstance(defaults, dict): defaults = {} expected_probes = _expand_probes(probes, defaults) _clean_probes(configured_probes) # let's remove the unnecessary data from the configured probes _clean_probes(expected_probes) # also from the expected data # ----- Compare expected config with the existing config ----------------------------------------------------------> diff = _compare_probes(configured_probes, expected_probes) # compute the diff # <---- Compare expected config with the existing config ----------------------------------------------------------- # ----- Call set_probes and delete_probes as needed ---------------------------------------------------------------> add_probes = diff.get('add') update_probes = diff.get('update') remove_probes = diff.get('remove') changes = { 'added': _ordered_dict_to_dict(add_probes), 'updated': _ordered_dict_to_dict(update_probes), 'removed': _ordered_dict_to_dict(remove_probes) } ret.update({ 'changes': changes }) if __opts__['test'] is True: ret.update({ 'comment': 'Testing mode: configuration was not changed!', 'result': None }) return ret config_change_expected = False # to check if something changed and a commit would be needed if add_probes: added = _set_rpm_probes(add_probes) if added.get('result'): config_change_expected = True else: result = False comment += 'Cannot define new probes: {reason}\n'.format( reason=added.get('comment') ) if update_probes: updated = _set_rpm_probes(update_probes) if updated.get('result'): config_change_expected = True else: result = False comment += 'Cannot update probes: {reason}\n'.format( reason=updated.get('comment') ) if remove_probes: removed = _delete_rpm_probes(remove_probes) if removed.get('result'): config_change_expected = True else: result = False comment += 'Cannot remove probes! {reason}\n'.format( reason=removed.get('comment') ) # <---- Call set_probes and delete_probes as needed ---------------------------------------------------------------- # ----- Try to save changes ---------------------------------------------------------------------------------------> if config_change_expected: # if any changes expected, try to commit result, comment = __salt__['net.config_control']() # <---- Try to save changes ---------------------------------------------------------------------------------------- # ----- Try to schedule the probes --------------------------------------------------------------------------------> add_scheduled = _schedule_probes(add_probes) if add_scheduled.get('result'): # if able to load the template to schedule the probes, try to commit the scheduling data # (yes, a second commit is needed) # on devices such as Juniper, RPM probes do not need to be scheduled # therefore the template is empty and won't try to commit empty changes result, comment = __salt__['net.config_control']() if config_change_expected: if result and comment == '': # if any changes and was able to apply them comment = 'Probes updated successfully!' ret.update({ 'result': result, 'comment': comment }) return ret
saltstack/salt
salt/states/probes.py
managed
python
def managed(name, probes, defaults=None): ''' Ensure the networks device is configured as specified in the state SLS file. Probes not specified will be removed, while probes not confiured as expected will trigger config updates. :param probes: Defines the probes as expected to be configured on the device. In order to ease the configuration and avoid repeating the same parameters for each probe, the next parameter (defaults) can be used, providing common characteristics. :param defaults: Specifies common parameters for the probes. SLS Example: .. code-block:: yaml rpmprobes: probes.managed: - probes: probe_name1: probe1_test1: source: 192.168.0.2 target: 192.168.0.1 probe1_test2: target: 172.17.17.1 probe1_test3: target: 8.8.8.8 probe_type: http-ping probe_name2: probe2_test1: test_interval: 100 - defaults: target: 10.10.10.10 probe_count: 15 test_interval: 3 probe_type: icmp-ping In the probes configuration, the only mandatory attribute is *target* (specified either in probes configuration, either in the defaults dictionary). All the other parameters will use the operating system defaults, if not provided: - ``source`` - Specifies the source IP Address to be used during the tests. If not specified will use the IP Address of the logical interface loopback0. - ``target`` - Destination IP Address. - ``probe_count`` - Total number of probes per test (1..15). System defaults: 1 on both JunOS & Cisco. - ``probe_interval`` - Delay between tests (0..86400 seconds). System defaults: 3 on JunOS, 5 on Cisco. - ``probe_type`` - Probe request type. Available options: - icmp-ping - tcp-ping - udp-ping Using the example configuration above, after running the state, on the device will be configured 4 probes, with the following properties: .. code-block:: yaml probe_name1: probe1_test1: source: 192.168.0.2 target: 192.168.0.1 probe_count: 15 test_interval: 3 probe_type: icmp-ping probe1_test2: target: 172.17.17.1 probe_count: 15 test_interval: 3 probe_type: icmp-ping probe1_test3: target: 8.8.8.8 probe_count: 15 test_interval: 3 probe_type: http-ping probe_name2: probe2_test1: target: 10.10.10.10 probe_count: 15 test_interval: 3 probe_type: icmp-ping ''' ret = _default_ret(name) result = True comment = '' rpm_probes_config = _retrieve_rpm_probes() # retrieves the RPM config from the device if not rpm_probes_config.get('result'): ret.update({ 'result': False, 'comment': 'Cannot retrieve configurtion of the probes from the device: {reason}'.format( reason=rpm_probes_config.get('comment') ) }) return ret # build expect probes config dictionary # using default values configured_probes = rpm_probes_config.get('out', {}) if not isinstance(defaults, dict): defaults = {} expected_probes = _expand_probes(probes, defaults) _clean_probes(configured_probes) # let's remove the unnecessary data from the configured probes _clean_probes(expected_probes) # also from the expected data # ----- Compare expected config with the existing config ----------------------------------------------------------> diff = _compare_probes(configured_probes, expected_probes) # compute the diff # <---- Compare expected config with the existing config ----------------------------------------------------------- # ----- Call set_probes and delete_probes as needed ---------------------------------------------------------------> add_probes = diff.get('add') update_probes = diff.get('update') remove_probes = diff.get('remove') changes = { 'added': _ordered_dict_to_dict(add_probes), 'updated': _ordered_dict_to_dict(update_probes), 'removed': _ordered_dict_to_dict(remove_probes) } ret.update({ 'changes': changes }) if __opts__['test'] is True: ret.update({ 'comment': 'Testing mode: configuration was not changed!', 'result': None }) return ret config_change_expected = False # to check if something changed and a commit would be needed if add_probes: added = _set_rpm_probes(add_probes) if added.get('result'): config_change_expected = True else: result = False comment += 'Cannot define new probes: {reason}\n'.format( reason=added.get('comment') ) if update_probes: updated = _set_rpm_probes(update_probes) if updated.get('result'): config_change_expected = True else: result = False comment += 'Cannot update probes: {reason}\n'.format( reason=updated.get('comment') ) if remove_probes: removed = _delete_rpm_probes(remove_probes) if removed.get('result'): config_change_expected = True else: result = False comment += 'Cannot remove probes! {reason}\n'.format( reason=removed.get('comment') ) # <---- Call set_probes and delete_probes as needed ---------------------------------------------------------------- # ----- Try to save changes ---------------------------------------------------------------------------------------> if config_change_expected: # if any changes expected, try to commit result, comment = __salt__['net.config_control']() # <---- Try to save changes ---------------------------------------------------------------------------------------- # ----- Try to schedule the probes --------------------------------------------------------------------------------> add_scheduled = _schedule_probes(add_probes) if add_scheduled.get('result'): # if able to load the template to schedule the probes, try to commit the scheduling data # (yes, a second commit is needed) # on devices such as Juniper, RPM probes do not need to be scheduled # therefore the template is empty and won't try to commit empty changes result, comment = __salt__['net.config_control']() if config_change_expected: if result and comment == '': # if any changes and was able to apply them comment = 'Probes updated successfully!' ret.update({ 'result': result, 'comment': comment }) return ret
Ensure the networks device is configured as specified in the state SLS file. Probes not specified will be removed, while probes not confiured as expected will trigger config updates. :param probes: Defines the probes as expected to be configured on the device. In order to ease the configuration and avoid repeating the same parameters for each probe, the next parameter (defaults) can be used, providing common characteristics. :param defaults: Specifies common parameters for the probes. SLS Example: .. code-block:: yaml rpmprobes: probes.managed: - probes: probe_name1: probe1_test1: source: 192.168.0.2 target: 192.168.0.1 probe1_test2: target: 172.17.17.1 probe1_test3: target: 8.8.8.8 probe_type: http-ping probe_name2: probe2_test1: test_interval: 100 - defaults: target: 10.10.10.10 probe_count: 15 test_interval: 3 probe_type: icmp-ping In the probes configuration, the only mandatory attribute is *target* (specified either in probes configuration, either in the defaults dictionary). All the other parameters will use the operating system defaults, if not provided: - ``source`` - Specifies the source IP Address to be used during the tests. If not specified will use the IP Address of the logical interface loopback0. - ``target`` - Destination IP Address. - ``probe_count`` - Total number of probes per test (1..15). System defaults: 1 on both JunOS & Cisco. - ``probe_interval`` - Delay between tests (0..86400 seconds). System defaults: 3 on JunOS, 5 on Cisco. - ``probe_type`` - Probe request type. Available options: - icmp-ping - tcp-ping - udp-ping Using the example configuration above, after running the state, on the device will be configured 4 probes, with the following properties: .. code-block:: yaml probe_name1: probe1_test1: source: 192.168.0.2 target: 192.168.0.1 probe_count: 15 test_interval: 3 probe_type: icmp-ping probe1_test2: target: 172.17.17.1 probe_count: 15 test_interval: 3 probe_type: icmp-ping probe1_test3: target: 8.8.8.8 probe_count: 15 test_interval: 3 probe_type: http-ping probe_name2: probe2_test1: target: 10.10.10.10 probe_count: 15 test_interval: 3 probe_type: icmp-ping
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/probes.py#L252-L454
[ "def _default_ret(name):\n\n '''\n Returns a default structure of the dictionary to be returned as output of the state functions.\n '''\n\n return {\n 'name': name,\n 'result': False,\n 'changes': {},\n 'comment': ''\n }\n", "def _ordered_dict_to_dict(probes):\n\n '''Mandatory to be dict type in order to be used in the NAPALM Jinja template.'''\n\n return loads(dumps(probes))\n", "def _retrieve_rpm_probes():\n\n '''\n Will retrieve the probes from the network device using salt module \"probes\" throught NAPALM proxy.\n '''\n\n return __salt__['probes.config']()\n", "def _expand_probes(probes, defaults):\n\n '''\n Updates the probes dictionary with different levels of default values.\n '''\n\n expected_probes = {}\n\n for probe_name, probe_test in six.iteritems(probes):\n if probe_name not in expected_probes.keys():\n expected_probes[probe_name] = {}\n probe_defaults = probe_test.pop('defaults', {})\n for test_name, test_details in six.iteritems(probe_test):\n test_defaults = test_details.pop('defaults', {})\n expected_test_details = deepcopy(defaults) # copy first the general defaults\n expected_test_details.update(probe_defaults) # update with more specific defaults if any\n expected_test_details.update(test_defaults) # update with the most specific defaults if possible\n expected_test_details.update(test_details) # update with the actual config of the test\n if test_name not in expected_probes[probe_name].keys():\n expected_probes[probe_name][test_name] = expected_test_details\n\n return expected_probes\n", "def _clean_probes(probes):\n\n '''\n Will remove empty and useless values from the probes dictionary.\n '''\n\n probes = _ordered_dict_to_dict(probes) # make sure we are working only with dict-type\n probes_copy = deepcopy(probes)\n for probe_name, probe_tests in six.iteritems(probes_copy):\n if not probe_tests:\n probes.pop(probe_name)\n continue\n for test_name, test_params in six.iteritems(probe_tests):\n if not test_params:\n probes[probe_name].pop(test_name)\n if not probes.get(probe_name):\n probes.pop(probe_name)\n\n return True\n", "def _compare_probes(configured_probes, expected_probes):\n\n '''\n Compares configured probes on the device with the expected configuration and returns the differences.\n '''\n\n new_probes = {}\n update_probes = {}\n remove_probes = {}\n\n # noth configured => configure with expected probes\n if not configured_probes:\n return {\n 'add': expected_probes\n }\n\n # noting expected => remove everything\n if not expected_probes:\n return {\n 'remove': configured_probes\n }\n\n configured_probes_keys_set = set(configured_probes.keys())\n expected_probes_keys_set = set(expected_probes.keys())\n new_probes_keys_set = expected_probes_keys_set - configured_probes_keys_set\n remove_probes_keys_set = configured_probes_keys_set - expected_probes_keys_set\n\n # new probes\n for probe_name in new_probes_keys_set:\n new_probes[probe_name] = expected_probes.pop(probe_name)\n\n # old probes, to be removed\n for probe_name in remove_probes_keys_set:\n remove_probes[probe_name] = configured_probes.pop(probe_name)\n\n # common probes\n for probe_name, probe_tests in six.iteritems(expected_probes):\n configured_probe_tests = configured_probes.get(probe_name, {})\n configured_tests_keys_set = set(configured_probe_tests.keys())\n expected_tests_keys_set = set(probe_tests.keys())\n new_tests_keys_set = expected_tests_keys_set - configured_tests_keys_set\n remove_tests_keys_set = configured_tests_keys_set - expected_tests_keys_set\n\n # new tests for common probes\n for test_name in new_tests_keys_set:\n if probe_name not in new_probes.keys():\n new_probes[probe_name] = {}\n new_probes[probe_name].update({\n test_name: probe_tests.pop(test_name)\n })\n # old tests for common probes\n for test_name in remove_tests_keys_set:\n if probe_name not in remove_probes.keys():\n remove_probes[probe_name] = {}\n remove_probes[probe_name].update({\n test_name: configured_probe_tests.pop(test_name)\n })\n # common tests for common probes\n for test_name, test_params in six.iteritems(probe_tests):\n configured_test_params = configured_probe_tests.get(test_name, {})\n # if test params are different, probe goes to update probes dict!\n if test_params != configured_test_params:\n if probe_name not in update_probes.keys():\n update_probes[probe_name] = {}\n update_probes[probe_name].update({\n test_name: test_params\n })\n\n return {\n 'add': new_probes,\n 'update': update_probes,\n 'remove': remove_probes\n }\n", "def _set_rpm_probes(probes):\n\n '''\n Calls the Salt module \"probes\" to configure the probes on the device.\n '''\n\n return __salt__['probes.set_probes'](\n _ordered_dict_to_dict(probes), # make sure this does not contain ordered dicts\n commit=False\n )\n", "def _schedule_probes(probes):\n\n '''\n Calls the Salt module \"probes\" to schedule the configured probes on the device.\n '''\n\n return __salt__['probes.schedule_probes'](\n _ordered_dict_to_dict(probes), # make sure this does not contain ordered dicts\n commit=False\n )\n", "def _delete_rpm_probes(probes):\n\n '''\n Calls the Salt module \"probes\" to delete probes from the device.\n '''\n\n return __salt__['probes.delete_probes'](\n _ordered_dict_to_dict(probes), # not mandatory, but let's make sure we catch all cases\n commit=False\n )\n" ]
# -*- coding: utf-8 -*- ''' Network Probes =============== Configure RPM (JunOS)/SLA (Cisco) probes on the device via NAPALM proxy. :codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com> :maturity: new :depends: napalm :platform: unix Dependencies ------------ - :mod:`napalm probes management module <salt.modules.napalm_probes>` .. versionadded: 2016.11.0 ''' from __future__ import absolute_import # python std lib import logging log = logging.getLogger(__name__) from copy import deepcopy # salt modules from salt.utils.json import loads, dumps from salt.ext import six # import NAPALM utils import salt.utils.napalm # ---------------------------------------------------------------------------------------------------------------------- # state properties # ---------------------------------------------------------------------------------------------------------------------- __virtualname__ = 'probes' # ---------------------------------------------------------------------------------------------------------------------- # global variables # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # property functions # ---------------------------------------------------------------------------------------------------------------------- def __virtual__(): ''' NAPALM library must be installed for this module to work and run in a (proxy) minion. ''' return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__) # ---------------------------------------------------------------------------------------------------------------------- # helper functions -- will not be exported # ---------------------------------------------------------------------------------------------------------------------- def _default_ret(name): ''' Returns a default structure of the dictionary to be returned as output of the state functions. ''' return { 'name': name, 'result': False, 'changes': {}, 'comment': '' } def _retrieve_rpm_probes(): ''' Will retrieve the probes from the network device using salt module "probes" throught NAPALM proxy. ''' return __salt__['probes.config']() def _expand_probes(probes, defaults): ''' Updates the probes dictionary with different levels of default values. ''' expected_probes = {} for probe_name, probe_test in six.iteritems(probes): if probe_name not in expected_probes.keys(): expected_probes[probe_name] = {} probe_defaults = probe_test.pop('defaults', {}) for test_name, test_details in six.iteritems(probe_test): test_defaults = test_details.pop('defaults', {}) expected_test_details = deepcopy(defaults) # copy first the general defaults expected_test_details.update(probe_defaults) # update with more specific defaults if any expected_test_details.update(test_defaults) # update with the most specific defaults if possible expected_test_details.update(test_details) # update with the actual config of the test if test_name not in expected_probes[probe_name].keys(): expected_probes[probe_name][test_name] = expected_test_details return expected_probes def _clean_probes(probes): ''' Will remove empty and useless values from the probes dictionary. ''' probes = _ordered_dict_to_dict(probes) # make sure we are working only with dict-type probes_copy = deepcopy(probes) for probe_name, probe_tests in six.iteritems(probes_copy): if not probe_tests: probes.pop(probe_name) continue for test_name, test_params in six.iteritems(probe_tests): if not test_params: probes[probe_name].pop(test_name) if not probes.get(probe_name): probes.pop(probe_name) return True def _compare_probes(configured_probes, expected_probes): ''' Compares configured probes on the device with the expected configuration and returns the differences. ''' new_probes = {} update_probes = {} remove_probes = {} # noth configured => configure with expected probes if not configured_probes: return { 'add': expected_probes } # noting expected => remove everything if not expected_probes: return { 'remove': configured_probes } configured_probes_keys_set = set(configured_probes.keys()) expected_probes_keys_set = set(expected_probes.keys()) new_probes_keys_set = expected_probes_keys_set - configured_probes_keys_set remove_probes_keys_set = configured_probes_keys_set - expected_probes_keys_set # new probes for probe_name in new_probes_keys_set: new_probes[probe_name] = expected_probes.pop(probe_name) # old probes, to be removed for probe_name in remove_probes_keys_set: remove_probes[probe_name] = configured_probes.pop(probe_name) # common probes for probe_name, probe_tests in six.iteritems(expected_probes): configured_probe_tests = configured_probes.get(probe_name, {}) configured_tests_keys_set = set(configured_probe_tests.keys()) expected_tests_keys_set = set(probe_tests.keys()) new_tests_keys_set = expected_tests_keys_set - configured_tests_keys_set remove_tests_keys_set = configured_tests_keys_set - expected_tests_keys_set # new tests for common probes for test_name in new_tests_keys_set: if probe_name not in new_probes.keys(): new_probes[probe_name] = {} new_probes[probe_name].update({ test_name: probe_tests.pop(test_name) }) # old tests for common probes for test_name in remove_tests_keys_set: if probe_name not in remove_probes.keys(): remove_probes[probe_name] = {} remove_probes[probe_name].update({ test_name: configured_probe_tests.pop(test_name) }) # common tests for common probes for test_name, test_params in six.iteritems(probe_tests): configured_test_params = configured_probe_tests.get(test_name, {}) # if test params are different, probe goes to update probes dict! if test_params != configured_test_params: if probe_name not in update_probes.keys(): update_probes[probe_name] = {} update_probes[probe_name].update({ test_name: test_params }) return { 'add': new_probes, 'update': update_probes, 'remove': remove_probes } def _ordered_dict_to_dict(probes): '''Mandatory to be dict type in order to be used in the NAPALM Jinja template.''' return loads(dumps(probes)) def _set_rpm_probes(probes): ''' Calls the Salt module "probes" to configure the probes on the device. ''' return __salt__['probes.set_probes']( _ordered_dict_to_dict(probes), # make sure this does not contain ordered dicts commit=False ) def _schedule_probes(probes): ''' Calls the Salt module "probes" to schedule the configured probes on the device. ''' return __salt__['probes.schedule_probes']( _ordered_dict_to_dict(probes), # make sure this does not contain ordered dicts commit=False ) def _delete_rpm_probes(probes): ''' Calls the Salt module "probes" to delete probes from the device. ''' return __salt__['probes.delete_probes']( _ordered_dict_to_dict(probes), # not mandatory, but let's make sure we catch all cases commit=False ) # ---------------------------------------------------------------------------------------------------------------------- # callable functions # ----------------------------------------------------------------------------------------------------------------------
saltstack/salt
salt/returners/smtp_return.py
returner
python
def returner(ret): ''' Send an email with the data ''' _options = _get_options(ret) from_addr = _options.get('from') to_addrs = _options.get('to').split(',') host = _options.get('host') port = _options.get('port') user = _options.get('username') passwd = _options.get('password') subject = _options.get('subject') or 'Email from Salt' gpgowner = _options.get('gpgowner') fields = _options.get('fields').split(',') if 'fields' in _options else [] smtp_tls = _options.get('tls') renderer = _options.get('renderer') or 'jinja' rend = salt.loader.render(__opts__, {}) blacklist = __opts__.get('renderer_blacklist') whitelist = __opts__.get('renderer_whitelist') if not port: port = 25 log.debug('SMTP port has been set to %s', port) for field in fields: if field in ret: subject += ' {0}'.format(ret[field]) subject = compile_template(':string:', rend, renderer, blacklist, whitelist, input_data=subject, **ret) if isinstance(subject, six.moves.StringIO): subject = subject.read() log.debug("smtp_return: Subject is '%s'", subject) template = _options.get('template') if template: content = compile_template(template, rend, renderer, blacklist, whitelist, **ret) else: template = ('id: {{id}}\r\n' 'function: {{fun}}\r\n' 'function args: {{fun_args}}\r\n' 'jid: {{jid}}\r\n' 'return: {{return}}\r\n') content = compile_template(':string:', rend, renderer, blacklist, whitelist, input_data=template, **ret) if gpgowner: if HAS_GNUPG: gpg = gnupg.GPG(gnupghome=os.path.expanduser('~{0}/.gnupg'.format(gpgowner)), options=['--trust-model always']) encrypted_data = gpg.encrypt(content, to_addrs) if encrypted_data.ok: log.debug('smtp_return: Encryption successful') content = six.text_type(encrypted_data) else: log.error('smtp_return: Encryption failed, only an error message will be sent') content = 'Encryption failed, the return data was not sent.\r\n\r\n{0}\r\n{1}'.format( encrypted_data.status, encrypted_data.stderr) else: log.error("gnupg python module is required in order to user gpgowner in smtp returner ; ignoring gpgowner configuration for now") if isinstance(content, six.moves.StringIO): content = content.read() message = ('From: {0}\r\n' 'To: {1}\r\n' 'Date: {2}\r\n' 'Subject: {3}\r\n' '\r\n' '{4}').format(from_addr, ', '.join(to_addrs), formatdate(localtime=True), subject, content) log.debug('smtp_return: Connecting to the server...') server = smtplib.SMTP(host, int(port)) if smtp_tls is True: server.starttls() log.debug('smtp_return: TLS enabled') if user and passwd: server.login(user, passwd) log.debug('smtp_return: Authenticated') # enable logging SMTP session after the login credentials were passed server.set_debuglevel(1) server.sendmail(from_addr, to_addrs, message) log.debug('smtp_return: Message sent.') server.quit()
Send an email with the data
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/smtp_return.py#L163-L260
[ "def compile_template(template,\n renderers,\n default,\n blacklist,\n whitelist,\n saltenv='base',\n sls='',\n input_data='',\n **kwargs):\n '''\n Take the path to a template and return the high data structure\n derived from the template.\n\n Helpers:\n\n :param mask_value:\n Mask value for debugging purposes (prevent sensitive information etc)\n example: \"mask_value=\"pass*\". All \"passwd\", \"password\", \"pass\" will\n be masked (as text).\n '''\n\n # if any error occurs, we return an empty dictionary\n ret = {}\n\n log.debug('compile template: %s', template)\n\n if 'env' in kwargs:\n # \"env\" is not supported; Use \"saltenv\".\n kwargs.pop('env')\n\n if template != ':string:':\n # Template was specified incorrectly\n if not isinstance(template, six.string_types):\n log.error('Template was specified incorrectly: %s', template)\n return ret\n # Template does not exist\n if not os.path.isfile(template):\n log.error('Template does not exist: %s', template)\n return ret\n # Template is an empty file\n if salt.utils.files.is_empty(template):\n log.debug('Template is an empty file: %s', template)\n return ret\n\n with codecs.open(template, encoding=SLS_ENCODING) as ifile:\n # data input to the first render function in the pipe\n input_data = ifile.read()\n if not input_data.strip():\n # Template is nothing but whitespace\n log.error('Template is nothing but whitespace: %s', template)\n return ret\n\n # Get the list of render funcs in the render pipe line.\n render_pipe = template_shebang(template, renderers, default, blacklist, whitelist, input_data)\n\n windows_newline = '\\r\\n' in input_data\n\n input_data = StringIO(input_data)\n for render, argline in render_pipe:\n if salt.utils.stringio.is_readable(input_data):\n input_data.seek(0) # pylint: disable=no-member\n render_kwargs = dict(renderers=renderers, tmplpath=template)\n render_kwargs.update(kwargs)\n if argline:\n render_kwargs['argline'] = argline\n start = time.time()\n ret = render(input_data, saltenv, sls, **render_kwargs)\n log.profile(\n 'Time (in seconds) to render \\'%s\\' using \\'%s\\' renderer: %s',\n template,\n render.__module__.split('.')[-1],\n time.time() - start\n )\n if ret is None:\n # The file is empty or is being written elsewhere\n time.sleep(0.01)\n ret = render(input_data, saltenv, sls, **render_kwargs)\n input_data = ret\n if log.isEnabledFor(logging.GARBAGE): # pylint: disable=no-member\n # If ret is not a StringIO (which means it was rendered using\n # yaml, mako, or another engine which renders to a data\n # structure) we don't want to log this.\n if salt.utils.stringio.is_readable(ret):\n log.debug('Rendered data from file: %s:\\n%s', template,\n salt.utils.sanitizers.mask_args_value(salt.utils.data.decode(ret.read()),\n kwargs.get('mask_value'))) # pylint: disable=no-member\n ret.seek(0) # pylint: disable=no-member\n\n # Preserve newlines from original template\n if windows_newline:\n if salt.utils.stringio.is_readable(ret):\n is_stringio = True\n contents = ret.read()\n else:\n is_stringio = False\n contents = ret\n\n if isinstance(contents, six.string_types):\n if '\\r\\n' not in contents:\n contents = contents.replace('\\n', '\\r\\n')\n ret = StringIO(contents) if is_stringio else contents\n else:\n if is_stringio:\n ret.seek(0)\n return ret\n", "def _get_options(ret=None):\n '''\n Get the SMTP options from salt.\n '''\n attrs = {'from': 'from',\n 'to': 'to',\n 'host': 'host',\n 'port': 'port',\n 'username': 'username',\n 'password': 'password',\n 'subject': 'subject',\n 'gpgowner': 'gpgowner',\n 'fields': 'fields',\n 'tls': 'tls',\n 'renderer': 'renderer',\n 'template': 'template'}\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n return _options\n" ]
# -*- coding: utf-8 -*- ''' Return salt data via email The following fields can be set in the minion conf file. Fields are optional unless noted otherwise. * ``from`` (required) The name/address of the email sender. * ``to`` (required) The names/addresses of the email recipients; comma-delimited. For example: ``you@example.com,someoneelse@example.com``. * ``host`` (required) The SMTP server hostname or address. * ``port`` The SMTP server port; defaults to ``25``. * ``username`` The username used to authenticate to the server. If specified a password is also required. It is recommended but not required to also use TLS with this option. * ``password`` The password used to authenticate to the server. * ``tls`` Whether to secure the connection using TLS; defaults to ``False`` * ``subject`` The email subject line. * ``fields`` Which fields from the returned data to include in the subject line of the email; comma-delimited. For example: ``id,fun``. Please note, *the subject line is not encrypted*. * ``gpgowner`` A user's :file:`~/.gpg` directory. This must contain a gpg public key matching the address the mail is sent to. If left unset, no encryption will be used. Requires :program:`python-gnupg` to be installed. * ``template`` The path to a file to be used as a template for the email body. * ``renderer`` A Salt renderer, or render-pipe, to use to render the email template. Default ``jinja``. Below is an example of the above settings in a Salt Minion configuration file: .. code-block:: yaml smtp.from: me@example.net smtp.to: you@example.com smtp.host: localhost smtp.port: 1025 Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location. For example: .. code-block:: yaml alternative.smtp.username: saltdev alternative.smtp.password: saltdev alternative.smtp.tls: True To use the SMTP returner, append '--return smtp' to the ``salt`` command. .. code-block:: bash salt '*' test.ping --return smtp To use the alternative configuration, append '--return_config alternative' to the ``salt`` command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return smtp --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the ``salt`` command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return smtp --return_kwargs '{"to": "user@domain.com"}' An easy way to test the SMTP returner is to use the development SMTP server built into Python. The command below will start a single-threaded SMTP server that prints any email it receives to the console. .. code-block:: python python -m smtpd -n -c DebuggingServer localhost:1025 .. versionadded:: 2016.11.0 It is possible to send emails with selected Salt events by configuring ``event_return`` option for Salt Master. For example: .. code-block:: yaml event_return: smtp event_return_whitelist: - salt/key smtp.from: me@example.net smtp.to: you@example.com smtp.host: localhost smtp.subject: 'Salt Master {{act}}ed key from Minion ID: {{id}}' smtp.template: /srv/salt/templates/email.j2 Also you need to create additional file ``/srv/salt/templates/email.j2`` with email body template: .. code-block:: yaml act: {{act}} id: {{id}} result: {{result}} This configuration enables Salt Master to send an email when accepting or rejecting minions keys. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import logging import smtplib from email.utils import formatdate # Import Salt libs from salt.ext import six import salt.utils.jid import salt.returners import salt.loader from salt.template import compile_template try: import gnupg HAS_GNUPG = True except ImportError: HAS_GNUPG = False log = logging.getLogger(__name__) __virtualname__ = 'smtp' def __virtual__(): return __virtualname__ def _get_options(ret=None): ''' Get the SMTP options from salt. ''' attrs = {'from': 'from', 'to': 'to', 'host': 'host', 'port': 'port', 'username': 'username', 'password': 'password', 'subject': 'subject', 'gpgowner': 'gpgowner', 'fields': 'fields', 'tls': 'tls', 'renderer': 'renderer', 'template': 'template'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) return _options def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__) def event_return(events): ''' Return event data via SMTP ''' for event in events: ret = event.get('data', False) if ret: returner(ret)
saltstack/salt
salt/returners/smtp_return.py
event_return
python
def event_return(events): ''' Return event data via SMTP ''' for event in events: ret = event.get('data', False) if ret: returner(ret)
Return event data via SMTP
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/smtp_return.py#L270-L279
[ "def returner(ret):\n '''\n Send an email with the data\n '''\n\n _options = _get_options(ret)\n from_addr = _options.get('from')\n to_addrs = _options.get('to').split(',')\n host = _options.get('host')\n port = _options.get('port')\n user = _options.get('username')\n passwd = _options.get('password')\n subject = _options.get('subject') or 'Email from Salt'\n gpgowner = _options.get('gpgowner')\n fields = _options.get('fields').split(',') if 'fields' in _options else []\n smtp_tls = _options.get('tls')\n\n renderer = _options.get('renderer') or 'jinja'\n rend = salt.loader.render(__opts__, {})\n blacklist = __opts__.get('renderer_blacklist')\n whitelist = __opts__.get('renderer_whitelist')\n\n if not port:\n port = 25\n log.debug('SMTP port has been set to %s', port)\n\n for field in fields:\n if field in ret:\n subject += ' {0}'.format(ret[field])\n subject = compile_template(':string:',\n rend,\n renderer,\n blacklist,\n whitelist,\n input_data=subject,\n **ret)\n if isinstance(subject, six.moves.StringIO):\n subject = subject.read()\n log.debug(\"smtp_return: Subject is '%s'\", subject)\n\n template = _options.get('template')\n if template:\n content = compile_template(template, rend, renderer, blacklist, whitelist, **ret)\n else:\n template = ('id: {{id}}\\r\\n'\n 'function: {{fun}}\\r\\n'\n 'function args: {{fun_args}}\\r\\n'\n 'jid: {{jid}}\\r\\n'\n 'return: {{return}}\\r\\n')\n content = compile_template(':string:',\n rend,\n renderer,\n blacklist,\n whitelist,\n input_data=template,\n **ret)\n\n if gpgowner:\n if HAS_GNUPG:\n gpg = gnupg.GPG(gnupghome=os.path.expanduser('~{0}/.gnupg'.format(gpgowner)),\n options=['--trust-model always'])\n encrypted_data = gpg.encrypt(content, to_addrs)\n if encrypted_data.ok:\n log.debug('smtp_return: Encryption successful')\n content = six.text_type(encrypted_data)\n else:\n log.error('smtp_return: Encryption failed, only an error message will be sent')\n content = 'Encryption failed, the return data was not sent.\\r\\n\\r\\n{0}\\r\\n{1}'.format(\n encrypted_data.status, encrypted_data.stderr)\n else:\n log.error(\"gnupg python module is required in order to user gpgowner in smtp returner ; ignoring gpgowner configuration for now\")\n if isinstance(content, six.moves.StringIO):\n content = content.read()\n\n message = ('From: {0}\\r\\n'\n 'To: {1}\\r\\n'\n 'Date: {2}\\r\\n'\n 'Subject: {3}\\r\\n'\n '\\r\\n'\n '{4}').format(from_addr,\n ', '.join(to_addrs),\n formatdate(localtime=True),\n subject,\n content)\n\n log.debug('smtp_return: Connecting to the server...')\n server = smtplib.SMTP(host, int(port))\n if smtp_tls is True:\n server.starttls()\n log.debug('smtp_return: TLS enabled')\n if user and passwd:\n server.login(user, passwd)\n log.debug('smtp_return: Authenticated')\n # enable logging SMTP session after the login credentials were passed\n server.set_debuglevel(1)\n server.sendmail(from_addr, to_addrs, message)\n log.debug('smtp_return: Message sent.')\n server.quit()\n" ]
# -*- coding: utf-8 -*- ''' Return salt data via email The following fields can be set in the minion conf file. Fields are optional unless noted otherwise. * ``from`` (required) The name/address of the email sender. * ``to`` (required) The names/addresses of the email recipients; comma-delimited. For example: ``you@example.com,someoneelse@example.com``. * ``host`` (required) The SMTP server hostname or address. * ``port`` The SMTP server port; defaults to ``25``. * ``username`` The username used to authenticate to the server. If specified a password is also required. It is recommended but not required to also use TLS with this option. * ``password`` The password used to authenticate to the server. * ``tls`` Whether to secure the connection using TLS; defaults to ``False`` * ``subject`` The email subject line. * ``fields`` Which fields from the returned data to include in the subject line of the email; comma-delimited. For example: ``id,fun``. Please note, *the subject line is not encrypted*. * ``gpgowner`` A user's :file:`~/.gpg` directory. This must contain a gpg public key matching the address the mail is sent to. If left unset, no encryption will be used. Requires :program:`python-gnupg` to be installed. * ``template`` The path to a file to be used as a template for the email body. * ``renderer`` A Salt renderer, or render-pipe, to use to render the email template. Default ``jinja``. Below is an example of the above settings in a Salt Minion configuration file: .. code-block:: yaml smtp.from: me@example.net smtp.to: you@example.com smtp.host: localhost smtp.port: 1025 Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location. For example: .. code-block:: yaml alternative.smtp.username: saltdev alternative.smtp.password: saltdev alternative.smtp.tls: True To use the SMTP returner, append '--return smtp' to the ``salt`` command. .. code-block:: bash salt '*' test.ping --return smtp To use the alternative configuration, append '--return_config alternative' to the ``salt`` command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return smtp --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the ``salt`` command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return smtp --return_kwargs '{"to": "user@domain.com"}' An easy way to test the SMTP returner is to use the development SMTP server built into Python. The command below will start a single-threaded SMTP server that prints any email it receives to the console. .. code-block:: python python -m smtpd -n -c DebuggingServer localhost:1025 .. versionadded:: 2016.11.0 It is possible to send emails with selected Salt events by configuring ``event_return`` option for Salt Master. For example: .. code-block:: yaml event_return: smtp event_return_whitelist: - salt/key smtp.from: me@example.net smtp.to: you@example.com smtp.host: localhost smtp.subject: 'Salt Master {{act}}ed key from Minion ID: {{id}}' smtp.template: /srv/salt/templates/email.j2 Also you need to create additional file ``/srv/salt/templates/email.j2`` with email body template: .. code-block:: yaml act: {{act}} id: {{id}} result: {{result}} This configuration enables Salt Master to send an email when accepting or rejecting minions keys. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import logging import smtplib from email.utils import formatdate # Import Salt libs from salt.ext import six import salt.utils.jid import salt.returners import salt.loader from salt.template import compile_template try: import gnupg HAS_GNUPG = True except ImportError: HAS_GNUPG = False log = logging.getLogger(__name__) __virtualname__ = 'smtp' def __virtual__(): return __virtualname__ def _get_options(ret=None): ''' Get the SMTP options from salt. ''' attrs = {'from': 'from', 'to': 'to', 'host': 'host', 'port': 'port', 'username': 'username', 'password': 'password', 'subject': 'subject', 'gpgowner': 'gpgowner', 'fields': 'fields', 'tls': 'tls', 'renderer': 'renderer', 'template': 'template'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) return _options def returner(ret): ''' Send an email with the data ''' _options = _get_options(ret) from_addr = _options.get('from') to_addrs = _options.get('to').split(',') host = _options.get('host') port = _options.get('port') user = _options.get('username') passwd = _options.get('password') subject = _options.get('subject') or 'Email from Salt' gpgowner = _options.get('gpgowner') fields = _options.get('fields').split(',') if 'fields' in _options else [] smtp_tls = _options.get('tls') renderer = _options.get('renderer') or 'jinja' rend = salt.loader.render(__opts__, {}) blacklist = __opts__.get('renderer_blacklist') whitelist = __opts__.get('renderer_whitelist') if not port: port = 25 log.debug('SMTP port has been set to %s', port) for field in fields: if field in ret: subject += ' {0}'.format(ret[field]) subject = compile_template(':string:', rend, renderer, blacklist, whitelist, input_data=subject, **ret) if isinstance(subject, six.moves.StringIO): subject = subject.read() log.debug("smtp_return: Subject is '%s'", subject) template = _options.get('template') if template: content = compile_template(template, rend, renderer, blacklist, whitelist, **ret) else: template = ('id: {{id}}\r\n' 'function: {{fun}}\r\n' 'function args: {{fun_args}}\r\n' 'jid: {{jid}}\r\n' 'return: {{return}}\r\n') content = compile_template(':string:', rend, renderer, blacklist, whitelist, input_data=template, **ret) if gpgowner: if HAS_GNUPG: gpg = gnupg.GPG(gnupghome=os.path.expanduser('~{0}/.gnupg'.format(gpgowner)), options=['--trust-model always']) encrypted_data = gpg.encrypt(content, to_addrs) if encrypted_data.ok: log.debug('smtp_return: Encryption successful') content = six.text_type(encrypted_data) else: log.error('smtp_return: Encryption failed, only an error message will be sent') content = 'Encryption failed, the return data was not sent.\r\n\r\n{0}\r\n{1}'.format( encrypted_data.status, encrypted_data.stderr) else: log.error("gnupg python module is required in order to user gpgowner in smtp returner ; ignoring gpgowner configuration for now") if isinstance(content, six.moves.StringIO): content = content.read() message = ('From: {0}\r\n' 'To: {1}\r\n' 'Date: {2}\r\n' 'Subject: {3}\r\n' '\r\n' '{4}').format(from_addr, ', '.join(to_addrs), formatdate(localtime=True), subject, content) log.debug('smtp_return: Connecting to the server...') server = smtplib.SMTP(host, int(port)) if smtp_tls is True: server.starttls() log.debug('smtp_return: TLS enabled') if user and passwd: server.login(user, passwd) log.debug('smtp_return: Authenticated') # enable logging SMTP session after the login credentials were passed server.set_debuglevel(1) server.sendmail(from_addr, to_addrs, message) log.debug('smtp_return: Message sent.') server.quit() def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
saltstack/salt
salt/modules/incron.py
_render_tab
python
def _render_tab(lst): ''' Takes a tab list structure and renders it to a list for applying it to a file ''' ret = [] for pre in lst['pre']: ret.append('{0}\n'.format(pre)) for cron in lst['crons']: ret.append('{0} {1} {2} {3}\n'.format(cron['path'], cron['mask'], cron['cmd'], TAG ) ) return ret
Takes a tab list structure and renders it to a list for applying it to a file
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/incron.py#L47-L62
null
# -*- coding: utf-8 -*- ''' Work with incron ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import os # Import salt libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.data import salt.utils.files import salt.utils.functools import salt.utils.stringutils # Set up logging log = logging.getLogger(__name__) TAG = '# Line managed by Salt, do not edit' _INCRON_SYSTEM_TAB = '/etc/incron.d/' _MASK_TYPES = [ 'IN_ACCESS', 'IN_ATTRIB', 'IN_CLOSE_WRITE', 'IN_CLOSE_NOWRITE', 'IN_CREATE', 'IN_DELETE', 'IN_DELETE_SELF', 'IN_MODIFY', 'IN_MOVE_SELF', 'IN_MOVED_FROM', 'IN_MOVED_TO', 'IN_OPEN', 'IN_ALL_EVENTS', 'IN_MOVE', 'IN_CLOSE', 'IN_DONT_FOLLOW', 'IN_ONESHOT', 'IN_ONLYDIR', 'IN_NO_LOOP' ] def _needs_change(old, new): if old != new: if new == 'random': # Allow switch from '*' or not present to 'random' if old == '*': return True elif new is not None: return True return False def _get_incron_cmdstr(path): ''' Returns a format string, to be used to build an incrontab command. ''' return 'incrontab {0}'.format(path) def write_incron_file(user, path): ''' Writes the contents of a file to a user's incrontab CLI Example: .. code-block:: bash salt '*' incron.write_incron_file root /tmp/new_incron ''' return __salt__['cmd.retcode'](_get_incron_cmdstr(path), runas=user, python_shell=False) == 0 def write_incron_file_verbose(user, path): ''' Writes the contents of a file to a user's incrontab and return error message on error CLI Example: .. code-block:: bash salt '*' incron.write_incron_file_verbose root /tmp/new_incron ''' return __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False) def _write_incron_lines(user, lines): ''' Takes a list of lines to be committed to a user's incrontab and writes it ''' if user == 'system': ret = {} ret['retcode'] = _write_file(_INCRON_SYSTEM_TAB, 'salt', ''.join(lines)) return ret else: path = salt.utils.files.mkstemp() with salt.utils.files.fopen(path, 'wb') as fp_: fp_.writelines(salt.utils.data.encode(lines)) if __grains__['os_family'] == 'Solaris' and user != "root": __salt__['cmd.run']('chown {0} {1}'.format(user, path), python_shell=False) ret = __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False) os.remove(path) return ret def _write_file(folder, filename, data): ''' Writes a file to disk ''' path = os.path.join(folder, filename) if not os.path.exists(folder): msg = '{0} cannot be written. {1} does not exist'.format(filename, folder) log.error(msg) raise AttributeError(six.text_type(msg)) with salt.utils.files.fopen(path, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(data)) return 0 def _read_file(folder, filename): ''' Reads and returns the contents of a file ''' path = os.path.join(folder, filename) try: with salt.utils.files.fopen(path, 'rb') as contents: return salt.utils.data.decode(contents.readlines()) except (OSError, IOError): return '' def raw_system_incron(): ''' Return the contents of the system wide incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_system_incron ''' _contents = _read_file(_INCRON_SYSTEM_TAB, 'salt') log.debug('incron read_file contents: %s', _contents) return ''.join(_contents) def raw_incron(user): ''' Return the contents of the user's incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_incron root ''' if __grains__['os_family'] == 'Solaris': cmd = 'incrontab -l {0}'.format(user) else: cmd = 'incrontab -l -u {0}'.format(user) return __salt__['cmd.run_stdout'](cmd, rstrip=False, runas=user, python_shell=False) def list_tab(user): ''' Return the contents of the specified user's incrontab CLI Example: .. code-block:: bash salt '*' incron.list_tab root ''' if user == 'system': data = raw_system_incron() else: data = raw_incron(user) log.debug('incron user data %s', data) ret = {'crons': [], 'pre': [] } flag = False comment = None tag = '# Line managed by Salt, do not edit' for line in data.splitlines(): if line.endswith(tag): if len(line.split()) > 3: # Appears to be a standard incron line comps = line.split() path = comps[0] mask = comps[1] (cmd, comment) = ' '.join(comps[2:]).split(' # ') dat = {'path': path, 'mask': mask, 'cmd': cmd, 'comment': comment} ret['crons'].append(dat) comment = None else: ret['pre'].append(line) return ret # For consistency's sake ls = salt.utils.functools.alias_function(list_tab, 'ls') def set_job(user, path, mask, cmd): ''' Sets an incron job up for a specified user. CLI Example: .. code-block:: bash salt '*' incron.set_job root '/root' 'IN_MODIFY' 'echo "$$ $@ $# $% $&"' ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) updated = False arg_mask = mask.split(',') arg_mask.sort() lst = list_tab(user) updated_crons = [] # Look for existing incrons that have cmd, path and at least one of the MASKS # remove and replace with the one we're passed for item, cron in enumerate(lst['crons']): if path == cron['path']: if cron['cmd'] == cmd: cron_mask = cron['mask'].split(',') cron_mask.sort() if cron_mask == arg_mask: return 'present' if any([x in cron_mask for x in arg_mask]): updated = True else: updated_crons.append(cron) else: updated_crons.append(cron) else: updated_crons.append(cron) cron = {'cmd': cmd, 'path': path, 'mask': mask} updated_crons.append(cron) lst['crons'] = updated_crons comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] if updated: return 'updated' else: return 'new' def rm_job(user, path, mask, cmd): ''' Remove a incron job for a specified user. If any of the day/time params are specified, the job will only be removed if the specified params match. CLI Example: .. code-block:: bash salt '*' incron.rm_job root /path ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) lst = list_tab(user) ret = 'absent' rm_ = None for ind in range(len(lst['crons'])): if rm_ is not None: break if path == lst['crons'][ind]['path']: if cmd == lst['crons'][ind]['cmd']: if mask == lst['crons'][ind]['mask']: rm_ = ind if rm_ is not None: lst['crons'].pop(rm_) ret = 'removed' comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] return ret rm = salt.utils.functools.alias_function(rm_job, 'rm')
saltstack/salt
salt/modules/incron.py
write_incron_file
python
def write_incron_file(user, path): ''' Writes the contents of a file to a user's incrontab CLI Example: .. code-block:: bash salt '*' incron.write_incron_file root /tmp/new_incron ''' return __salt__['cmd.retcode'](_get_incron_cmdstr(path), runas=user, python_shell=False) == 0
Writes the contents of a file to a user's incrontab CLI Example: .. code-block:: bash salt '*' incron.write_incron_file root /tmp/new_incron
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/incron.py#L72-L82
[ "def _get_incron_cmdstr(path):\n '''\n Returns a format string, to be used to build an incrontab command.\n '''\n return 'incrontab {0}'.format(path)\n" ]
# -*- coding: utf-8 -*- ''' Work with incron ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import os # Import salt libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.data import salt.utils.files import salt.utils.functools import salt.utils.stringutils # Set up logging log = logging.getLogger(__name__) TAG = '# Line managed by Salt, do not edit' _INCRON_SYSTEM_TAB = '/etc/incron.d/' _MASK_TYPES = [ 'IN_ACCESS', 'IN_ATTRIB', 'IN_CLOSE_WRITE', 'IN_CLOSE_NOWRITE', 'IN_CREATE', 'IN_DELETE', 'IN_DELETE_SELF', 'IN_MODIFY', 'IN_MOVE_SELF', 'IN_MOVED_FROM', 'IN_MOVED_TO', 'IN_OPEN', 'IN_ALL_EVENTS', 'IN_MOVE', 'IN_CLOSE', 'IN_DONT_FOLLOW', 'IN_ONESHOT', 'IN_ONLYDIR', 'IN_NO_LOOP' ] def _needs_change(old, new): if old != new: if new == 'random': # Allow switch from '*' or not present to 'random' if old == '*': return True elif new is not None: return True return False def _render_tab(lst): ''' Takes a tab list structure and renders it to a list for applying it to a file ''' ret = [] for pre in lst['pre']: ret.append('{0}\n'.format(pre)) for cron in lst['crons']: ret.append('{0} {1} {2} {3}\n'.format(cron['path'], cron['mask'], cron['cmd'], TAG ) ) return ret def _get_incron_cmdstr(path): ''' Returns a format string, to be used to build an incrontab command. ''' return 'incrontab {0}'.format(path) def write_incron_file_verbose(user, path): ''' Writes the contents of a file to a user's incrontab and return error message on error CLI Example: .. code-block:: bash salt '*' incron.write_incron_file_verbose root /tmp/new_incron ''' return __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False) def _write_incron_lines(user, lines): ''' Takes a list of lines to be committed to a user's incrontab and writes it ''' if user == 'system': ret = {} ret['retcode'] = _write_file(_INCRON_SYSTEM_TAB, 'salt', ''.join(lines)) return ret else: path = salt.utils.files.mkstemp() with salt.utils.files.fopen(path, 'wb') as fp_: fp_.writelines(salt.utils.data.encode(lines)) if __grains__['os_family'] == 'Solaris' and user != "root": __salt__['cmd.run']('chown {0} {1}'.format(user, path), python_shell=False) ret = __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False) os.remove(path) return ret def _write_file(folder, filename, data): ''' Writes a file to disk ''' path = os.path.join(folder, filename) if not os.path.exists(folder): msg = '{0} cannot be written. {1} does not exist'.format(filename, folder) log.error(msg) raise AttributeError(six.text_type(msg)) with salt.utils.files.fopen(path, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(data)) return 0 def _read_file(folder, filename): ''' Reads and returns the contents of a file ''' path = os.path.join(folder, filename) try: with salt.utils.files.fopen(path, 'rb') as contents: return salt.utils.data.decode(contents.readlines()) except (OSError, IOError): return '' def raw_system_incron(): ''' Return the contents of the system wide incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_system_incron ''' _contents = _read_file(_INCRON_SYSTEM_TAB, 'salt') log.debug('incron read_file contents: %s', _contents) return ''.join(_contents) def raw_incron(user): ''' Return the contents of the user's incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_incron root ''' if __grains__['os_family'] == 'Solaris': cmd = 'incrontab -l {0}'.format(user) else: cmd = 'incrontab -l -u {0}'.format(user) return __salt__['cmd.run_stdout'](cmd, rstrip=False, runas=user, python_shell=False) def list_tab(user): ''' Return the contents of the specified user's incrontab CLI Example: .. code-block:: bash salt '*' incron.list_tab root ''' if user == 'system': data = raw_system_incron() else: data = raw_incron(user) log.debug('incron user data %s', data) ret = {'crons': [], 'pre': [] } flag = False comment = None tag = '# Line managed by Salt, do not edit' for line in data.splitlines(): if line.endswith(tag): if len(line.split()) > 3: # Appears to be a standard incron line comps = line.split() path = comps[0] mask = comps[1] (cmd, comment) = ' '.join(comps[2:]).split(' # ') dat = {'path': path, 'mask': mask, 'cmd': cmd, 'comment': comment} ret['crons'].append(dat) comment = None else: ret['pre'].append(line) return ret # For consistency's sake ls = salt.utils.functools.alias_function(list_tab, 'ls') def set_job(user, path, mask, cmd): ''' Sets an incron job up for a specified user. CLI Example: .. code-block:: bash salt '*' incron.set_job root '/root' 'IN_MODIFY' 'echo "$$ $@ $# $% $&"' ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) updated = False arg_mask = mask.split(',') arg_mask.sort() lst = list_tab(user) updated_crons = [] # Look for existing incrons that have cmd, path and at least one of the MASKS # remove and replace with the one we're passed for item, cron in enumerate(lst['crons']): if path == cron['path']: if cron['cmd'] == cmd: cron_mask = cron['mask'].split(',') cron_mask.sort() if cron_mask == arg_mask: return 'present' if any([x in cron_mask for x in arg_mask]): updated = True else: updated_crons.append(cron) else: updated_crons.append(cron) else: updated_crons.append(cron) cron = {'cmd': cmd, 'path': path, 'mask': mask} updated_crons.append(cron) lst['crons'] = updated_crons comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] if updated: return 'updated' else: return 'new' def rm_job(user, path, mask, cmd): ''' Remove a incron job for a specified user. If any of the day/time params are specified, the job will only be removed if the specified params match. CLI Example: .. code-block:: bash salt '*' incron.rm_job root /path ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) lst = list_tab(user) ret = 'absent' rm_ = None for ind in range(len(lst['crons'])): if rm_ is not None: break if path == lst['crons'][ind]['path']: if cmd == lst['crons'][ind]['cmd']: if mask == lst['crons'][ind]['mask']: rm_ = ind if rm_ is not None: lst['crons'].pop(rm_) ret = 'removed' comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] return ret rm = salt.utils.functools.alias_function(rm_job, 'rm')
saltstack/salt
salt/modules/incron.py
write_incron_file_verbose
python
def write_incron_file_verbose(user, path): ''' Writes the contents of a file to a user's incrontab and return error message on error CLI Example: .. code-block:: bash salt '*' incron.write_incron_file_verbose root /tmp/new_incron ''' return __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False)
Writes the contents of a file to a user's incrontab and return error message on error CLI Example: .. code-block:: bash salt '*' incron.write_incron_file_verbose root /tmp/new_incron
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/incron.py#L85-L95
[ "def _get_incron_cmdstr(path):\n '''\n Returns a format string, to be used to build an incrontab command.\n '''\n return 'incrontab {0}'.format(path)\n" ]
# -*- coding: utf-8 -*- ''' Work with incron ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import os # Import salt libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.data import salt.utils.files import salt.utils.functools import salt.utils.stringutils # Set up logging log = logging.getLogger(__name__) TAG = '# Line managed by Salt, do not edit' _INCRON_SYSTEM_TAB = '/etc/incron.d/' _MASK_TYPES = [ 'IN_ACCESS', 'IN_ATTRIB', 'IN_CLOSE_WRITE', 'IN_CLOSE_NOWRITE', 'IN_CREATE', 'IN_DELETE', 'IN_DELETE_SELF', 'IN_MODIFY', 'IN_MOVE_SELF', 'IN_MOVED_FROM', 'IN_MOVED_TO', 'IN_OPEN', 'IN_ALL_EVENTS', 'IN_MOVE', 'IN_CLOSE', 'IN_DONT_FOLLOW', 'IN_ONESHOT', 'IN_ONLYDIR', 'IN_NO_LOOP' ] def _needs_change(old, new): if old != new: if new == 'random': # Allow switch from '*' or not present to 'random' if old == '*': return True elif new is not None: return True return False def _render_tab(lst): ''' Takes a tab list structure and renders it to a list for applying it to a file ''' ret = [] for pre in lst['pre']: ret.append('{0}\n'.format(pre)) for cron in lst['crons']: ret.append('{0} {1} {2} {3}\n'.format(cron['path'], cron['mask'], cron['cmd'], TAG ) ) return ret def _get_incron_cmdstr(path): ''' Returns a format string, to be used to build an incrontab command. ''' return 'incrontab {0}'.format(path) def write_incron_file(user, path): ''' Writes the contents of a file to a user's incrontab CLI Example: .. code-block:: bash salt '*' incron.write_incron_file root /tmp/new_incron ''' return __salt__['cmd.retcode'](_get_incron_cmdstr(path), runas=user, python_shell=False) == 0 def _write_incron_lines(user, lines): ''' Takes a list of lines to be committed to a user's incrontab and writes it ''' if user == 'system': ret = {} ret['retcode'] = _write_file(_INCRON_SYSTEM_TAB, 'salt', ''.join(lines)) return ret else: path = salt.utils.files.mkstemp() with salt.utils.files.fopen(path, 'wb') as fp_: fp_.writelines(salt.utils.data.encode(lines)) if __grains__['os_family'] == 'Solaris' and user != "root": __salt__['cmd.run']('chown {0} {1}'.format(user, path), python_shell=False) ret = __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False) os.remove(path) return ret def _write_file(folder, filename, data): ''' Writes a file to disk ''' path = os.path.join(folder, filename) if not os.path.exists(folder): msg = '{0} cannot be written. {1} does not exist'.format(filename, folder) log.error(msg) raise AttributeError(six.text_type(msg)) with salt.utils.files.fopen(path, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(data)) return 0 def _read_file(folder, filename): ''' Reads and returns the contents of a file ''' path = os.path.join(folder, filename) try: with salt.utils.files.fopen(path, 'rb') as contents: return salt.utils.data.decode(contents.readlines()) except (OSError, IOError): return '' def raw_system_incron(): ''' Return the contents of the system wide incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_system_incron ''' _contents = _read_file(_INCRON_SYSTEM_TAB, 'salt') log.debug('incron read_file contents: %s', _contents) return ''.join(_contents) def raw_incron(user): ''' Return the contents of the user's incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_incron root ''' if __grains__['os_family'] == 'Solaris': cmd = 'incrontab -l {0}'.format(user) else: cmd = 'incrontab -l -u {0}'.format(user) return __salt__['cmd.run_stdout'](cmd, rstrip=False, runas=user, python_shell=False) def list_tab(user): ''' Return the contents of the specified user's incrontab CLI Example: .. code-block:: bash salt '*' incron.list_tab root ''' if user == 'system': data = raw_system_incron() else: data = raw_incron(user) log.debug('incron user data %s', data) ret = {'crons': [], 'pre': [] } flag = False comment = None tag = '# Line managed by Salt, do not edit' for line in data.splitlines(): if line.endswith(tag): if len(line.split()) > 3: # Appears to be a standard incron line comps = line.split() path = comps[0] mask = comps[1] (cmd, comment) = ' '.join(comps[2:]).split(' # ') dat = {'path': path, 'mask': mask, 'cmd': cmd, 'comment': comment} ret['crons'].append(dat) comment = None else: ret['pre'].append(line) return ret # For consistency's sake ls = salt.utils.functools.alias_function(list_tab, 'ls') def set_job(user, path, mask, cmd): ''' Sets an incron job up for a specified user. CLI Example: .. code-block:: bash salt '*' incron.set_job root '/root' 'IN_MODIFY' 'echo "$$ $@ $# $% $&"' ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) updated = False arg_mask = mask.split(',') arg_mask.sort() lst = list_tab(user) updated_crons = [] # Look for existing incrons that have cmd, path and at least one of the MASKS # remove and replace with the one we're passed for item, cron in enumerate(lst['crons']): if path == cron['path']: if cron['cmd'] == cmd: cron_mask = cron['mask'].split(',') cron_mask.sort() if cron_mask == arg_mask: return 'present' if any([x in cron_mask for x in arg_mask]): updated = True else: updated_crons.append(cron) else: updated_crons.append(cron) else: updated_crons.append(cron) cron = {'cmd': cmd, 'path': path, 'mask': mask} updated_crons.append(cron) lst['crons'] = updated_crons comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] if updated: return 'updated' else: return 'new' def rm_job(user, path, mask, cmd): ''' Remove a incron job for a specified user. If any of the day/time params are specified, the job will only be removed if the specified params match. CLI Example: .. code-block:: bash salt '*' incron.rm_job root /path ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) lst = list_tab(user) ret = 'absent' rm_ = None for ind in range(len(lst['crons'])): if rm_ is not None: break if path == lst['crons'][ind]['path']: if cmd == lst['crons'][ind]['cmd']: if mask == lst['crons'][ind]['mask']: rm_ = ind if rm_ is not None: lst['crons'].pop(rm_) ret = 'removed' comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] return ret rm = salt.utils.functools.alias_function(rm_job, 'rm')
saltstack/salt
salt/modules/incron.py
_write_incron_lines
python
def _write_incron_lines(user, lines): ''' Takes a list of lines to be committed to a user's incrontab and writes it ''' if user == 'system': ret = {} ret['retcode'] = _write_file(_INCRON_SYSTEM_TAB, 'salt', ''.join(lines)) return ret else: path = salt.utils.files.mkstemp() with salt.utils.files.fopen(path, 'wb') as fp_: fp_.writelines(salt.utils.data.encode(lines)) if __grains__['os_family'] == 'Solaris' and user != "root": __salt__['cmd.run']('chown {0} {1}'.format(user, path), python_shell=False) ret = __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False) os.remove(path) return ret
Takes a list of lines to be committed to a user's incrontab and writes it
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/incron.py#L98-L114
[ "def encode(data, encoding=None, errors='strict', keep=False,\n preserve_dict_class=False, preserve_tuples=False):\n '''\n Generic function which will encode whichever type is passed, if necessary\n\n If `strict` is True, and `keep` is False, and we fail to encode, a\n UnicodeEncodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where encoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs.\n '''\n if isinstance(data, Mapping):\n return encode_dict(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n elif isinstance(data, list):\n return encode_list(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n elif isinstance(data, tuple):\n return encode_tuple(data, encoding, errors, keep, preserve_dict_class) \\\n if preserve_tuples \\\n else encode_list(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n else:\n try:\n return salt.utils.stringutils.to_bytes(data, encoding, errors)\n except TypeError:\n # to_bytes raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply\n # means we are going to leave the value as-is.\n pass\n except UnicodeEncodeError:\n if not keep:\n raise\n return data\n", "def mkstemp(*args, **kwargs):\n '''\n Helper function which does exactly what ``tempfile.mkstemp()`` does but\n accepts another argument, ``close_fd``, which, by default, is true and closes\n the fd before returning the file path. Something commonly done throughout\n Salt's code.\n '''\n if 'prefix' not in kwargs:\n kwargs['prefix'] = '__salt.tmp.'\n close_fd = kwargs.pop('close_fd', True)\n fd_, f_path = tempfile.mkstemp(*args, **kwargs)\n if close_fd is False:\n return fd_, f_path\n os.close(fd_)\n del fd_\n return f_path\n", "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def _write_file(folder, filename, data):\n '''\n Writes a file to disk\n '''\n path = os.path.join(folder, filename)\n if not os.path.exists(folder):\n msg = '{0} cannot be written. {1} does not exist'.format(filename, folder)\n log.error(msg)\n raise AttributeError(six.text_type(msg))\n with salt.utils.files.fopen(path, 'w') as fp_:\n fp_.write(salt.utils.stringutils.to_str(data))\n\n return 0\n", "def _get_incron_cmdstr(path):\n '''\n Returns a format string, to be used to build an incrontab command.\n '''\n return 'incrontab {0}'.format(path)\n" ]
# -*- coding: utf-8 -*- ''' Work with incron ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import os # Import salt libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.data import salt.utils.files import salt.utils.functools import salt.utils.stringutils # Set up logging log = logging.getLogger(__name__) TAG = '# Line managed by Salt, do not edit' _INCRON_SYSTEM_TAB = '/etc/incron.d/' _MASK_TYPES = [ 'IN_ACCESS', 'IN_ATTRIB', 'IN_CLOSE_WRITE', 'IN_CLOSE_NOWRITE', 'IN_CREATE', 'IN_DELETE', 'IN_DELETE_SELF', 'IN_MODIFY', 'IN_MOVE_SELF', 'IN_MOVED_FROM', 'IN_MOVED_TO', 'IN_OPEN', 'IN_ALL_EVENTS', 'IN_MOVE', 'IN_CLOSE', 'IN_DONT_FOLLOW', 'IN_ONESHOT', 'IN_ONLYDIR', 'IN_NO_LOOP' ] def _needs_change(old, new): if old != new: if new == 'random': # Allow switch from '*' or not present to 'random' if old == '*': return True elif new is not None: return True return False def _render_tab(lst): ''' Takes a tab list structure and renders it to a list for applying it to a file ''' ret = [] for pre in lst['pre']: ret.append('{0}\n'.format(pre)) for cron in lst['crons']: ret.append('{0} {1} {2} {3}\n'.format(cron['path'], cron['mask'], cron['cmd'], TAG ) ) return ret def _get_incron_cmdstr(path): ''' Returns a format string, to be used to build an incrontab command. ''' return 'incrontab {0}'.format(path) def write_incron_file(user, path): ''' Writes the contents of a file to a user's incrontab CLI Example: .. code-block:: bash salt '*' incron.write_incron_file root /tmp/new_incron ''' return __salt__['cmd.retcode'](_get_incron_cmdstr(path), runas=user, python_shell=False) == 0 def write_incron_file_verbose(user, path): ''' Writes the contents of a file to a user's incrontab and return error message on error CLI Example: .. code-block:: bash salt '*' incron.write_incron_file_verbose root /tmp/new_incron ''' return __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False) def _write_file(folder, filename, data): ''' Writes a file to disk ''' path = os.path.join(folder, filename) if not os.path.exists(folder): msg = '{0} cannot be written. {1} does not exist'.format(filename, folder) log.error(msg) raise AttributeError(six.text_type(msg)) with salt.utils.files.fopen(path, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(data)) return 0 def _read_file(folder, filename): ''' Reads and returns the contents of a file ''' path = os.path.join(folder, filename) try: with salt.utils.files.fopen(path, 'rb') as contents: return salt.utils.data.decode(contents.readlines()) except (OSError, IOError): return '' def raw_system_incron(): ''' Return the contents of the system wide incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_system_incron ''' _contents = _read_file(_INCRON_SYSTEM_TAB, 'salt') log.debug('incron read_file contents: %s', _contents) return ''.join(_contents) def raw_incron(user): ''' Return the contents of the user's incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_incron root ''' if __grains__['os_family'] == 'Solaris': cmd = 'incrontab -l {0}'.format(user) else: cmd = 'incrontab -l -u {0}'.format(user) return __salt__['cmd.run_stdout'](cmd, rstrip=False, runas=user, python_shell=False) def list_tab(user): ''' Return the contents of the specified user's incrontab CLI Example: .. code-block:: bash salt '*' incron.list_tab root ''' if user == 'system': data = raw_system_incron() else: data = raw_incron(user) log.debug('incron user data %s', data) ret = {'crons': [], 'pre': [] } flag = False comment = None tag = '# Line managed by Salt, do not edit' for line in data.splitlines(): if line.endswith(tag): if len(line.split()) > 3: # Appears to be a standard incron line comps = line.split() path = comps[0] mask = comps[1] (cmd, comment) = ' '.join(comps[2:]).split(' # ') dat = {'path': path, 'mask': mask, 'cmd': cmd, 'comment': comment} ret['crons'].append(dat) comment = None else: ret['pre'].append(line) return ret # For consistency's sake ls = salt.utils.functools.alias_function(list_tab, 'ls') def set_job(user, path, mask, cmd): ''' Sets an incron job up for a specified user. CLI Example: .. code-block:: bash salt '*' incron.set_job root '/root' 'IN_MODIFY' 'echo "$$ $@ $# $% $&"' ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) updated = False arg_mask = mask.split(',') arg_mask.sort() lst = list_tab(user) updated_crons = [] # Look for existing incrons that have cmd, path and at least one of the MASKS # remove and replace with the one we're passed for item, cron in enumerate(lst['crons']): if path == cron['path']: if cron['cmd'] == cmd: cron_mask = cron['mask'].split(',') cron_mask.sort() if cron_mask == arg_mask: return 'present' if any([x in cron_mask for x in arg_mask]): updated = True else: updated_crons.append(cron) else: updated_crons.append(cron) else: updated_crons.append(cron) cron = {'cmd': cmd, 'path': path, 'mask': mask} updated_crons.append(cron) lst['crons'] = updated_crons comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] if updated: return 'updated' else: return 'new' def rm_job(user, path, mask, cmd): ''' Remove a incron job for a specified user. If any of the day/time params are specified, the job will only be removed if the specified params match. CLI Example: .. code-block:: bash salt '*' incron.rm_job root /path ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) lst = list_tab(user) ret = 'absent' rm_ = None for ind in range(len(lst['crons'])): if rm_ is not None: break if path == lst['crons'][ind]['path']: if cmd == lst['crons'][ind]['cmd']: if mask == lst['crons'][ind]['mask']: rm_ = ind if rm_ is not None: lst['crons'].pop(rm_) ret = 'removed' comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] return ret rm = salt.utils.functools.alias_function(rm_job, 'rm')
saltstack/salt
salt/modules/incron.py
_write_file
python
def _write_file(folder, filename, data): ''' Writes a file to disk ''' path = os.path.join(folder, filename) if not os.path.exists(folder): msg = '{0} cannot be written. {1} does not exist'.format(filename, folder) log.error(msg) raise AttributeError(six.text_type(msg)) with salt.utils.files.fopen(path, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(data)) return 0
Writes a file to disk
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/incron.py#L117-L129
null
# -*- coding: utf-8 -*- ''' Work with incron ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import os # Import salt libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.data import salt.utils.files import salt.utils.functools import salt.utils.stringutils # Set up logging log = logging.getLogger(__name__) TAG = '# Line managed by Salt, do not edit' _INCRON_SYSTEM_TAB = '/etc/incron.d/' _MASK_TYPES = [ 'IN_ACCESS', 'IN_ATTRIB', 'IN_CLOSE_WRITE', 'IN_CLOSE_NOWRITE', 'IN_CREATE', 'IN_DELETE', 'IN_DELETE_SELF', 'IN_MODIFY', 'IN_MOVE_SELF', 'IN_MOVED_FROM', 'IN_MOVED_TO', 'IN_OPEN', 'IN_ALL_EVENTS', 'IN_MOVE', 'IN_CLOSE', 'IN_DONT_FOLLOW', 'IN_ONESHOT', 'IN_ONLYDIR', 'IN_NO_LOOP' ] def _needs_change(old, new): if old != new: if new == 'random': # Allow switch from '*' or not present to 'random' if old == '*': return True elif new is not None: return True return False def _render_tab(lst): ''' Takes a tab list structure and renders it to a list for applying it to a file ''' ret = [] for pre in lst['pre']: ret.append('{0}\n'.format(pre)) for cron in lst['crons']: ret.append('{0} {1} {2} {3}\n'.format(cron['path'], cron['mask'], cron['cmd'], TAG ) ) return ret def _get_incron_cmdstr(path): ''' Returns a format string, to be used to build an incrontab command. ''' return 'incrontab {0}'.format(path) def write_incron_file(user, path): ''' Writes the contents of a file to a user's incrontab CLI Example: .. code-block:: bash salt '*' incron.write_incron_file root /tmp/new_incron ''' return __salt__['cmd.retcode'](_get_incron_cmdstr(path), runas=user, python_shell=False) == 0 def write_incron_file_verbose(user, path): ''' Writes the contents of a file to a user's incrontab and return error message on error CLI Example: .. code-block:: bash salt '*' incron.write_incron_file_verbose root /tmp/new_incron ''' return __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False) def _write_incron_lines(user, lines): ''' Takes a list of lines to be committed to a user's incrontab and writes it ''' if user == 'system': ret = {} ret['retcode'] = _write_file(_INCRON_SYSTEM_TAB, 'salt', ''.join(lines)) return ret else: path = salt.utils.files.mkstemp() with salt.utils.files.fopen(path, 'wb') as fp_: fp_.writelines(salt.utils.data.encode(lines)) if __grains__['os_family'] == 'Solaris' and user != "root": __salt__['cmd.run']('chown {0} {1}'.format(user, path), python_shell=False) ret = __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False) os.remove(path) return ret def _read_file(folder, filename): ''' Reads and returns the contents of a file ''' path = os.path.join(folder, filename) try: with salt.utils.files.fopen(path, 'rb') as contents: return salt.utils.data.decode(contents.readlines()) except (OSError, IOError): return '' def raw_system_incron(): ''' Return the contents of the system wide incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_system_incron ''' _contents = _read_file(_INCRON_SYSTEM_TAB, 'salt') log.debug('incron read_file contents: %s', _contents) return ''.join(_contents) def raw_incron(user): ''' Return the contents of the user's incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_incron root ''' if __grains__['os_family'] == 'Solaris': cmd = 'incrontab -l {0}'.format(user) else: cmd = 'incrontab -l -u {0}'.format(user) return __salt__['cmd.run_stdout'](cmd, rstrip=False, runas=user, python_shell=False) def list_tab(user): ''' Return the contents of the specified user's incrontab CLI Example: .. code-block:: bash salt '*' incron.list_tab root ''' if user == 'system': data = raw_system_incron() else: data = raw_incron(user) log.debug('incron user data %s', data) ret = {'crons': [], 'pre': [] } flag = False comment = None tag = '# Line managed by Salt, do not edit' for line in data.splitlines(): if line.endswith(tag): if len(line.split()) > 3: # Appears to be a standard incron line comps = line.split() path = comps[0] mask = comps[1] (cmd, comment) = ' '.join(comps[2:]).split(' # ') dat = {'path': path, 'mask': mask, 'cmd': cmd, 'comment': comment} ret['crons'].append(dat) comment = None else: ret['pre'].append(line) return ret # For consistency's sake ls = salt.utils.functools.alias_function(list_tab, 'ls') def set_job(user, path, mask, cmd): ''' Sets an incron job up for a specified user. CLI Example: .. code-block:: bash salt '*' incron.set_job root '/root' 'IN_MODIFY' 'echo "$$ $@ $# $% $&"' ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) updated = False arg_mask = mask.split(',') arg_mask.sort() lst = list_tab(user) updated_crons = [] # Look for existing incrons that have cmd, path and at least one of the MASKS # remove and replace with the one we're passed for item, cron in enumerate(lst['crons']): if path == cron['path']: if cron['cmd'] == cmd: cron_mask = cron['mask'].split(',') cron_mask.sort() if cron_mask == arg_mask: return 'present' if any([x in cron_mask for x in arg_mask]): updated = True else: updated_crons.append(cron) else: updated_crons.append(cron) else: updated_crons.append(cron) cron = {'cmd': cmd, 'path': path, 'mask': mask} updated_crons.append(cron) lst['crons'] = updated_crons comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] if updated: return 'updated' else: return 'new' def rm_job(user, path, mask, cmd): ''' Remove a incron job for a specified user. If any of the day/time params are specified, the job will only be removed if the specified params match. CLI Example: .. code-block:: bash salt '*' incron.rm_job root /path ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) lst = list_tab(user) ret = 'absent' rm_ = None for ind in range(len(lst['crons'])): if rm_ is not None: break if path == lst['crons'][ind]['path']: if cmd == lst['crons'][ind]['cmd']: if mask == lst['crons'][ind]['mask']: rm_ = ind if rm_ is not None: lst['crons'].pop(rm_) ret = 'removed' comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] return ret rm = salt.utils.functools.alias_function(rm_job, 'rm')
saltstack/salt
salt/modules/incron.py
_read_file
python
def _read_file(folder, filename): ''' Reads and returns the contents of a file ''' path = os.path.join(folder, filename) try: with salt.utils.files.fopen(path, 'rb') as contents: return salt.utils.data.decode(contents.readlines()) except (OSError, IOError): return ''
Reads and returns the contents of a file
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/incron.py#L132-L141
[ "def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n", "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n" ]
# -*- coding: utf-8 -*- ''' Work with incron ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import os # Import salt libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.data import salt.utils.files import salt.utils.functools import salt.utils.stringutils # Set up logging log = logging.getLogger(__name__) TAG = '# Line managed by Salt, do not edit' _INCRON_SYSTEM_TAB = '/etc/incron.d/' _MASK_TYPES = [ 'IN_ACCESS', 'IN_ATTRIB', 'IN_CLOSE_WRITE', 'IN_CLOSE_NOWRITE', 'IN_CREATE', 'IN_DELETE', 'IN_DELETE_SELF', 'IN_MODIFY', 'IN_MOVE_SELF', 'IN_MOVED_FROM', 'IN_MOVED_TO', 'IN_OPEN', 'IN_ALL_EVENTS', 'IN_MOVE', 'IN_CLOSE', 'IN_DONT_FOLLOW', 'IN_ONESHOT', 'IN_ONLYDIR', 'IN_NO_LOOP' ] def _needs_change(old, new): if old != new: if new == 'random': # Allow switch from '*' or not present to 'random' if old == '*': return True elif new is not None: return True return False def _render_tab(lst): ''' Takes a tab list structure and renders it to a list for applying it to a file ''' ret = [] for pre in lst['pre']: ret.append('{0}\n'.format(pre)) for cron in lst['crons']: ret.append('{0} {1} {2} {3}\n'.format(cron['path'], cron['mask'], cron['cmd'], TAG ) ) return ret def _get_incron_cmdstr(path): ''' Returns a format string, to be used to build an incrontab command. ''' return 'incrontab {0}'.format(path) def write_incron_file(user, path): ''' Writes the contents of a file to a user's incrontab CLI Example: .. code-block:: bash salt '*' incron.write_incron_file root /tmp/new_incron ''' return __salt__['cmd.retcode'](_get_incron_cmdstr(path), runas=user, python_shell=False) == 0 def write_incron_file_verbose(user, path): ''' Writes the contents of a file to a user's incrontab and return error message on error CLI Example: .. code-block:: bash salt '*' incron.write_incron_file_verbose root /tmp/new_incron ''' return __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False) def _write_incron_lines(user, lines): ''' Takes a list of lines to be committed to a user's incrontab and writes it ''' if user == 'system': ret = {} ret['retcode'] = _write_file(_INCRON_SYSTEM_TAB, 'salt', ''.join(lines)) return ret else: path = salt.utils.files.mkstemp() with salt.utils.files.fopen(path, 'wb') as fp_: fp_.writelines(salt.utils.data.encode(lines)) if __grains__['os_family'] == 'Solaris' and user != "root": __salt__['cmd.run']('chown {0} {1}'.format(user, path), python_shell=False) ret = __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False) os.remove(path) return ret def _write_file(folder, filename, data): ''' Writes a file to disk ''' path = os.path.join(folder, filename) if not os.path.exists(folder): msg = '{0} cannot be written. {1} does not exist'.format(filename, folder) log.error(msg) raise AttributeError(six.text_type(msg)) with salt.utils.files.fopen(path, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(data)) return 0 def raw_system_incron(): ''' Return the contents of the system wide incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_system_incron ''' _contents = _read_file(_INCRON_SYSTEM_TAB, 'salt') log.debug('incron read_file contents: %s', _contents) return ''.join(_contents) def raw_incron(user): ''' Return the contents of the user's incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_incron root ''' if __grains__['os_family'] == 'Solaris': cmd = 'incrontab -l {0}'.format(user) else: cmd = 'incrontab -l -u {0}'.format(user) return __salt__['cmd.run_stdout'](cmd, rstrip=False, runas=user, python_shell=False) def list_tab(user): ''' Return the contents of the specified user's incrontab CLI Example: .. code-block:: bash salt '*' incron.list_tab root ''' if user == 'system': data = raw_system_incron() else: data = raw_incron(user) log.debug('incron user data %s', data) ret = {'crons': [], 'pre': [] } flag = False comment = None tag = '# Line managed by Salt, do not edit' for line in data.splitlines(): if line.endswith(tag): if len(line.split()) > 3: # Appears to be a standard incron line comps = line.split() path = comps[0] mask = comps[1] (cmd, comment) = ' '.join(comps[2:]).split(' # ') dat = {'path': path, 'mask': mask, 'cmd': cmd, 'comment': comment} ret['crons'].append(dat) comment = None else: ret['pre'].append(line) return ret # For consistency's sake ls = salt.utils.functools.alias_function(list_tab, 'ls') def set_job(user, path, mask, cmd): ''' Sets an incron job up for a specified user. CLI Example: .. code-block:: bash salt '*' incron.set_job root '/root' 'IN_MODIFY' 'echo "$$ $@ $# $% $&"' ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) updated = False arg_mask = mask.split(',') arg_mask.sort() lst = list_tab(user) updated_crons = [] # Look for existing incrons that have cmd, path and at least one of the MASKS # remove and replace with the one we're passed for item, cron in enumerate(lst['crons']): if path == cron['path']: if cron['cmd'] == cmd: cron_mask = cron['mask'].split(',') cron_mask.sort() if cron_mask == arg_mask: return 'present' if any([x in cron_mask for x in arg_mask]): updated = True else: updated_crons.append(cron) else: updated_crons.append(cron) else: updated_crons.append(cron) cron = {'cmd': cmd, 'path': path, 'mask': mask} updated_crons.append(cron) lst['crons'] = updated_crons comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] if updated: return 'updated' else: return 'new' def rm_job(user, path, mask, cmd): ''' Remove a incron job for a specified user. If any of the day/time params are specified, the job will only be removed if the specified params match. CLI Example: .. code-block:: bash salt '*' incron.rm_job root /path ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) lst = list_tab(user) ret = 'absent' rm_ = None for ind in range(len(lst['crons'])): if rm_ is not None: break if path == lst['crons'][ind]['path']: if cmd == lst['crons'][ind]['cmd']: if mask == lst['crons'][ind]['mask']: rm_ = ind if rm_ is not None: lst['crons'].pop(rm_) ret = 'removed' comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] return ret rm = salt.utils.functools.alias_function(rm_job, 'rm')
saltstack/salt
salt/modules/incron.py
raw_incron
python
def raw_incron(user): ''' Return the contents of the user's incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_incron root ''' if __grains__['os_family'] == 'Solaris': cmd = 'incrontab -l {0}'.format(user) else: cmd = 'incrontab -l -u {0}'.format(user) return __salt__['cmd.run_stdout'](cmd, rstrip=False, runas=user, python_shell=False)
Return the contents of the user's incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_incron root
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/incron.py#L159-L173
null
# -*- coding: utf-8 -*- ''' Work with incron ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import os # Import salt libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.data import salt.utils.files import salt.utils.functools import salt.utils.stringutils # Set up logging log = logging.getLogger(__name__) TAG = '# Line managed by Salt, do not edit' _INCRON_SYSTEM_TAB = '/etc/incron.d/' _MASK_TYPES = [ 'IN_ACCESS', 'IN_ATTRIB', 'IN_CLOSE_WRITE', 'IN_CLOSE_NOWRITE', 'IN_CREATE', 'IN_DELETE', 'IN_DELETE_SELF', 'IN_MODIFY', 'IN_MOVE_SELF', 'IN_MOVED_FROM', 'IN_MOVED_TO', 'IN_OPEN', 'IN_ALL_EVENTS', 'IN_MOVE', 'IN_CLOSE', 'IN_DONT_FOLLOW', 'IN_ONESHOT', 'IN_ONLYDIR', 'IN_NO_LOOP' ] def _needs_change(old, new): if old != new: if new == 'random': # Allow switch from '*' or not present to 'random' if old == '*': return True elif new is not None: return True return False def _render_tab(lst): ''' Takes a tab list structure and renders it to a list for applying it to a file ''' ret = [] for pre in lst['pre']: ret.append('{0}\n'.format(pre)) for cron in lst['crons']: ret.append('{0} {1} {2} {3}\n'.format(cron['path'], cron['mask'], cron['cmd'], TAG ) ) return ret def _get_incron_cmdstr(path): ''' Returns a format string, to be used to build an incrontab command. ''' return 'incrontab {0}'.format(path) def write_incron_file(user, path): ''' Writes the contents of a file to a user's incrontab CLI Example: .. code-block:: bash salt '*' incron.write_incron_file root /tmp/new_incron ''' return __salt__['cmd.retcode'](_get_incron_cmdstr(path), runas=user, python_shell=False) == 0 def write_incron_file_verbose(user, path): ''' Writes the contents of a file to a user's incrontab and return error message on error CLI Example: .. code-block:: bash salt '*' incron.write_incron_file_verbose root /tmp/new_incron ''' return __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False) def _write_incron_lines(user, lines): ''' Takes a list of lines to be committed to a user's incrontab and writes it ''' if user == 'system': ret = {} ret['retcode'] = _write_file(_INCRON_SYSTEM_TAB, 'salt', ''.join(lines)) return ret else: path = salt.utils.files.mkstemp() with salt.utils.files.fopen(path, 'wb') as fp_: fp_.writelines(salt.utils.data.encode(lines)) if __grains__['os_family'] == 'Solaris' and user != "root": __salt__['cmd.run']('chown {0} {1}'.format(user, path), python_shell=False) ret = __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False) os.remove(path) return ret def _write_file(folder, filename, data): ''' Writes a file to disk ''' path = os.path.join(folder, filename) if not os.path.exists(folder): msg = '{0} cannot be written. {1} does not exist'.format(filename, folder) log.error(msg) raise AttributeError(six.text_type(msg)) with salt.utils.files.fopen(path, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(data)) return 0 def _read_file(folder, filename): ''' Reads and returns the contents of a file ''' path = os.path.join(folder, filename) try: with salt.utils.files.fopen(path, 'rb') as contents: return salt.utils.data.decode(contents.readlines()) except (OSError, IOError): return '' def raw_system_incron(): ''' Return the contents of the system wide incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_system_incron ''' _contents = _read_file(_INCRON_SYSTEM_TAB, 'salt') log.debug('incron read_file contents: %s', _contents) return ''.join(_contents) def list_tab(user): ''' Return the contents of the specified user's incrontab CLI Example: .. code-block:: bash salt '*' incron.list_tab root ''' if user == 'system': data = raw_system_incron() else: data = raw_incron(user) log.debug('incron user data %s', data) ret = {'crons': [], 'pre': [] } flag = False comment = None tag = '# Line managed by Salt, do not edit' for line in data.splitlines(): if line.endswith(tag): if len(line.split()) > 3: # Appears to be a standard incron line comps = line.split() path = comps[0] mask = comps[1] (cmd, comment) = ' '.join(comps[2:]).split(' # ') dat = {'path': path, 'mask': mask, 'cmd': cmd, 'comment': comment} ret['crons'].append(dat) comment = None else: ret['pre'].append(line) return ret # For consistency's sake ls = salt.utils.functools.alias_function(list_tab, 'ls') def set_job(user, path, mask, cmd): ''' Sets an incron job up for a specified user. CLI Example: .. code-block:: bash salt '*' incron.set_job root '/root' 'IN_MODIFY' 'echo "$$ $@ $# $% $&"' ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) updated = False arg_mask = mask.split(',') arg_mask.sort() lst = list_tab(user) updated_crons = [] # Look for existing incrons that have cmd, path and at least one of the MASKS # remove and replace with the one we're passed for item, cron in enumerate(lst['crons']): if path == cron['path']: if cron['cmd'] == cmd: cron_mask = cron['mask'].split(',') cron_mask.sort() if cron_mask == arg_mask: return 'present' if any([x in cron_mask for x in arg_mask]): updated = True else: updated_crons.append(cron) else: updated_crons.append(cron) else: updated_crons.append(cron) cron = {'cmd': cmd, 'path': path, 'mask': mask} updated_crons.append(cron) lst['crons'] = updated_crons comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] if updated: return 'updated' else: return 'new' def rm_job(user, path, mask, cmd): ''' Remove a incron job for a specified user. If any of the day/time params are specified, the job will only be removed if the specified params match. CLI Example: .. code-block:: bash salt '*' incron.rm_job root /path ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) lst = list_tab(user) ret = 'absent' rm_ = None for ind in range(len(lst['crons'])): if rm_ is not None: break if path == lst['crons'][ind]['path']: if cmd == lst['crons'][ind]['cmd']: if mask == lst['crons'][ind]['mask']: rm_ = ind if rm_ is not None: lst['crons'].pop(rm_) ret = 'removed' comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] return ret rm = salt.utils.functools.alias_function(rm_job, 'rm')
saltstack/salt
salt/modules/incron.py
list_tab
python
def list_tab(user): ''' Return the contents of the specified user's incrontab CLI Example: .. code-block:: bash salt '*' incron.list_tab root ''' if user == 'system': data = raw_system_incron() else: data = raw_incron(user) log.debug('incron user data %s', data) ret = {'crons': [], 'pre': [] } flag = False comment = None tag = '# Line managed by Salt, do not edit' for line in data.splitlines(): if line.endswith(tag): if len(line.split()) > 3: # Appears to be a standard incron line comps = line.split() path = comps[0] mask = comps[1] (cmd, comment) = ' '.join(comps[2:]).split(' # ') dat = {'path': path, 'mask': mask, 'cmd': cmd, 'comment': comment} ret['crons'].append(dat) comment = None else: ret['pre'].append(line) return ret
Return the contents of the specified user's incrontab CLI Example: .. code-block:: bash salt '*' incron.list_tab root
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/incron.py#L176-L214
[ "def raw_system_incron():\n '''\n Return the contents of the system wide incrontab\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' incron.raw_system_incron\n '''\n _contents = _read_file(_INCRON_SYSTEM_TAB, 'salt')\n log.debug('incron read_file contents: %s', _contents)\n return ''.join(_contents)\n", "def raw_incron(user):\n '''\n Return the contents of the user's incrontab\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' incron.raw_incron root\n '''\n if __grains__['os_family'] == 'Solaris':\n cmd = 'incrontab -l {0}'.format(user)\n else:\n cmd = 'incrontab -l -u {0}'.format(user)\n return __salt__['cmd.run_stdout'](cmd, rstrip=False, runas=user, python_shell=False)\n" ]
# -*- coding: utf-8 -*- ''' Work with incron ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import os # Import salt libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.data import salt.utils.files import salt.utils.functools import salt.utils.stringutils # Set up logging log = logging.getLogger(__name__) TAG = '# Line managed by Salt, do not edit' _INCRON_SYSTEM_TAB = '/etc/incron.d/' _MASK_TYPES = [ 'IN_ACCESS', 'IN_ATTRIB', 'IN_CLOSE_WRITE', 'IN_CLOSE_NOWRITE', 'IN_CREATE', 'IN_DELETE', 'IN_DELETE_SELF', 'IN_MODIFY', 'IN_MOVE_SELF', 'IN_MOVED_FROM', 'IN_MOVED_TO', 'IN_OPEN', 'IN_ALL_EVENTS', 'IN_MOVE', 'IN_CLOSE', 'IN_DONT_FOLLOW', 'IN_ONESHOT', 'IN_ONLYDIR', 'IN_NO_LOOP' ] def _needs_change(old, new): if old != new: if new == 'random': # Allow switch from '*' or not present to 'random' if old == '*': return True elif new is not None: return True return False def _render_tab(lst): ''' Takes a tab list structure and renders it to a list for applying it to a file ''' ret = [] for pre in lst['pre']: ret.append('{0}\n'.format(pre)) for cron in lst['crons']: ret.append('{0} {1} {2} {3}\n'.format(cron['path'], cron['mask'], cron['cmd'], TAG ) ) return ret def _get_incron_cmdstr(path): ''' Returns a format string, to be used to build an incrontab command. ''' return 'incrontab {0}'.format(path) def write_incron_file(user, path): ''' Writes the contents of a file to a user's incrontab CLI Example: .. code-block:: bash salt '*' incron.write_incron_file root /tmp/new_incron ''' return __salt__['cmd.retcode'](_get_incron_cmdstr(path), runas=user, python_shell=False) == 0 def write_incron_file_verbose(user, path): ''' Writes the contents of a file to a user's incrontab and return error message on error CLI Example: .. code-block:: bash salt '*' incron.write_incron_file_verbose root /tmp/new_incron ''' return __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False) def _write_incron_lines(user, lines): ''' Takes a list of lines to be committed to a user's incrontab and writes it ''' if user == 'system': ret = {} ret['retcode'] = _write_file(_INCRON_SYSTEM_TAB, 'salt', ''.join(lines)) return ret else: path = salt.utils.files.mkstemp() with salt.utils.files.fopen(path, 'wb') as fp_: fp_.writelines(salt.utils.data.encode(lines)) if __grains__['os_family'] == 'Solaris' and user != "root": __salt__['cmd.run']('chown {0} {1}'.format(user, path), python_shell=False) ret = __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False) os.remove(path) return ret def _write_file(folder, filename, data): ''' Writes a file to disk ''' path = os.path.join(folder, filename) if not os.path.exists(folder): msg = '{0} cannot be written. {1} does not exist'.format(filename, folder) log.error(msg) raise AttributeError(six.text_type(msg)) with salt.utils.files.fopen(path, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(data)) return 0 def _read_file(folder, filename): ''' Reads and returns the contents of a file ''' path = os.path.join(folder, filename) try: with salt.utils.files.fopen(path, 'rb') as contents: return salt.utils.data.decode(contents.readlines()) except (OSError, IOError): return '' def raw_system_incron(): ''' Return the contents of the system wide incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_system_incron ''' _contents = _read_file(_INCRON_SYSTEM_TAB, 'salt') log.debug('incron read_file contents: %s', _contents) return ''.join(_contents) def raw_incron(user): ''' Return the contents of the user's incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_incron root ''' if __grains__['os_family'] == 'Solaris': cmd = 'incrontab -l {0}'.format(user) else: cmd = 'incrontab -l -u {0}'.format(user) return __salt__['cmd.run_stdout'](cmd, rstrip=False, runas=user, python_shell=False) # For consistency's sake ls = salt.utils.functools.alias_function(list_tab, 'ls') def set_job(user, path, mask, cmd): ''' Sets an incron job up for a specified user. CLI Example: .. code-block:: bash salt '*' incron.set_job root '/root' 'IN_MODIFY' 'echo "$$ $@ $# $% $&"' ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) updated = False arg_mask = mask.split(',') arg_mask.sort() lst = list_tab(user) updated_crons = [] # Look for existing incrons that have cmd, path and at least one of the MASKS # remove and replace with the one we're passed for item, cron in enumerate(lst['crons']): if path == cron['path']: if cron['cmd'] == cmd: cron_mask = cron['mask'].split(',') cron_mask.sort() if cron_mask == arg_mask: return 'present' if any([x in cron_mask for x in arg_mask]): updated = True else: updated_crons.append(cron) else: updated_crons.append(cron) else: updated_crons.append(cron) cron = {'cmd': cmd, 'path': path, 'mask': mask} updated_crons.append(cron) lst['crons'] = updated_crons comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] if updated: return 'updated' else: return 'new' def rm_job(user, path, mask, cmd): ''' Remove a incron job for a specified user. If any of the day/time params are specified, the job will only be removed if the specified params match. CLI Example: .. code-block:: bash salt '*' incron.rm_job root /path ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) lst = list_tab(user) ret = 'absent' rm_ = None for ind in range(len(lst['crons'])): if rm_ is not None: break if path == lst['crons'][ind]['path']: if cmd == lst['crons'][ind]['cmd']: if mask == lst['crons'][ind]['mask']: rm_ = ind if rm_ is not None: lst['crons'].pop(rm_) ret = 'removed' comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] return ret rm = salt.utils.functools.alias_function(rm_job, 'rm')
saltstack/salt
salt/modules/incron.py
set_job
python
def set_job(user, path, mask, cmd): ''' Sets an incron job up for a specified user. CLI Example: .. code-block:: bash salt '*' incron.set_job root '/root' 'IN_MODIFY' 'echo "$$ $@ $# $% $&"' ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) updated = False arg_mask = mask.split(',') arg_mask.sort() lst = list_tab(user) updated_crons = [] # Look for existing incrons that have cmd, path and at least one of the MASKS # remove and replace with the one we're passed for item, cron in enumerate(lst['crons']): if path == cron['path']: if cron['cmd'] == cmd: cron_mask = cron['mask'].split(',') cron_mask.sort() if cron_mask == arg_mask: return 'present' if any([x in cron_mask for x in arg_mask]): updated = True else: updated_crons.append(cron) else: updated_crons.append(cron) else: updated_crons.append(cron) cron = {'cmd': cmd, 'path': path, 'mask': mask} updated_crons.append(cron) lst['crons'] = updated_crons comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] if updated: return 'updated' else: return 'new'
Sets an incron job up for a specified user. CLI Example: .. code-block:: bash salt '*' incron.set_job root '/root' 'IN_MODIFY' 'echo "$$ $@ $# $% $&"'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/incron.py#L221-L276
[ "def _render_tab(lst):\n '''\n Takes a tab list structure and renders it to a list for applying it to\n a file\n '''\n ret = []\n for pre in lst['pre']:\n ret.append('{0}\\n'.format(pre))\n for cron in lst['crons']:\n ret.append('{0} {1} {2} {3}\\n'.format(cron['path'],\n cron['mask'],\n cron['cmd'],\n TAG\n )\n )\n return ret\n", "def list_tab(user):\n '''\n Return the contents of the specified user's incrontab\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' incron.list_tab root\n '''\n if user == 'system':\n data = raw_system_incron()\n else:\n data = raw_incron(user)\n log.debug('incron user data %s', data)\n ret = {'crons': [],\n 'pre': []\n }\n flag = False\n comment = None\n tag = '# Line managed by Salt, do not edit'\n for line in data.splitlines():\n if line.endswith(tag):\n if len(line.split()) > 3:\n # Appears to be a standard incron line\n comps = line.split()\n path = comps[0]\n mask = comps[1]\n (cmd, comment) = ' '.join(comps[2:]).split(' # ')\n\n dat = {'path': path,\n 'mask': mask,\n 'cmd': cmd,\n 'comment': comment}\n ret['crons'].append(dat)\n comment = None\n else:\n ret['pre'].append(line)\n return ret\n", "def _write_incron_lines(user, lines):\n '''\n Takes a list of lines to be committed to a user's incrontab and writes it\n '''\n if user == 'system':\n ret = {}\n ret['retcode'] = _write_file(_INCRON_SYSTEM_TAB, 'salt', ''.join(lines))\n return ret\n else:\n path = salt.utils.files.mkstemp()\n with salt.utils.files.fopen(path, 'wb') as fp_:\n fp_.writelines(salt.utils.data.encode(lines))\n if __grains__['os_family'] == 'Solaris' and user != \"root\":\n __salt__['cmd.run']('chown {0} {1}'.format(user, path), python_shell=False)\n ret = __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False)\n os.remove(path)\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Work with incron ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import os # Import salt libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.data import salt.utils.files import salt.utils.functools import salt.utils.stringutils # Set up logging log = logging.getLogger(__name__) TAG = '# Line managed by Salt, do not edit' _INCRON_SYSTEM_TAB = '/etc/incron.d/' _MASK_TYPES = [ 'IN_ACCESS', 'IN_ATTRIB', 'IN_CLOSE_WRITE', 'IN_CLOSE_NOWRITE', 'IN_CREATE', 'IN_DELETE', 'IN_DELETE_SELF', 'IN_MODIFY', 'IN_MOVE_SELF', 'IN_MOVED_FROM', 'IN_MOVED_TO', 'IN_OPEN', 'IN_ALL_EVENTS', 'IN_MOVE', 'IN_CLOSE', 'IN_DONT_FOLLOW', 'IN_ONESHOT', 'IN_ONLYDIR', 'IN_NO_LOOP' ] def _needs_change(old, new): if old != new: if new == 'random': # Allow switch from '*' or not present to 'random' if old == '*': return True elif new is not None: return True return False def _render_tab(lst): ''' Takes a tab list structure and renders it to a list for applying it to a file ''' ret = [] for pre in lst['pre']: ret.append('{0}\n'.format(pre)) for cron in lst['crons']: ret.append('{0} {1} {2} {3}\n'.format(cron['path'], cron['mask'], cron['cmd'], TAG ) ) return ret def _get_incron_cmdstr(path): ''' Returns a format string, to be used to build an incrontab command. ''' return 'incrontab {0}'.format(path) def write_incron_file(user, path): ''' Writes the contents of a file to a user's incrontab CLI Example: .. code-block:: bash salt '*' incron.write_incron_file root /tmp/new_incron ''' return __salt__['cmd.retcode'](_get_incron_cmdstr(path), runas=user, python_shell=False) == 0 def write_incron_file_verbose(user, path): ''' Writes the contents of a file to a user's incrontab and return error message on error CLI Example: .. code-block:: bash salt '*' incron.write_incron_file_verbose root /tmp/new_incron ''' return __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False) def _write_incron_lines(user, lines): ''' Takes a list of lines to be committed to a user's incrontab and writes it ''' if user == 'system': ret = {} ret['retcode'] = _write_file(_INCRON_SYSTEM_TAB, 'salt', ''.join(lines)) return ret else: path = salt.utils.files.mkstemp() with salt.utils.files.fopen(path, 'wb') as fp_: fp_.writelines(salt.utils.data.encode(lines)) if __grains__['os_family'] == 'Solaris' and user != "root": __salt__['cmd.run']('chown {0} {1}'.format(user, path), python_shell=False) ret = __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False) os.remove(path) return ret def _write_file(folder, filename, data): ''' Writes a file to disk ''' path = os.path.join(folder, filename) if not os.path.exists(folder): msg = '{0} cannot be written. {1} does not exist'.format(filename, folder) log.error(msg) raise AttributeError(six.text_type(msg)) with salt.utils.files.fopen(path, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(data)) return 0 def _read_file(folder, filename): ''' Reads and returns the contents of a file ''' path = os.path.join(folder, filename) try: with salt.utils.files.fopen(path, 'rb') as contents: return salt.utils.data.decode(contents.readlines()) except (OSError, IOError): return '' def raw_system_incron(): ''' Return the contents of the system wide incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_system_incron ''' _contents = _read_file(_INCRON_SYSTEM_TAB, 'salt') log.debug('incron read_file contents: %s', _contents) return ''.join(_contents) def raw_incron(user): ''' Return the contents of the user's incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_incron root ''' if __grains__['os_family'] == 'Solaris': cmd = 'incrontab -l {0}'.format(user) else: cmd = 'incrontab -l -u {0}'.format(user) return __salt__['cmd.run_stdout'](cmd, rstrip=False, runas=user, python_shell=False) def list_tab(user): ''' Return the contents of the specified user's incrontab CLI Example: .. code-block:: bash salt '*' incron.list_tab root ''' if user == 'system': data = raw_system_incron() else: data = raw_incron(user) log.debug('incron user data %s', data) ret = {'crons': [], 'pre': [] } flag = False comment = None tag = '# Line managed by Salt, do not edit' for line in data.splitlines(): if line.endswith(tag): if len(line.split()) > 3: # Appears to be a standard incron line comps = line.split() path = comps[0] mask = comps[1] (cmd, comment) = ' '.join(comps[2:]).split(' # ') dat = {'path': path, 'mask': mask, 'cmd': cmd, 'comment': comment} ret['crons'].append(dat) comment = None else: ret['pre'].append(line) return ret # For consistency's sake ls = salt.utils.functools.alias_function(list_tab, 'ls') def rm_job(user, path, mask, cmd): ''' Remove a incron job for a specified user. If any of the day/time params are specified, the job will only be removed if the specified params match. CLI Example: .. code-block:: bash salt '*' incron.rm_job root /path ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) lst = list_tab(user) ret = 'absent' rm_ = None for ind in range(len(lst['crons'])): if rm_ is not None: break if path == lst['crons'][ind]['path']: if cmd == lst['crons'][ind]['cmd']: if mask == lst['crons'][ind]['mask']: rm_ = ind if rm_ is not None: lst['crons'].pop(rm_) ret = 'removed' comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] return ret rm = salt.utils.functools.alias_function(rm_job, 'rm')
saltstack/salt
salt/modules/incron.py
rm_job
python
def rm_job(user, path, mask, cmd): ''' Remove a incron job for a specified user. If any of the day/time params are specified, the job will only be removed if the specified params match. CLI Example: .. code-block:: bash salt '*' incron.rm_job root /path ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) lst = list_tab(user) ret = 'absent' rm_ = None for ind in range(len(lst['crons'])): if rm_ is not None: break if path == lst['crons'][ind]['path']: if cmd == lst['crons'][ind]['cmd']: if mask == lst['crons'][ind]['mask']: rm_ = ind if rm_ is not None: lst['crons'].pop(rm_) ret = 'removed' comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] return ret
Remove a incron job for a specified user. If any of the day/time params are specified, the job will only be removed if the specified params match. CLI Example: .. code-block:: bash salt '*' incron.rm_job root /path
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/incron.py#L279-L320
[ "def _render_tab(lst):\n '''\n Takes a tab list structure and renders it to a list for applying it to\n a file\n '''\n ret = []\n for pre in lst['pre']:\n ret.append('{0}\\n'.format(pre))\n for cron in lst['crons']:\n ret.append('{0} {1} {2} {3}\\n'.format(cron['path'],\n cron['mask'],\n cron['cmd'],\n TAG\n )\n )\n return ret\n", "def list_tab(user):\n '''\n Return the contents of the specified user's incrontab\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' incron.list_tab root\n '''\n if user == 'system':\n data = raw_system_incron()\n else:\n data = raw_incron(user)\n log.debug('incron user data %s', data)\n ret = {'crons': [],\n 'pre': []\n }\n flag = False\n comment = None\n tag = '# Line managed by Salt, do not edit'\n for line in data.splitlines():\n if line.endswith(tag):\n if len(line.split()) > 3:\n # Appears to be a standard incron line\n comps = line.split()\n path = comps[0]\n mask = comps[1]\n (cmd, comment) = ' '.join(comps[2:]).split(' # ')\n\n dat = {'path': path,\n 'mask': mask,\n 'cmd': cmd,\n 'comment': comment}\n ret['crons'].append(dat)\n comment = None\n else:\n ret['pre'].append(line)\n return ret\n", "def _write_incron_lines(user, lines):\n '''\n Takes a list of lines to be committed to a user's incrontab and writes it\n '''\n if user == 'system':\n ret = {}\n ret['retcode'] = _write_file(_INCRON_SYSTEM_TAB, 'salt', ''.join(lines))\n return ret\n else:\n path = salt.utils.files.mkstemp()\n with salt.utils.files.fopen(path, 'wb') as fp_:\n fp_.writelines(salt.utils.data.encode(lines))\n if __grains__['os_family'] == 'Solaris' and user != \"root\":\n __salt__['cmd.run']('chown {0} {1}'.format(user, path), python_shell=False)\n ret = __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False)\n os.remove(path)\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Work with incron ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import os # Import salt libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.data import salt.utils.files import salt.utils.functools import salt.utils.stringutils # Set up logging log = logging.getLogger(__name__) TAG = '# Line managed by Salt, do not edit' _INCRON_SYSTEM_TAB = '/etc/incron.d/' _MASK_TYPES = [ 'IN_ACCESS', 'IN_ATTRIB', 'IN_CLOSE_WRITE', 'IN_CLOSE_NOWRITE', 'IN_CREATE', 'IN_DELETE', 'IN_DELETE_SELF', 'IN_MODIFY', 'IN_MOVE_SELF', 'IN_MOVED_FROM', 'IN_MOVED_TO', 'IN_OPEN', 'IN_ALL_EVENTS', 'IN_MOVE', 'IN_CLOSE', 'IN_DONT_FOLLOW', 'IN_ONESHOT', 'IN_ONLYDIR', 'IN_NO_LOOP' ] def _needs_change(old, new): if old != new: if new == 'random': # Allow switch from '*' or not present to 'random' if old == '*': return True elif new is not None: return True return False def _render_tab(lst): ''' Takes a tab list structure and renders it to a list for applying it to a file ''' ret = [] for pre in lst['pre']: ret.append('{0}\n'.format(pre)) for cron in lst['crons']: ret.append('{0} {1} {2} {3}\n'.format(cron['path'], cron['mask'], cron['cmd'], TAG ) ) return ret def _get_incron_cmdstr(path): ''' Returns a format string, to be used to build an incrontab command. ''' return 'incrontab {0}'.format(path) def write_incron_file(user, path): ''' Writes the contents of a file to a user's incrontab CLI Example: .. code-block:: bash salt '*' incron.write_incron_file root /tmp/new_incron ''' return __salt__['cmd.retcode'](_get_incron_cmdstr(path), runas=user, python_shell=False) == 0 def write_incron_file_verbose(user, path): ''' Writes the contents of a file to a user's incrontab and return error message on error CLI Example: .. code-block:: bash salt '*' incron.write_incron_file_verbose root /tmp/new_incron ''' return __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False) def _write_incron_lines(user, lines): ''' Takes a list of lines to be committed to a user's incrontab and writes it ''' if user == 'system': ret = {} ret['retcode'] = _write_file(_INCRON_SYSTEM_TAB, 'salt', ''.join(lines)) return ret else: path = salt.utils.files.mkstemp() with salt.utils.files.fopen(path, 'wb') as fp_: fp_.writelines(salt.utils.data.encode(lines)) if __grains__['os_family'] == 'Solaris' and user != "root": __salt__['cmd.run']('chown {0} {1}'.format(user, path), python_shell=False) ret = __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False) os.remove(path) return ret def _write_file(folder, filename, data): ''' Writes a file to disk ''' path = os.path.join(folder, filename) if not os.path.exists(folder): msg = '{0} cannot be written. {1} does not exist'.format(filename, folder) log.error(msg) raise AttributeError(six.text_type(msg)) with salt.utils.files.fopen(path, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(data)) return 0 def _read_file(folder, filename): ''' Reads and returns the contents of a file ''' path = os.path.join(folder, filename) try: with salt.utils.files.fopen(path, 'rb') as contents: return salt.utils.data.decode(contents.readlines()) except (OSError, IOError): return '' def raw_system_incron(): ''' Return the contents of the system wide incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_system_incron ''' _contents = _read_file(_INCRON_SYSTEM_TAB, 'salt') log.debug('incron read_file contents: %s', _contents) return ''.join(_contents) def raw_incron(user): ''' Return the contents of the user's incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_incron root ''' if __grains__['os_family'] == 'Solaris': cmd = 'incrontab -l {0}'.format(user) else: cmd = 'incrontab -l -u {0}'.format(user) return __salt__['cmd.run_stdout'](cmd, rstrip=False, runas=user, python_shell=False) def list_tab(user): ''' Return the contents of the specified user's incrontab CLI Example: .. code-block:: bash salt '*' incron.list_tab root ''' if user == 'system': data = raw_system_incron() else: data = raw_incron(user) log.debug('incron user data %s', data) ret = {'crons': [], 'pre': [] } flag = False comment = None tag = '# Line managed by Salt, do not edit' for line in data.splitlines(): if line.endswith(tag): if len(line.split()) > 3: # Appears to be a standard incron line comps = line.split() path = comps[0] mask = comps[1] (cmd, comment) = ' '.join(comps[2:]).split(' # ') dat = {'path': path, 'mask': mask, 'cmd': cmd, 'comment': comment} ret['crons'].append(dat) comment = None else: ret['pre'].append(line) return ret # For consistency's sake ls = salt.utils.functools.alias_function(list_tab, 'ls') def set_job(user, path, mask, cmd): ''' Sets an incron job up for a specified user. CLI Example: .. code-block:: bash salt '*' incron.set_job root '/root' 'IN_MODIFY' 'echo "$$ $@ $# $% $&"' ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types for item in mask.split(','): if item not in _MASK_TYPES: return 'Invalid mask type: {0}' . format(item) updated = False arg_mask = mask.split(',') arg_mask.sort() lst = list_tab(user) updated_crons = [] # Look for existing incrons that have cmd, path and at least one of the MASKS # remove and replace with the one we're passed for item, cron in enumerate(lst['crons']): if path == cron['path']: if cron['cmd'] == cmd: cron_mask = cron['mask'].split(',') cron_mask.sort() if cron_mask == arg_mask: return 'present' if any([x in cron_mask for x in arg_mask]): updated = True else: updated_crons.append(cron) else: updated_crons.append(cron) else: updated_crons.append(cron) cron = {'cmd': cmd, 'path': path, 'mask': mask} updated_crons.append(cron) lst['crons'] = updated_crons comdat = _write_incron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] if updated: return 'updated' else: return 'new' rm = salt.utils.functools.alias_function(rm_job, 'rm')
saltstack/salt
salt/engines/ircbot.py
start
python
def start(nick, host, port=6667, username=None, password=None, channels=None, use_ssl=False, use_sasl=False, char='!', allow_hosts=False, allow_nicks=False, disable_query=True): ''' IRC Bot for interacting with salt. nick Nickname of the connected Bot. host irc server (example - chat.freenode.net). port irc port. Default: 6667 password password for authenticating. If not provided, user will not authenticate on the irc server. channels channels to join. use_ssl connect to server using ssl. Default: False use_sasl authenticate using sasl, instead of messaging NickServ. Default: False .. note:: This will allow the bot user to be fully authenticated before joining any channels char command character to look for. Default: ! allow_hosts hostmasks allowed to use commands on the bot. Default: False True to allow all False to allow none List of regexes to allow matching allow_nicks Nicks that are allowed to use commands on the bot. Default: False True to allow all False to allow none List of regexes to allow matching disable_query Disable commands from being sent through private queries. Require they be sent to a channel, so that all communication can be controlled by access to the channel. Default: True .. warning:: Unauthenticated Access to event stream This engine sends events calls to the event stream without authenticating them in salt. Authentication will need to be configured and enforced on the irc server or enforced in the irc channel. The engine only accepts commands from channels, so non authenticated users could be banned or quieted in the channel. /mode +q $~a # quiet all users who are not authenticated /mode +r # do not allow unauthenticated users into the channel It would also be possible to add a password to the irc channel, or only allow invited users to join. ''' client = IRCClient(nick, host, port, username, password, channels or [], use_ssl, use_sasl, char, allow_hosts, allow_nicks, disable_query) client.io_loop.start()
IRC Bot for interacting with salt. nick Nickname of the connected Bot. host irc server (example - chat.freenode.net). port irc port. Default: 6667 password password for authenticating. If not provided, user will not authenticate on the irc server. channels channels to join. use_ssl connect to server using ssl. Default: False use_sasl authenticate using sasl, instead of messaging NickServ. Default: False .. note:: This will allow the bot user to be fully authenticated before joining any channels char command character to look for. Default: ! allow_hosts hostmasks allowed to use commands on the bot. Default: False True to allow all False to allow none List of regexes to allow matching allow_nicks Nicks that are allowed to use commands on the bot. Default: False True to allow all False to allow none List of regexes to allow matching disable_query Disable commands from being sent through private queries. Require they be sent to a channel, so that all communication can be controlled by access to the channel. Default: True .. warning:: Unauthenticated Access to event stream This engine sends events calls to the event stream without authenticating them in salt. Authentication will need to be configured and enforced on the irc server or enforced in the irc channel. The engine only accepts commands from channels, so non authenticated users could be banned or quieted in the channel. /mode +q $~a # quiet all users who are not authenticated /mode +r # do not allow unauthenticated users into the channel It would also be possible to add a password to the irc channel, or only allow invited users to join.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/ircbot.py#L225-L285
null
# -*- coding: utf-8 -*- ''' IRC Bot engine .. versionadded:: 2017.7.0 Example Configuration .. code-block:: yaml engines: - ircbot: nick: <nick> username: <username> password: <password> host: chat.freenode.net port: 7000 channels: - salt-test - '##something' use_ssl: True use_sasl: True disable_query: True allow_hosts: - salt/engineer/.* allow_nicks: - gtmanfred Available commands on irc are: ping return pong echo <stuff> return <stuff> targeted at the user who sent the commands event <tag> [<extra>, <data>] fire event on the master or minion event stream with the tag `salt/engines/ircbot/<tag>` and a data object with a list of everything else sent in the message Example of usage .. code-block:: text 08:33:57 @gtmanfred > !ping 08:33:57 gtmanbot > gtmanfred: pong 08:34:02 @gtmanfred > !echo ping 08:34:02 gtmanbot > ping 08:34:17 @gtmanfred > !event test/tag/ircbot irc is useful 08:34:17 gtmanbot > gtmanfred: TaDa! .. code-block:: text [DEBUG ] Sending event: tag = salt/engines/ircbot/test/tag/ircbot; data = {'_stamp': '2016-11-28T14:34:16.633623', 'data': ['irc', 'is', 'useful']} ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libraries import base64 import logging import re import socket import ssl from collections import namedtuple import tornado.ioloop import tornado.iostream import logging log = logging.getLogger(__name__) # Import salt libraries import salt.utils.event # Import 3rd-party libs from salt.ext import six # Nothing listening here Event = namedtuple("Event", "source code line") PrivEvent = namedtuple("PrivEvent", "source nick user host code channel command line") class IRCClient(object): def __init__(self, nick, host, port=6667, username=None, password=None, channels=None, use_ssl=False, use_sasl=False, char='!', allow_hosts=False, allow_nicks=False, disable_query=True): self.nick = nick self.host = host self.port = port self.username = username or nick self.password = password self.channels = channels or [] self.ssl = use_ssl self.sasl = use_sasl self.char = char self.allow_hosts = allow_hosts self.allow_nicks = allow_nicks self.disable_query = disable_query self.io_loop = tornado.ioloop.IOLoop(make_current=False) self.io_loop.make_current() self._connect() def _connect(self): _sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) if self.ssl is True: self._stream = tornado.iostream.SSLIOStream(_sock, ssl_options={'cert_reqs': ssl.CERT_NONE}) else: self._stream = tornado.iostream.IOStream(_sock) self._stream.set_close_callback(self.on_closed) self._stream.connect((self.host, self.port), self.on_connect) def read_messages(self): self._stream.read_until('\r\n', self._message) @staticmethod def _event(line): log.debug('Received: %s', line) search = re.match('^(?:(?P<source>:[^ ]+) )?(?P<code>[^ ]+)(?: (?P<line>.*))?$', line) source, code, line = search.group('source'), search.group('code'), search.group('line') return Event(source, code, line) def _allow_host(self, host): if isinstance(self.allow_hosts, bool): return self.allow_hosts else: return any([re.match(match, host) for match in self.allow_hosts]) def _allow_nick(self, nick): if isinstance(self.allow_nicks, bool): return self.allow_nicks else: return any([re.match(match, nick) for match in self.allow_nicks]) def _privmsg(self, event): search = re.match('^:(?P<nick>[^!]+)!(?P<user>[^@]+)@(?P<host>.*)$', event.source) nick, user, host = search.group('nick'), search.group('user'), search.group('host') search = re.match('^(?P<channel>[^ ]+) :(?:{0}(?P<command>[^ ]+)(?: (?P<line>.*))?)?$'.format(self.char), event.line) if search: channel, command, line = search.group('channel'), search.group('command'), search.group('line') if self.disable_query is True and not channel.startswith('#'): return if channel == self.nick: channel = nick privevent = PrivEvent(event.source, nick, user, host, event.code, channel, command, line) if (self._allow_nick(nick) or self._allow_host(host)) and hasattr(self, '_command_{0}'.format(command)): getattr(self, '_command_{0}'.format(command))(privevent) def _command_echo(self, event): message = 'PRIVMSG {0} :{1}'.format(event.channel, event.line) self.send_message(message) def _command_ping(self, event): message = 'PRIVMSG {0} :{1}: pong'.format(event.channel, event.nick) self.send_message(message) def _command_event(self, event): if __opts__.get('__role') == 'master': fire_master = salt.utils.event.get_master_event(__opts__, __opts__['sock_dir']).fire_event else: fire_master = None def fire(tag, msg): ''' How to fire the event ''' if fire_master: fire_master(msg, tag) else: __salt__['event.send'](tag, msg) args = event.line.split(' ') tag = args[0] if len(args) > 1: payload = {'data': args[1:]} else: payload = {'data': []} fire('salt/engines/ircbot/' + tag, payload) message = 'PRIVMSG {0} :{1}: TaDa!'.format(event.channel, event.nick) self.send_message(message) def _message(self, raw): raw = raw.rstrip(b'\r\n').decode('utf-8') event = self._event(raw) if event.code == "PING": tornado.ioloop.IOLoop.current().spawn_callback(self.send_message, "PONG {0}".format(event.line)) elif event.code == 'PRIVMSG': tornado.ioloop.IOLoop.current().spawn_callback(self._privmsg, event) self.read_messages() def join_channel(self, channel): if not channel.startswith('#'): channel = '#' + channel self.send_message('JOIN {0}'.format(channel)) def on_connect(self): logging.info("on_connect") if self.sasl is True: self.send_message('CAP REQ :sasl') self.send_message('NICK {0}'.format(self.nick)) self.send_message('USER saltstack 0 * :saltstack') if self.password: if self.sasl is True: authstring = base64.b64encode("{0}\x00{0}\x00{1}".format(self.username, self.password).encode()) self.send_message('AUTHENTICATE PLAIN') self.send_message('AUTHENTICATE {0}'.format(authstring)) self.send_message('CAP END') else: self.send_message('PRIVMSG NickServ :IDENTIFY {0} {1}'.format(self.username, self.password)) for channel in self.channels: self.join_channel(channel) self.read_messages() def on_closed(self): logging.info("on_closed") def send_message(self, line): if isinstance(line, six.string_types): line = line.encode('utf-8') log.debug("Sending: %s", line) self._stream.write(line + b'\r\n')
saltstack/salt
salt/modules/suse_apache.py
check_mod_enabled
python
def check_mod_enabled(mod): ''' Checks to see if the specific apache mod is enabled. This will only be functional on operating systems that support `a2enmod -l` to list the enabled mods. CLI Example: .. code-block:: bash salt '*' apache.check_mod_enabled status ''' if mod.endswith('.load') or mod.endswith('.conf'): mod_name = mod[:-5] else: mod_name = mod cmd = 'a2enmod -l' try: active_mods = __salt__['cmd.run'](cmd, python_shell=False).split(' ') except Exception as e: return e return mod_name in active_mods
Checks to see if the specific apache mod is enabled. This will only be functional on operating systems that support `a2enmod -l` to list the enabled mods. CLI Example: .. code-block:: bash salt '*' apache.check_mod_enabled status
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/suse_apache.py#L31-L55
null
# -*- coding: utf-8 -*- ''' Support for Apache Please note: The functions in here are SUSE-specific. Placing them in this separate file will allow them to load only on SUSE systems, while still loading under the ``apache`` namespace. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging # Import salt libs import salt.utils.path log = logging.getLogger(__name__) __virtualname__ = 'apache' def __virtual__(): ''' Only load the module if apache is installed. ''' if salt.utils.path.which('apache2ctl') and __grains__['os_family'] == 'Suse': return __virtualname__ return (False, 'apache execution module not loaded: apache not installed.') def a2enmod(mod): ''' Runs a2enmod for the given mod. CLI Example: .. code-block:: bash salt '*' apache.a2enmod vhost_alias ''' ret = {} command = ['a2enmod', mod] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Enable Mod' ret['Mod'] = mod if status == 1: ret['Status'] = 'Mod {0} Not found'.format(mod) elif status == 0: ret['Status'] = 'Mod {0} enabled'.format(mod) else: ret['Status'] = status return ret def a2dismod(mod): ''' Runs a2dismod for the given mod. CLI Example: .. code-block:: bash salt '*' apache.a2dismod vhost_alias ''' ret = {} command = ['a2dismod', mod] try: status = __salt__['cmd.retcode'](command, python_shell=False) except Exception as e: return e ret['Name'] = 'Apache2 Disable Mod' ret['Mod'] = mod if status == 256: ret['Status'] = 'Mod {0} Not found'.format(mod) elif status == 0: ret['Status'] = 'Mod {0} disabled'.format(mod) else: ret['Status'] = status return ret
saltstack/salt
salt/modules/boto_kms.py
create_alias
python
def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): ''' Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.create_alias(alias_name, target_key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L80-L98
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon KMS .. versionadded:: 2015.8.0 :configuration: This module accepts explicit kms credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at:: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file:: kms.keyid: GKTADJGHEIQSXMKKRBJ08H kms.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration:: kms.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import Salt libs import salt.utils.compat import salt.utils.odict as odict import salt.serializers.json import salt.utils.versions log = logging.getLogger(__name__) # Import third party libs try: # pylint: disable=unused-import import boto import boto.kms # pylint: enable=unused-import logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except (ImportError, AttributeError): HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( boto_ver='2.38.0', check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'kms', pack=__salt__) def create_grant(key_id, grantee_principal, retiring_principal=None, operations=None, constraints=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Adds a grant to a key to specify who can access the key and under what conditions. CLI example:: salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: r['grant'] = conn.create_grant( key_id, grantee_principal, retiring_principal=retiring_principal, operations=operations, constraints=constraints, grant_tokens=grant_tokens ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def create_key(policy=None, description=None, key_usage=None, region=None, key=None, keyid=None, profile=None): ''' Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} _policy = salt.serializers.json.serialize(policy) try: key_metadata = conn.create_key( _policy, description=description, key_usage=key_usage ) r['key_metadata'] = key_metadata['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: plaintext = conn.decrypt( ciphertext_blob, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['plaintext'] = plaintext['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def key_exists(key_id, region=None, key=None, keyid=None, profile=None): ''' Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['result'] = True except boto.exception.BotoServerError as e: if isinstance(e, boto.kms.exceptions.NotFoundException): r['result'] = False return r r['error'] = __utils__['boto.get_error'](e) return r def _get_key_id(alias, region=None, key=None, keyid=None, profile=None): ''' From an alias, get a key_id. ''' key_metadata = describe_key( alias, region, key, keyid, profile )['key_metadata'] return key_metadata['KeyId'] def describe_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Get detailed information about a key. CLI example:: salt myminion boto_kms.describe_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['key_metadata'] = key['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def disable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def disable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.disable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as enabled. CLI example:: salt myminion boto_kms.enable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.enable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ciphertext = conn.encrypt( key_id, plaintext, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['ciphertext'] = ciphertext['CiphertextBlob'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key_without_plaintext( key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None ): ''' Generate a secure data key without a plaintext copy of the key. CLI example:: salt myminion boto_kms.generate_data_key_without_plaintext 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key_without_plaintext( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_random(number_of_bytes=None, region=None, key=None, keyid=None, profile=None): ''' Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: random = conn.generate_random(number_of_bytes) r['random'] = random['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_policy = conn.get_key_policy(key_id, policy_name) r['key_policy'] = salt.serializers.json.deserialize( key_policy['Policy'], object_pairs_hook=odict.OrderedDict ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_rotation_status(key_id, region=None, key=None, keyid=None, profile=None): ''' Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_rotation_status = conn.get_key_rotation_status(key_id) r['result'] = key_rotation_status['KeyRotationEnabled'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_grants(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: _grants = [] next_marker = None while True: grants = conn.list_grants( key_id, limit=limit, marker=next_marker ) for grant in grants['Grants']: _grants.append(grant) if 'NextMarker' in grants: next_marker = grants['NextMarker'] else: break r['grants'] = _grants except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_key_policies(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: key_policies = conn.list_key_policies( key_id, limit=limit, marker=marker ) # TODO: handle limit, marker and truncation automatically. r['key_policies'] = key_policies['PolicyNames'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def put_key_policy(key_id, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.put_key_policy(key_id, policy_name, salt.serializers.json.serialize(policy)) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context=None, destination_encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Reencrypt encrypted data with a new master key. CLI example:: salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}' ''' conn = _get_conn( region=region, key=key, keyid=keyid, profile=profile ) r = {} try: ciphertext = conn.re_encrypt( ciphertext_blob, destination_key_id, source_encryption_context, destination_encryption_context, grant_tokens ) r['ciphertext'] = ciphertext except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None, profile=None): ''' Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j... ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: conn.revoke_grant(key_id, grant_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def update_key_description(key_id, description, region=None, key=None, keyid=None, profile=None): ''' Update a key's description. CLI example:: salt myminion boto_kms.update_key_description 'alias/mykey' 'My key' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.update_key_description(key_id, description) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
saltstack/salt
salt/modules/boto_kms.py
create_grant
python
def create_grant(key_id, grantee_principal, retiring_principal=None, operations=None, constraints=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Adds a grant to a key to specify who can access the key and under what conditions. CLI example:: salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: r['grant'] = conn.create_grant( key_id, grantee_principal, retiring_principal=retiring_principal, operations=operations, constraints=constraints, grant_tokens=grant_tokens ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r
Adds a grant to a key to specify who can access the key and under what conditions. CLI example:: salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L101-L128
[ "def _get_key_id(alias, region=None, key=None, keyid=None, profile=None):\n '''\n From an alias, get a key_id.\n '''\n key_metadata = describe_key(\n alias, region, key, keyid, profile\n )['key_metadata']\n return key_metadata['KeyId']\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon KMS .. versionadded:: 2015.8.0 :configuration: This module accepts explicit kms credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at:: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file:: kms.keyid: GKTADJGHEIQSXMKKRBJ08H kms.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration:: kms.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import Salt libs import salt.utils.compat import salt.utils.odict as odict import salt.serializers.json import salt.utils.versions log = logging.getLogger(__name__) # Import third party libs try: # pylint: disable=unused-import import boto import boto.kms # pylint: enable=unused-import logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except (ImportError, AttributeError): HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( boto_ver='2.38.0', check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'kms', pack=__salt__) def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): ''' Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.create_alias(alias_name, target_key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def create_key(policy=None, description=None, key_usage=None, region=None, key=None, keyid=None, profile=None): ''' Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} _policy = salt.serializers.json.serialize(policy) try: key_metadata = conn.create_key( _policy, description=description, key_usage=key_usage ) r['key_metadata'] = key_metadata['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: plaintext = conn.decrypt( ciphertext_blob, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['plaintext'] = plaintext['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def key_exists(key_id, region=None, key=None, keyid=None, profile=None): ''' Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['result'] = True except boto.exception.BotoServerError as e: if isinstance(e, boto.kms.exceptions.NotFoundException): r['result'] = False return r r['error'] = __utils__['boto.get_error'](e) return r def _get_key_id(alias, region=None, key=None, keyid=None, profile=None): ''' From an alias, get a key_id. ''' key_metadata = describe_key( alias, region, key, keyid, profile )['key_metadata'] return key_metadata['KeyId'] def describe_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Get detailed information about a key. CLI example:: salt myminion boto_kms.describe_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['key_metadata'] = key['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def disable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def disable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.disable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as enabled. CLI example:: salt myminion boto_kms.enable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.enable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ciphertext = conn.encrypt( key_id, plaintext, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['ciphertext'] = ciphertext['CiphertextBlob'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key_without_plaintext( key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None ): ''' Generate a secure data key without a plaintext copy of the key. CLI example:: salt myminion boto_kms.generate_data_key_without_plaintext 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key_without_plaintext( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_random(number_of_bytes=None, region=None, key=None, keyid=None, profile=None): ''' Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: random = conn.generate_random(number_of_bytes) r['random'] = random['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_policy = conn.get_key_policy(key_id, policy_name) r['key_policy'] = salt.serializers.json.deserialize( key_policy['Policy'], object_pairs_hook=odict.OrderedDict ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_rotation_status(key_id, region=None, key=None, keyid=None, profile=None): ''' Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_rotation_status = conn.get_key_rotation_status(key_id) r['result'] = key_rotation_status['KeyRotationEnabled'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_grants(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: _grants = [] next_marker = None while True: grants = conn.list_grants( key_id, limit=limit, marker=next_marker ) for grant in grants['Grants']: _grants.append(grant) if 'NextMarker' in grants: next_marker = grants['NextMarker'] else: break r['grants'] = _grants except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_key_policies(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: key_policies = conn.list_key_policies( key_id, limit=limit, marker=marker ) # TODO: handle limit, marker and truncation automatically. r['key_policies'] = key_policies['PolicyNames'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def put_key_policy(key_id, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.put_key_policy(key_id, policy_name, salt.serializers.json.serialize(policy)) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context=None, destination_encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Reencrypt encrypted data with a new master key. CLI example:: salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}' ''' conn = _get_conn( region=region, key=key, keyid=keyid, profile=profile ) r = {} try: ciphertext = conn.re_encrypt( ciphertext_blob, destination_key_id, source_encryption_context, destination_encryption_context, grant_tokens ) r['ciphertext'] = ciphertext except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None, profile=None): ''' Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j... ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: conn.revoke_grant(key_id, grant_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def update_key_description(key_id, description, region=None, key=None, keyid=None, profile=None): ''' Update a key's description. CLI example:: salt myminion boto_kms.update_key_description 'alias/mykey' 'My key' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.update_key_description(key_id, description) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
saltstack/salt
salt/modules/boto_kms.py
create_key
python
def create_key(policy=None, description=None, key_usage=None, region=None, key=None, keyid=None, profile=None): ''' Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} _policy = salt.serializers.json.serialize(policy) try: key_metadata = conn.create_key( _policy, description=description, key_usage=key_usage ) r['key_metadata'] = key_metadata['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r
Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L131-L153
[ "def serialize(obj, **options):\n '''\n Serialize Python data to JSON.\n\n :param obj: the data structure to serialize\n :param options: options given to lower json/simplejson module.\n '''\n\n try:\n if 'fp' in options:\n return salt.utils.json.dump(obj, _json_module=_json, **options)\n else:\n return salt.utils.json.dumps(obj, _json_module=_json, **options)\n except Exception as error:\n raise SerializationError(error)\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon KMS .. versionadded:: 2015.8.0 :configuration: This module accepts explicit kms credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at:: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file:: kms.keyid: GKTADJGHEIQSXMKKRBJ08H kms.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration:: kms.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import Salt libs import salt.utils.compat import salt.utils.odict as odict import salt.serializers.json import salt.utils.versions log = logging.getLogger(__name__) # Import third party libs try: # pylint: disable=unused-import import boto import boto.kms # pylint: enable=unused-import logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except (ImportError, AttributeError): HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( boto_ver='2.38.0', check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'kms', pack=__salt__) def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): ''' Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.create_alias(alias_name, target_key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def create_grant(key_id, grantee_principal, retiring_principal=None, operations=None, constraints=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Adds a grant to a key to specify who can access the key and under what conditions. CLI example:: salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: r['grant'] = conn.create_grant( key_id, grantee_principal, retiring_principal=retiring_principal, operations=operations, constraints=constraints, grant_tokens=grant_tokens ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: plaintext = conn.decrypt( ciphertext_blob, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['plaintext'] = plaintext['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def key_exists(key_id, region=None, key=None, keyid=None, profile=None): ''' Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['result'] = True except boto.exception.BotoServerError as e: if isinstance(e, boto.kms.exceptions.NotFoundException): r['result'] = False return r r['error'] = __utils__['boto.get_error'](e) return r def _get_key_id(alias, region=None, key=None, keyid=None, profile=None): ''' From an alias, get a key_id. ''' key_metadata = describe_key( alias, region, key, keyid, profile )['key_metadata'] return key_metadata['KeyId'] def describe_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Get detailed information about a key. CLI example:: salt myminion boto_kms.describe_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['key_metadata'] = key['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def disable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def disable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.disable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as enabled. CLI example:: salt myminion boto_kms.enable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.enable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ciphertext = conn.encrypt( key_id, plaintext, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['ciphertext'] = ciphertext['CiphertextBlob'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key_without_plaintext( key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None ): ''' Generate a secure data key without a plaintext copy of the key. CLI example:: salt myminion boto_kms.generate_data_key_without_plaintext 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key_without_plaintext( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_random(number_of_bytes=None, region=None, key=None, keyid=None, profile=None): ''' Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: random = conn.generate_random(number_of_bytes) r['random'] = random['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_policy = conn.get_key_policy(key_id, policy_name) r['key_policy'] = salt.serializers.json.deserialize( key_policy['Policy'], object_pairs_hook=odict.OrderedDict ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_rotation_status(key_id, region=None, key=None, keyid=None, profile=None): ''' Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_rotation_status = conn.get_key_rotation_status(key_id) r['result'] = key_rotation_status['KeyRotationEnabled'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_grants(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: _grants = [] next_marker = None while True: grants = conn.list_grants( key_id, limit=limit, marker=next_marker ) for grant in grants['Grants']: _grants.append(grant) if 'NextMarker' in grants: next_marker = grants['NextMarker'] else: break r['grants'] = _grants except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_key_policies(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: key_policies = conn.list_key_policies( key_id, limit=limit, marker=marker ) # TODO: handle limit, marker and truncation automatically. r['key_policies'] = key_policies['PolicyNames'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def put_key_policy(key_id, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.put_key_policy(key_id, policy_name, salt.serializers.json.serialize(policy)) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context=None, destination_encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Reencrypt encrypted data with a new master key. CLI example:: salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}' ''' conn = _get_conn( region=region, key=key, keyid=keyid, profile=profile ) r = {} try: ciphertext = conn.re_encrypt( ciphertext_blob, destination_key_id, source_encryption_context, destination_encryption_context, grant_tokens ) r['ciphertext'] = ciphertext except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None, profile=None): ''' Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j... ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: conn.revoke_grant(key_id, grant_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def update_key_description(key_id, description, region=None, key=None, keyid=None, profile=None): ''' Update a key's description. CLI example:: salt myminion boto_kms.update_key_description 'alias/mykey' 'My key' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.update_key_description(key_id, description) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
saltstack/salt
salt/modules/boto_kms.py
decrypt
python
def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: plaintext = conn.decrypt( ciphertext_blob, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['plaintext'] = plaintext['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r
Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L156-L177
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon KMS .. versionadded:: 2015.8.0 :configuration: This module accepts explicit kms credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at:: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file:: kms.keyid: GKTADJGHEIQSXMKKRBJ08H kms.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration:: kms.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import Salt libs import salt.utils.compat import salt.utils.odict as odict import salt.serializers.json import salt.utils.versions log = logging.getLogger(__name__) # Import third party libs try: # pylint: disable=unused-import import boto import boto.kms # pylint: enable=unused-import logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except (ImportError, AttributeError): HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( boto_ver='2.38.0', check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'kms', pack=__salt__) def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): ''' Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.create_alias(alias_name, target_key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def create_grant(key_id, grantee_principal, retiring_principal=None, operations=None, constraints=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Adds a grant to a key to specify who can access the key and under what conditions. CLI example:: salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: r['grant'] = conn.create_grant( key_id, grantee_principal, retiring_principal=retiring_principal, operations=operations, constraints=constraints, grant_tokens=grant_tokens ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def create_key(policy=None, description=None, key_usage=None, region=None, key=None, keyid=None, profile=None): ''' Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} _policy = salt.serializers.json.serialize(policy) try: key_metadata = conn.create_key( _policy, description=description, key_usage=key_usage ) r['key_metadata'] = key_metadata['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def key_exists(key_id, region=None, key=None, keyid=None, profile=None): ''' Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['result'] = True except boto.exception.BotoServerError as e: if isinstance(e, boto.kms.exceptions.NotFoundException): r['result'] = False return r r['error'] = __utils__['boto.get_error'](e) return r def _get_key_id(alias, region=None, key=None, keyid=None, profile=None): ''' From an alias, get a key_id. ''' key_metadata = describe_key( alias, region, key, keyid, profile )['key_metadata'] return key_metadata['KeyId'] def describe_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Get detailed information about a key. CLI example:: salt myminion boto_kms.describe_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['key_metadata'] = key['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def disable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def disable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.disable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as enabled. CLI example:: salt myminion boto_kms.enable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.enable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ciphertext = conn.encrypt( key_id, plaintext, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['ciphertext'] = ciphertext['CiphertextBlob'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key_without_plaintext( key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None ): ''' Generate a secure data key without a plaintext copy of the key. CLI example:: salt myminion boto_kms.generate_data_key_without_plaintext 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key_without_plaintext( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_random(number_of_bytes=None, region=None, key=None, keyid=None, profile=None): ''' Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: random = conn.generate_random(number_of_bytes) r['random'] = random['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_policy = conn.get_key_policy(key_id, policy_name) r['key_policy'] = salt.serializers.json.deserialize( key_policy['Policy'], object_pairs_hook=odict.OrderedDict ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_rotation_status(key_id, region=None, key=None, keyid=None, profile=None): ''' Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_rotation_status = conn.get_key_rotation_status(key_id) r['result'] = key_rotation_status['KeyRotationEnabled'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_grants(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: _grants = [] next_marker = None while True: grants = conn.list_grants( key_id, limit=limit, marker=next_marker ) for grant in grants['Grants']: _grants.append(grant) if 'NextMarker' in grants: next_marker = grants['NextMarker'] else: break r['grants'] = _grants except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_key_policies(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: key_policies = conn.list_key_policies( key_id, limit=limit, marker=marker ) # TODO: handle limit, marker and truncation automatically. r['key_policies'] = key_policies['PolicyNames'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def put_key_policy(key_id, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.put_key_policy(key_id, policy_name, salt.serializers.json.serialize(policy)) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context=None, destination_encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Reencrypt encrypted data with a new master key. CLI example:: salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}' ''' conn = _get_conn( region=region, key=key, keyid=keyid, profile=profile ) r = {} try: ciphertext = conn.re_encrypt( ciphertext_blob, destination_key_id, source_encryption_context, destination_encryption_context, grant_tokens ) r['ciphertext'] = ciphertext except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None, profile=None): ''' Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j... ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: conn.revoke_grant(key_id, grant_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def update_key_description(key_id, description, region=None, key=None, keyid=None, profile=None): ''' Update a key's description. CLI example:: salt myminion boto_kms.update_key_description 'alias/mykey' 'My key' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.update_key_description(key_id, description) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
saltstack/salt
salt/modules/boto_kms.py
key_exists
python
def key_exists(key_id, region=None, key=None, keyid=None, profile=None): ''' Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['result'] = True except boto.exception.BotoServerError as e: if isinstance(e, boto.kms.exceptions.NotFoundException): r['result'] = False return r r['error'] = __utils__['boto.get_error'](e) return r
Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L180-L200
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon KMS .. versionadded:: 2015.8.0 :configuration: This module accepts explicit kms credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at:: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file:: kms.keyid: GKTADJGHEIQSXMKKRBJ08H kms.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration:: kms.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import Salt libs import salt.utils.compat import salt.utils.odict as odict import salt.serializers.json import salt.utils.versions log = logging.getLogger(__name__) # Import third party libs try: # pylint: disable=unused-import import boto import boto.kms # pylint: enable=unused-import logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except (ImportError, AttributeError): HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( boto_ver='2.38.0', check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'kms', pack=__salt__) def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): ''' Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.create_alias(alias_name, target_key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def create_grant(key_id, grantee_principal, retiring_principal=None, operations=None, constraints=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Adds a grant to a key to specify who can access the key and under what conditions. CLI example:: salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: r['grant'] = conn.create_grant( key_id, grantee_principal, retiring_principal=retiring_principal, operations=operations, constraints=constraints, grant_tokens=grant_tokens ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def create_key(policy=None, description=None, key_usage=None, region=None, key=None, keyid=None, profile=None): ''' Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} _policy = salt.serializers.json.serialize(policy) try: key_metadata = conn.create_key( _policy, description=description, key_usage=key_usage ) r['key_metadata'] = key_metadata['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: plaintext = conn.decrypt( ciphertext_blob, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['plaintext'] = plaintext['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def _get_key_id(alias, region=None, key=None, keyid=None, profile=None): ''' From an alias, get a key_id. ''' key_metadata = describe_key( alias, region, key, keyid, profile )['key_metadata'] return key_metadata['KeyId'] def describe_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Get detailed information about a key. CLI example:: salt myminion boto_kms.describe_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['key_metadata'] = key['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def disable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def disable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.disable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as enabled. CLI example:: salt myminion boto_kms.enable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.enable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ciphertext = conn.encrypt( key_id, plaintext, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['ciphertext'] = ciphertext['CiphertextBlob'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key_without_plaintext( key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None ): ''' Generate a secure data key without a plaintext copy of the key. CLI example:: salt myminion boto_kms.generate_data_key_without_plaintext 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key_without_plaintext( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_random(number_of_bytes=None, region=None, key=None, keyid=None, profile=None): ''' Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: random = conn.generate_random(number_of_bytes) r['random'] = random['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_policy = conn.get_key_policy(key_id, policy_name) r['key_policy'] = salt.serializers.json.deserialize( key_policy['Policy'], object_pairs_hook=odict.OrderedDict ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_rotation_status(key_id, region=None, key=None, keyid=None, profile=None): ''' Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_rotation_status = conn.get_key_rotation_status(key_id) r['result'] = key_rotation_status['KeyRotationEnabled'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_grants(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: _grants = [] next_marker = None while True: grants = conn.list_grants( key_id, limit=limit, marker=next_marker ) for grant in grants['Grants']: _grants.append(grant) if 'NextMarker' in grants: next_marker = grants['NextMarker'] else: break r['grants'] = _grants except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_key_policies(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: key_policies = conn.list_key_policies( key_id, limit=limit, marker=marker ) # TODO: handle limit, marker and truncation automatically. r['key_policies'] = key_policies['PolicyNames'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def put_key_policy(key_id, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.put_key_policy(key_id, policy_name, salt.serializers.json.serialize(policy)) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context=None, destination_encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Reencrypt encrypted data with a new master key. CLI example:: salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}' ''' conn = _get_conn( region=region, key=key, keyid=keyid, profile=profile ) r = {} try: ciphertext = conn.re_encrypt( ciphertext_blob, destination_key_id, source_encryption_context, destination_encryption_context, grant_tokens ) r['ciphertext'] = ciphertext except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None, profile=None): ''' Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j... ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: conn.revoke_grant(key_id, grant_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def update_key_description(key_id, description, region=None, key=None, keyid=None, profile=None): ''' Update a key's description. CLI example:: salt myminion boto_kms.update_key_description 'alias/mykey' 'My key' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.update_key_description(key_id, description) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
saltstack/salt
salt/modules/boto_kms.py
_get_key_id
python
def _get_key_id(alias, region=None, key=None, keyid=None, profile=None): ''' From an alias, get a key_id. ''' key_metadata = describe_key( alias, region, key, keyid, profile )['key_metadata'] return key_metadata['KeyId']
From an alias, get a key_id.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L203-L210
[ "def describe_key(key_id, region=None, key=None, keyid=None, profile=None):\n '''\n Get detailed information about a key.\n\n CLI example::\n\n salt myminion boto_kms.describe_key 'alias/mykey'\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n r = {}\n try:\n key = conn.describe_key(key_id)\n # TODO: add to context cache\n r['key_metadata'] = key['KeyMetadata']\n except boto.exception.BotoServerError as e:\n r['error'] = __utils__['boto.get_error'](e)\n return r\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon KMS .. versionadded:: 2015.8.0 :configuration: This module accepts explicit kms credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at:: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file:: kms.keyid: GKTADJGHEIQSXMKKRBJ08H kms.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration:: kms.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import Salt libs import salt.utils.compat import salt.utils.odict as odict import salt.serializers.json import salt.utils.versions log = logging.getLogger(__name__) # Import third party libs try: # pylint: disable=unused-import import boto import boto.kms # pylint: enable=unused-import logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except (ImportError, AttributeError): HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( boto_ver='2.38.0', check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'kms', pack=__salt__) def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): ''' Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.create_alias(alias_name, target_key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def create_grant(key_id, grantee_principal, retiring_principal=None, operations=None, constraints=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Adds a grant to a key to specify who can access the key and under what conditions. CLI example:: salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: r['grant'] = conn.create_grant( key_id, grantee_principal, retiring_principal=retiring_principal, operations=operations, constraints=constraints, grant_tokens=grant_tokens ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def create_key(policy=None, description=None, key_usage=None, region=None, key=None, keyid=None, profile=None): ''' Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} _policy = salt.serializers.json.serialize(policy) try: key_metadata = conn.create_key( _policy, description=description, key_usage=key_usage ) r['key_metadata'] = key_metadata['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: plaintext = conn.decrypt( ciphertext_blob, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['plaintext'] = plaintext['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def key_exists(key_id, region=None, key=None, keyid=None, profile=None): ''' Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['result'] = True except boto.exception.BotoServerError as e: if isinstance(e, boto.kms.exceptions.NotFoundException): r['result'] = False return r r['error'] = __utils__['boto.get_error'](e) return r def describe_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Get detailed information about a key. CLI example:: salt myminion boto_kms.describe_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['key_metadata'] = key['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def disable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def disable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.disable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as enabled. CLI example:: salt myminion boto_kms.enable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.enable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ciphertext = conn.encrypt( key_id, plaintext, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['ciphertext'] = ciphertext['CiphertextBlob'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key_without_plaintext( key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None ): ''' Generate a secure data key without a plaintext copy of the key. CLI example:: salt myminion boto_kms.generate_data_key_without_plaintext 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key_without_plaintext( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_random(number_of_bytes=None, region=None, key=None, keyid=None, profile=None): ''' Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: random = conn.generate_random(number_of_bytes) r['random'] = random['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_policy = conn.get_key_policy(key_id, policy_name) r['key_policy'] = salt.serializers.json.deserialize( key_policy['Policy'], object_pairs_hook=odict.OrderedDict ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_rotation_status(key_id, region=None, key=None, keyid=None, profile=None): ''' Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_rotation_status = conn.get_key_rotation_status(key_id) r['result'] = key_rotation_status['KeyRotationEnabled'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_grants(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: _grants = [] next_marker = None while True: grants = conn.list_grants( key_id, limit=limit, marker=next_marker ) for grant in grants['Grants']: _grants.append(grant) if 'NextMarker' in grants: next_marker = grants['NextMarker'] else: break r['grants'] = _grants except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_key_policies(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: key_policies = conn.list_key_policies( key_id, limit=limit, marker=marker ) # TODO: handle limit, marker and truncation automatically. r['key_policies'] = key_policies['PolicyNames'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def put_key_policy(key_id, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.put_key_policy(key_id, policy_name, salt.serializers.json.serialize(policy)) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context=None, destination_encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Reencrypt encrypted data with a new master key. CLI example:: salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}' ''' conn = _get_conn( region=region, key=key, keyid=keyid, profile=profile ) r = {} try: ciphertext = conn.re_encrypt( ciphertext_blob, destination_key_id, source_encryption_context, destination_encryption_context, grant_tokens ) r['ciphertext'] = ciphertext except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None, profile=None): ''' Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j... ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: conn.revoke_grant(key_id, grant_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def update_key_description(key_id, description, region=None, key=None, keyid=None, profile=None): ''' Update a key's description. CLI example:: salt myminion boto_kms.update_key_description 'alias/mykey' 'My key' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.update_key_description(key_id, description) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
saltstack/salt
salt/modules/boto_kms.py
disable_key
python
def disable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L233-L250
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon KMS .. versionadded:: 2015.8.0 :configuration: This module accepts explicit kms credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at:: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file:: kms.keyid: GKTADJGHEIQSXMKKRBJ08H kms.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration:: kms.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import Salt libs import salt.utils.compat import salt.utils.odict as odict import salt.serializers.json import salt.utils.versions log = logging.getLogger(__name__) # Import third party libs try: # pylint: disable=unused-import import boto import boto.kms # pylint: enable=unused-import logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except (ImportError, AttributeError): HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( boto_ver='2.38.0', check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'kms', pack=__salt__) def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): ''' Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.create_alias(alias_name, target_key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def create_grant(key_id, grantee_principal, retiring_principal=None, operations=None, constraints=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Adds a grant to a key to specify who can access the key and under what conditions. CLI example:: salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: r['grant'] = conn.create_grant( key_id, grantee_principal, retiring_principal=retiring_principal, operations=operations, constraints=constraints, grant_tokens=grant_tokens ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def create_key(policy=None, description=None, key_usage=None, region=None, key=None, keyid=None, profile=None): ''' Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} _policy = salt.serializers.json.serialize(policy) try: key_metadata = conn.create_key( _policy, description=description, key_usage=key_usage ) r['key_metadata'] = key_metadata['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: plaintext = conn.decrypt( ciphertext_blob, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['plaintext'] = plaintext['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def key_exists(key_id, region=None, key=None, keyid=None, profile=None): ''' Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['result'] = True except boto.exception.BotoServerError as e: if isinstance(e, boto.kms.exceptions.NotFoundException): r['result'] = False return r r['error'] = __utils__['boto.get_error'](e) return r def _get_key_id(alias, region=None, key=None, keyid=None, profile=None): ''' From an alias, get a key_id. ''' key_metadata = describe_key( alias, region, key, keyid, profile )['key_metadata'] return key_metadata['KeyId'] def describe_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Get detailed information about a key. CLI example:: salt myminion boto_kms.describe_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['key_metadata'] = key['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def disable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.disable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as enabled. CLI example:: salt myminion boto_kms.enable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.enable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ciphertext = conn.encrypt( key_id, plaintext, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['ciphertext'] = ciphertext['CiphertextBlob'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key_without_plaintext( key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None ): ''' Generate a secure data key without a plaintext copy of the key. CLI example:: salt myminion boto_kms.generate_data_key_without_plaintext 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key_without_plaintext( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_random(number_of_bytes=None, region=None, key=None, keyid=None, profile=None): ''' Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: random = conn.generate_random(number_of_bytes) r['random'] = random['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_policy = conn.get_key_policy(key_id, policy_name) r['key_policy'] = salt.serializers.json.deserialize( key_policy['Policy'], object_pairs_hook=odict.OrderedDict ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_rotation_status(key_id, region=None, key=None, keyid=None, profile=None): ''' Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_rotation_status = conn.get_key_rotation_status(key_id) r['result'] = key_rotation_status['KeyRotationEnabled'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_grants(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: _grants = [] next_marker = None while True: grants = conn.list_grants( key_id, limit=limit, marker=next_marker ) for grant in grants['Grants']: _grants.append(grant) if 'NextMarker' in grants: next_marker = grants['NextMarker'] else: break r['grants'] = _grants except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_key_policies(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: key_policies = conn.list_key_policies( key_id, limit=limit, marker=marker ) # TODO: handle limit, marker and truncation automatically. r['key_policies'] = key_policies['PolicyNames'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def put_key_policy(key_id, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.put_key_policy(key_id, policy_name, salt.serializers.json.serialize(policy)) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context=None, destination_encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Reencrypt encrypted data with a new master key. CLI example:: salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}' ''' conn = _get_conn( region=region, key=key, keyid=keyid, profile=profile ) r = {} try: ciphertext = conn.re_encrypt( ciphertext_blob, destination_key_id, source_encryption_context, destination_encryption_context, grant_tokens ) r['ciphertext'] = ciphertext except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None, profile=None): ''' Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j... ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: conn.revoke_grant(key_id, grant_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def update_key_description(key_id, description, region=None, key=None, keyid=None, profile=None): ''' Update a key's description. CLI example:: salt myminion boto_kms.update_key_description 'alias/mykey' 'My key' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.update_key_description(key_id, description) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
saltstack/salt
salt/modules/boto_kms.py
encrypt
python
def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ciphertext = conn.encrypt( key_id, plaintext, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['ciphertext'] = ciphertext['CiphertextBlob'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r
Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L315-L337
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon KMS .. versionadded:: 2015.8.0 :configuration: This module accepts explicit kms credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at:: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file:: kms.keyid: GKTADJGHEIQSXMKKRBJ08H kms.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration:: kms.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import Salt libs import salt.utils.compat import salt.utils.odict as odict import salt.serializers.json import salt.utils.versions log = logging.getLogger(__name__) # Import third party libs try: # pylint: disable=unused-import import boto import boto.kms # pylint: enable=unused-import logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except (ImportError, AttributeError): HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( boto_ver='2.38.0', check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'kms', pack=__salt__) def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): ''' Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.create_alias(alias_name, target_key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def create_grant(key_id, grantee_principal, retiring_principal=None, operations=None, constraints=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Adds a grant to a key to specify who can access the key and under what conditions. CLI example:: salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: r['grant'] = conn.create_grant( key_id, grantee_principal, retiring_principal=retiring_principal, operations=operations, constraints=constraints, grant_tokens=grant_tokens ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def create_key(policy=None, description=None, key_usage=None, region=None, key=None, keyid=None, profile=None): ''' Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} _policy = salt.serializers.json.serialize(policy) try: key_metadata = conn.create_key( _policy, description=description, key_usage=key_usage ) r['key_metadata'] = key_metadata['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: plaintext = conn.decrypt( ciphertext_blob, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['plaintext'] = plaintext['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def key_exists(key_id, region=None, key=None, keyid=None, profile=None): ''' Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['result'] = True except boto.exception.BotoServerError as e: if isinstance(e, boto.kms.exceptions.NotFoundException): r['result'] = False return r r['error'] = __utils__['boto.get_error'](e) return r def _get_key_id(alias, region=None, key=None, keyid=None, profile=None): ''' From an alias, get a key_id. ''' key_metadata = describe_key( alias, region, key, keyid, profile )['key_metadata'] return key_metadata['KeyId'] def describe_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Get detailed information about a key. CLI example:: salt myminion boto_kms.describe_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['key_metadata'] = key['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def disable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def disable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.disable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as enabled. CLI example:: salt myminion boto_kms.enable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.enable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key_without_plaintext( key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None ): ''' Generate a secure data key without a plaintext copy of the key. CLI example:: salt myminion boto_kms.generate_data_key_without_plaintext 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key_without_plaintext( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_random(number_of_bytes=None, region=None, key=None, keyid=None, profile=None): ''' Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: random = conn.generate_random(number_of_bytes) r['random'] = random['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_policy = conn.get_key_policy(key_id, policy_name) r['key_policy'] = salt.serializers.json.deserialize( key_policy['Policy'], object_pairs_hook=odict.OrderedDict ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_rotation_status(key_id, region=None, key=None, keyid=None, profile=None): ''' Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_rotation_status = conn.get_key_rotation_status(key_id) r['result'] = key_rotation_status['KeyRotationEnabled'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_grants(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: _grants = [] next_marker = None while True: grants = conn.list_grants( key_id, limit=limit, marker=next_marker ) for grant in grants['Grants']: _grants.append(grant) if 'NextMarker' in grants: next_marker = grants['NextMarker'] else: break r['grants'] = _grants except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_key_policies(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: key_policies = conn.list_key_policies( key_id, limit=limit, marker=marker ) # TODO: handle limit, marker and truncation automatically. r['key_policies'] = key_policies['PolicyNames'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def put_key_policy(key_id, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.put_key_policy(key_id, policy_name, salt.serializers.json.serialize(policy)) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context=None, destination_encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Reencrypt encrypted data with a new master key. CLI example:: salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}' ''' conn = _get_conn( region=region, key=key, keyid=keyid, profile=profile ) r = {} try: ciphertext = conn.re_encrypt( ciphertext_blob, destination_key_id, source_encryption_context, destination_encryption_context, grant_tokens ) r['ciphertext'] = ciphertext except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None, profile=None): ''' Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j... ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: conn.revoke_grant(key_id, grant_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def update_key_description(key_id, description, region=None, key=None, keyid=None, profile=None): ''' Update a key's description. CLI example:: salt myminion boto_kms.update_key_description 'alias/mykey' 'My key' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.update_key_description(key_id, description) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
saltstack/salt
salt/modules/boto_kms.py
generate_data_key
python
def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r
Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L340-L364
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon KMS .. versionadded:: 2015.8.0 :configuration: This module accepts explicit kms credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at:: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file:: kms.keyid: GKTADJGHEIQSXMKKRBJ08H kms.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration:: kms.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import Salt libs import salt.utils.compat import salt.utils.odict as odict import salt.serializers.json import salt.utils.versions log = logging.getLogger(__name__) # Import third party libs try: # pylint: disable=unused-import import boto import boto.kms # pylint: enable=unused-import logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except (ImportError, AttributeError): HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( boto_ver='2.38.0', check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'kms', pack=__salt__) def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): ''' Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.create_alias(alias_name, target_key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def create_grant(key_id, grantee_principal, retiring_principal=None, operations=None, constraints=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Adds a grant to a key to specify who can access the key and under what conditions. CLI example:: salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: r['grant'] = conn.create_grant( key_id, grantee_principal, retiring_principal=retiring_principal, operations=operations, constraints=constraints, grant_tokens=grant_tokens ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def create_key(policy=None, description=None, key_usage=None, region=None, key=None, keyid=None, profile=None): ''' Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} _policy = salt.serializers.json.serialize(policy) try: key_metadata = conn.create_key( _policy, description=description, key_usage=key_usage ) r['key_metadata'] = key_metadata['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: plaintext = conn.decrypt( ciphertext_blob, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['plaintext'] = plaintext['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def key_exists(key_id, region=None, key=None, keyid=None, profile=None): ''' Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['result'] = True except boto.exception.BotoServerError as e: if isinstance(e, boto.kms.exceptions.NotFoundException): r['result'] = False return r r['error'] = __utils__['boto.get_error'](e) return r def _get_key_id(alias, region=None, key=None, keyid=None, profile=None): ''' From an alias, get a key_id. ''' key_metadata = describe_key( alias, region, key, keyid, profile )['key_metadata'] return key_metadata['KeyId'] def describe_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Get detailed information about a key. CLI example:: salt myminion boto_kms.describe_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['key_metadata'] = key['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def disable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def disable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.disable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as enabled. CLI example:: salt myminion boto_kms.enable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.enable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ciphertext = conn.encrypt( key_id, plaintext, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['ciphertext'] = ciphertext['CiphertextBlob'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key_without_plaintext( key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None ): ''' Generate a secure data key without a plaintext copy of the key. CLI example:: salt myminion boto_kms.generate_data_key_without_plaintext 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key_without_plaintext( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_random(number_of_bytes=None, region=None, key=None, keyid=None, profile=None): ''' Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: random = conn.generate_random(number_of_bytes) r['random'] = random['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_policy = conn.get_key_policy(key_id, policy_name) r['key_policy'] = salt.serializers.json.deserialize( key_policy['Policy'], object_pairs_hook=odict.OrderedDict ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_rotation_status(key_id, region=None, key=None, keyid=None, profile=None): ''' Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_rotation_status = conn.get_key_rotation_status(key_id) r['result'] = key_rotation_status['KeyRotationEnabled'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_grants(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: _grants = [] next_marker = None while True: grants = conn.list_grants( key_id, limit=limit, marker=next_marker ) for grant in grants['Grants']: _grants.append(grant) if 'NextMarker' in grants: next_marker = grants['NextMarker'] else: break r['grants'] = _grants except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_key_policies(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: key_policies = conn.list_key_policies( key_id, limit=limit, marker=marker ) # TODO: handle limit, marker and truncation automatically. r['key_policies'] = key_policies['PolicyNames'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def put_key_policy(key_id, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.put_key_policy(key_id, policy_name, salt.serializers.json.serialize(policy)) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context=None, destination_encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Reencrypt encrypted data with a new master key. CLI example:: salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}' ''' conn = _get_conn( region=region, key=key, keyid=keyid, profile=profile ) r = {} try: ciphertext = conn.re_encrypt( ciphertext_blob, destination_key_id, source_encryption_context, destination_encryption_context, grant_tokens ) r['ciphertext'] = ciphertext except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None, profile=None): ''' Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j... ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: conn.revoke_grant(key_id, grant_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def update_key_description(key_id, description, region=None, key=None, keyid=None, profile=None): ''' Update a key's description. CLI example:: salt myminion boto_kms.update_key_description 'alias/mykey' 'My key' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.update_key_description(key_id, description) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
saltstack/salt
salt/modules/boto_kms.py
generate_random
python
def generate_random(number_of_bytes=None, region=None, key=None, keyid=None, profile=None): ''' Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: random = conn.generate_random(number_of_bytes) r['random'] = random['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r
Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L395-L412
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon KMS .. versionadded:: 2015.8.0 :configuration: This module accepts explicit kms credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at:: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file:: kms.keyid: GKTADJGHEIQSXMKKRBJ08H kms.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration:: kms.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import Salt libs import salt.utils.compat import salt.utils.odict as odict import salt.serializers.json import salt.utils.versions log = logging.getLogger(__name__) # Import third party libs try: # pylint: disable=unused-import import boto import boto.kms # pylint: enable=unused-import logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except (ImportError, AttributeError): HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( boto_ver='2.38.0', check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'kms', pack=__salt__) def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): ''' Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.create_alias(alias_name, target_key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def create_grant(key_id, grantee_principal, retiring_principal=None, operations=None, constraints=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Adds a grant to a key to specify who can access the key and under what conditions. CLI example:: salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: r['grant'] = conn.create_grant( key_id, grantee_principal, retiring_principal=retiring_principal, operations=operations, constraints=constraints, grant_tokens=grant_tokens ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def create_key(policy=None, description=None, key_usage=None, region=None, key=None, keyid=None, profile=None): ''' Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} _policy = salt.serializers.json.serialize(policy) try: key_metadata = conn.create_key( _policy, description=description, key_usage=key_usage ) r['key_metadata'] = key_metadata['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: plaintext = conn.decrypt( ciphertext_blob, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['plaintext'] = plaintext['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def key_exists(key_id, region=None, key=None, keyid=None, profile=None): ''' Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['result'] = True except boto.exception.BotoServerError as e: if isinstance(e, boto.kms.exceptions.NotFoundException): r['result'] = False return r r['error'] = __utils__['boto.get_error'](e) return r def _get_key_id(alias, region=None, key=None, keyid=None, profile=None): ''' From an alias, get a key_id. ''' key_metadata = describe_key( alias, region, key, keyid, profile )['key_metadata'] return key_metadata['KeyId'] def describe_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Get detailed information about a key. CLI example:: salt myminion boto_kms.describe_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['key_metadata'] = key['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def disable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def disable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.disable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as enabled. CLI example:: salt myminion boto_kms.enable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.enable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ciphertext = conn.encrypt( key_id, plaintext, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['ciphertext'] = ciphertext['CiphertextBlob'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key_without_plaintext( key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None ): ''' Generate a secure data key without a plaintext copy of the key. CLI example:: salt myminion boto_kms.generate_data_key_without_plaintext 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key_without_plaintext( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_policy = conn.get_key_policy(key_id, policy_name) r['key_policy'] = salt.serializers.json.deserialize( key_policy['Policy'], object_pairs_hook=odict.OrderedDict ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_rotation_status(key_id, region=None, key=None, keyid=None, profile=None): ''' Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_rotation_status = conn.get_key_rotation_status(key_id) r['result'] = key_rotation_status['KeyRotationEnabled'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_grants(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: _grants = [] next_marker = None while True: grants = conn.list_grants( key_id, limit=limit, marker=next_marker ) for grant in grants['Grants']: _grants.append(grant) if 'NextMarker' in grants: next_marker = grants['NextMarker'] else: break r['grants'] = _grants except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_key_policies(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: key_policies = conn.list_key_policies( key_id, limit=limit, marker=marker ) # TODO: handle limit, marker and truncation automatically. r['key_policies'] = key_policies['PolicyNames'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def put_key_policy(key_id, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.put_key_policy(key_id, policy_name, salt.serializers.json.serialize(policy)) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context=None, destination_encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Reencrypt encrypted data with a new master key. CLI example:: salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}' ''' conn = _get_conn( region=region, key=key, keyid=keyid, profile=profile ) r = {} try: ciphertext = conn.re_encrypt( ciphertext_blob, destination_key_id, source_encryption_context, destination_encryption_context, grant_tokens ) r['ciphertext'] = ciphertext except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None, profile=None): ''' Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j... ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: conn.revoke_grant(key_id, grant_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def update_key_description(key_id, description, region=None, key=None, keyid=None, profile=None): ''' Update a key's description. CLI example:: salt myminion boto_kms.update_key_description 'alias/mykey' 'My key' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.update_key_description(key_id, description) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
saltstack/salt
salt/modules/boto_kms.py
get_key_policy
python
def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_policy = conn.get_key_policy(key_id, policy_name) r['key_policy'] = salt.serializers.json.deserialize( key_policy['Policy'], object_pairs_hook=odict.OrderedDict ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r
Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L415-L435
[ "def deserialize(stream_or_string, **options):\n '''\n Deserialize any string or stream like object into a Python data structure.\n\n :param stream_or_string: stream or string to deserialize.\n :param options: options given to lower json/simplejson module.\n '''\n\n try:\n if not isinstance(stream_or_string, (bytes, six.string_types)):\n return salt.utils.json.load(\n stream_or_string, _json_module=_json, **options)\n\n if isinstance(stream_or_string, bytes):\n stream_or_string = stream_or_string.decode('utf-8')\n\n return salt.utils.json.loads(stream_or_string, _json_module=_json)\n except Exception as error:\n raise DeserializationError(error)\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon KMS .. versionadded:: 2015.8.0 :configuration: This module accepts explicit kms credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at:: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file:: kms.keyid: GKTADJGHEIQSXMKKRBJ08H kms.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration:: kms.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import Salt libs import salt.utils.compat import salt.utils.odict as odict import salt.serializers.json import salt.utils.versions log = logging.getLogger(__name__) # Import third party libs try: # pylint: disable=unused-import import boto import boto.kms # pylint: enable=unused-import logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except (ImportError, AttributeError): HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( boto_ver='2.38.0', check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'kms', pack=__salt__) def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): ''' Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.create_alias(alias_name, target_key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def create_grant(key_id, grantee_principal, retiring_principal=None, operations=None, constraints=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Adds a grant to a key to specify who can access the key and under what conditions. CLI example:: salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: r['grant'] = conn.create_grant( key_id, grantee_principal, retiring_principal=retiring_principal, operations=operations, constraints=constraints, grant_tokens=grant_tokens ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def create_key(policy=None, description=None, key_usage=None, region=None, key=None, keyid=None, profile=None): ''' Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} _policy = salt.serializers.json.serialize(policy) try: key_metadata = conn.create_key( _policy, description=description, key_usage=key_usage ) r['key_metadata'] = key_metadata['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: plaintext = conn.decrypt( ciphertext_blob, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['plaintext'] = plaintext['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def key_exists(key_id, region=None, key=None, keyid=None, profile=None): ''' Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['result'] = True except boto.exception.BotoServerError as e: if isinstance(e, boto.kms.exceptions.NotFoundException): r['result'] = False return r r['error'] = __utils__['boto.get_error'](e) return r def _get_key_id(alias, region=None, key=None, keyid=None, profile=None): ''' From an alias, get a key_id. ''' key_metadata = describe_key( alias, region, key, keyid, profile )['key_metadata'] return key_metadata['KeyId'] def describe_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Get detailed information about a key. CLI example:: salt myminion boto_kms.describe_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['key_metadata'] = key['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def disable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def disable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.disable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as enabled. CLI example:: salt myminion boto_kms.enable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.enable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ciphertext = conn.encrypt( key_id, plaintext, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['ciphertext'] = ciphertext['CiphertextBlob'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key_without_plaintext( key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None ): ''' Generate a secure data key without a plaintext copy of the key. CLI example:: salt myminion boto_kms.generate_data_key_without_plaintext 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key_without_plaintext( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_random(number_of_bytes=None, region=None, key=None, keyid=None, profile=None): ''' Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: random = conn.generate_random(number_of_bytes) r['random'] = random['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_rotation_status(key_id, region=None, key=None, keyid=None, profile=None): ''' Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_rotation_status = conn.get_key_rotation_status(key_id) r['result'] = key_rotation_status['KeyRotationEnabled'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_grants(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: _grants = [] next_marker = None while True: grants = conn.list_grants( key_id, limit=limit, marker=next_marker ) for grant in grants['Grants']: _grants.append(grant) if 'NextMarker' in grants: next_marker = grants['NextMarker'] else: break r['grants'] = _grants except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_key_policies(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: key_policies = conn.list_key_policies( key_id, limit=limit, marker=marker ) # TODO: handle limit, marker and truncation automatically. r['key_policies'] = key_policies['PolicyNames'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def put_key_policy(key_id, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.put_key_policy(key_id, policy_name, salt.serializers.json.serialize(policy)) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context=None, destination_encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Reencrypt encrypted data with a new master key. CLI example:: salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}' ''' conn = _get_conn( region=region, key=key, keyid=keyid, profile=profile ) r = {} try: ciphertext = conn.re_encrypt( ciphertext_blob, destination_key_id, source_encryption_context, destination_encryption_context, grant_tokens ) r['ciphertext'] = ciphertext except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None, profile=None): ''' Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j... ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: conn.revoke_grant(key_id, grant_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def update_key_description(key_id, description, region=None, key=None, keyid=None, profile=None): ''' Update a key's description. CLI example:: salt myminion boto_kms.update_key_description 'alias/mykey' 'My key' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.update_key_description(key_id, description) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
saltstack/salt
salt/modules/boto_kms.py
get_key_rotation_status
python
def get_key_rotation_status(key_id, region=None, key=None, keyid=None, profile=None): ''' Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_rotation_status = conn.get_key_rotation_status(key_id) r['result'] = key_rotation_status['KeyRotationEnabled'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r
Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L438-L455
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon KMS .. versionadded:: 2015.8.0 :configuration: This module accepts explicit kms credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at:: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file:: kms.keyid: GKTADJGHEIQSXMKKRBJ08H kms.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration:: kms.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import Salt libs import salt.utils.compat import salt.utils.odict as odict import salt.serializers.json import salt.utils.versions log = logging.getLogger(__name__) # Import third party libs try: # pylint: disable=unused-import import boto import boto.kms # pylint: enable=unused-import logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except (ImportError, AttributeError): HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( boto_ver='2.38.0', check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'kms', pack=__salt__) def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): ''' Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.create_alias(alias_name, target_key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def create_grant(key_id, grantee_principal, retiring_principal=None, operations=None, constraints=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Adds a grant to a key to specify who can access the key and under what conditions. CLI example:: salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: r['grant'] = conn.create_grant( key_id, grantee_principal, retiring_principal=retiring_principal, operations=operations, constraints=constraints, grant_tokens=grant_tokens ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def create_key(policy=None, description=None, key_usage=None, region=None, key=None, keyid=None, profile=None): ''' Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} _policy = salt.serializers.json.serialize(policy) try: key_metadata = conn.create_key( _policy, description=description, key_usage=key_usage ) r['key_metadata'] = key_metadata['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: plaintext = conn.decrypt( ciphertext_blob, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['plaintext'] = plaintext['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def key_exists(key_id, region=None, key=None, keyid=None, profile=None): ''' Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['result'] = True except boto.exception.BotoServerError as e: if isinstance(e, boto.kms.exceptions.NotFoundException): r['result'] = False return r r['error'] = __utils__['boto.get_error'](e) return r def _get_key_id(alias, region=None, key=None, keyid=None, profile=None): ''' From an alias, get a key_id. ''' key_metadata = describe_key( alias, region, key, keyid, profile )['key_metadata'] return key_metadata['KeyId'] def describe_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Get detailed information about a key. CLI example:: salt myminion boto_kms.describe_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['key_metadata'] = key['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def disable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def disable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.disable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as enabled. CLI example:: salt myminion boto_kms.enable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.enable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ciphertext = conn.encrypt( key_id, plaintext, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['ciphertext'] = ciphertext['CiphertextBlob'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key_without_plaintext( key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None ): ''' Generate a secure data key without a plaintext copy of the key. CLI example:: salt myminion boto_kms.generate_data_key_without_plaintext 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key_without_plaintext( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_random(number_of_bytes=None, region=None, key=None, keyid=None, profile=None): ''' Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: random = conn.generate_random(number_of_bytes) r['random'] = random['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_policy = conn.get_key_policy(key_id, policy_name) r['key_policy'] = salt.serializers.json.deserialize( key_policy['Policy'], object_pairs_hook=odict.OrderedDict ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_grants(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: _grants = [] next_marker = None while True: grants = conn.list_grants( key_id, limit=limit, marker=next_marker ) for grant in grants['Grants']: _grants.append(grant) if 'NextMarker' in grants: next_marker = grants['NextMarker'] else: break r['grants'] = _grants except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_key_policies(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: key_policies = conn.list_key_policies( key_id, limit=limit, marker=marker ) # TODO: handle limit, marker and truncation automatically. r['key_policies'] = key_policies['PolicyNames'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def put_key_policy(key_id, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.put_key_policy(key_id, policy_name, salt.serializers.json.serialize(policy)) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context=None, destination_encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Reencrypt encrypted data with a new master key. CLI example:: salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}' ''' conn = _get_conn( region=region, key=key, keyid=keyid, profile=profile ) r = {} try: ciphertext = conn.re_encrypt( ciphertext_blob, destination_key_id, source_encryption_context, destination_encryption_context, grant_tokens ) r['ciphertext'] = ciphertext except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None, profile=None): ''' Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j... ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: conn.revoke_grant(key_id, grant_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def update_key_description(key_id, description, region=None, key=None, keyid=None, profile=None): ''' Update a key's description. CLI example:: salt myminion boto_kms.update_key_description 'alias/mykey' 'My key' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.update_key_description(key_id, description) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
saltstack/salt
salt/modules/boto_kms.py
list_grants
python
def list_grants(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: _grants = [] next_marker = None while True: grants = conn.list_grants( key_id, limit=limit, marker=next_marker ) for grant in grants['Grants']: _grants.append(grant) if 'NextMarker' in grants: next_marker = grants['NextMarker'] else: break r['grants'] = _grants except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r
List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L458-L490
[ "def _get_key_id(alias, region=None, key=None, keyid=None, profile=None):\n '''\n From an alias, get a key_id.\n '''\n key_metadata = describe_key(\n alias, region, key, keyid, profile\n )['key_metadata']\n return key_metadata['KeyId']\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon KMS .. versionadded:: 2015.8.0 :configuration: This module accepts explicit kms credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at:: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file:: kms.keyid: GKTADJGHEIQSXMKKRBJ08H kms.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration:: kms.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import Salt libs import salt.utils.compat import salt.utils.odict as odict import salt.serializers.json import salt.utils.versions log = logging.getLogger(__name__) # Import third party libs try: # pylint: disable=unused-import import boto import boto.kms # pylint: enable=unused-import logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except (ImportError, AttributeError): HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( boto_ver='2.38.0', check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'kms', pack=__salt__) def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): ''' Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.create_alias(alias_name, target_key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def create_grant(key_id, grantee_principal, retiring_principal=None, operations=None, constraints=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Adds a grant to a key to specify who can access the key and under what conditions. CLI example:: salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: r['grant'] = conn.create_grant( key_id, grantee_principal, retiring_principal=retiring_principal, operations=operations, constraints=constraints, grant_tokens=grant_tokens ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def create_key(policy=None, description=None, key_usage=None, region=None, key=None, keyid=None, profile=None): ''' Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} _policy = salt.serializers.json.serialize(policy) try: key_metadata = conn.create_key( _policy, description=description, key_usage=key_usage ) r['key_metadata'] = key_metadata['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: plaintext = conn.decrypt( ciphertext_blob, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['plaintext'] = plaintext['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def key_exists(key_id, region=None, key=None, keyid=None, profile=None): ''' Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['result'] = True except boto.exception.BotoServerError as e: if isinstance(e, boto.kms.exceptions.NotFoundException): r['result'] = False return r r['error'] = __utils__['boto.get_error'](e) return r def _get_key_id(alias, region=None, key=None, keyid=None, profile=None): ''' From an alias, get a key_id. ''' key_metadata = describe_key( alias, region, key, keyid, profile )['key_metadata'] return key_metadata['KeyId'] def describe_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Get detailed information about a key. CLI example:: salt myminion boto_kms.describe_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['key_metadata'] = key['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def disable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def disable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.disable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as enabled. CLI example:: salt myminion boto_kms.enable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.enable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ciphertext = conn.encrypt( key_id, plaintext, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['ciphertext'] = ciphertext['CiphertextBlob'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key_without_plaintext( key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None ): ''' Generate a secure data key without a plaintext copy of the key. CLI example:: salt myminion boto_kms.generate_data_key_without_plaintext 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key_without_plaintext( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_random(number_of_bytes=None, region=None, key=None, keyid=None, profile=None): ''' Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: random = conn.generate_random(number_of_bytes) r['random'] = random['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_policy = conn.get_key_policy(key_id, policy_name) r['key_policy'] = salt.serializers.json.deserialize( key_policy['Policy'], object_pairs_hook=odict.OrderedDict ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_rotation_status(key_id, region=None, key=None, keyid=None, profile=None): ''' Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_rotation_status = conn.get_key_rotation_status(key_id) r['result'] = key_rotation_status['KeyRotationEnabled'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_key_policies(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: key_policies = conn.list_key_policies( key_id, limit=limit, marker=marker ) # TODO: handle limit, marker and truncation automatically. r['key_policies'] = key_policies['PolicyNames'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def put_key_policy(key_id, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.put_key_policy(key_id, policy_name, salt.serializers.json.serialize(policy)) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context=None, destination_encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Reencrypt encrypted data with a new master key. CLI example:: salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}' ''' conn = _get_conn( region=region, key=key, keyid=keyid, profile=profile ) r = {} try: ciphertext = conn.re_encrypt( ciphertext_blob, destination_key_id, source_encryption_context, destination_encryption_context, grant_tokens ) r['ciphertext'] = ciphertext except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None, profile=None): ''' Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j... ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: conn.revoke_grant(key_id, grant_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def update_key_description(key_id, description, region=None, key=None, keyid=None, profile=None): ''' Update a key's description. CLI example:: salt myminion boto_kms.update_key_description 'alias/mykey' 'My key' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.update_key_description(key_id, description) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
saltstack/salt
salt/modules/boto_kms.py
list_key_policies
python
def list_key_policies(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: key_policies = conn.list_key_policies( key_id, limit=limit, marker=marker ) # TODO: handle limit, marker and truncation automatically. r['key_policies'] = key_policies['PolicyNames'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r
List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L493-L517
[ "def _get_key_id(alias, region=None, key=None, keyid=None, profile=None):\n '''\n From an alias, get a key_id.\n '''\n key_metadata = describe_key(\n alias, region, key, keyid, profile\n )['key_metadata']\n return key_metadata['KeyId']\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon KMS .. versionadded:: 2015.8.0 :configuration: This module accepts explicit kms credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at:: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file:: kms.keyid: GKTADJGHEIQSXMKKRBJ08H kms.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration:: kms.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import Salt libs import salt.utils.compat import salt.utils.odict as odict import salt.serializers.json import salt.utils.versions log = logging.getLogger(__name__) # Import third party libs try: # pylint: disable=unused-import import boto import boto.kms # pylint: enable=unused-import logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except (ImportError, AttributeError): HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( boto_ver='2.38.0', check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'kms', pack=__salt__) def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): ''' Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.create_alias(alias_name, target_key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def create_grant(key_id, grantee_principal, retiring_principal=None, operations=None, constraints=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Adds a grant to a key to specify who can access the key and under what conditions. CLI example:: salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: r['grant'] = conn.create_grant( key_id, grantee_principal, retiring_principal=retiring_principal, operations=operations, constraints=constraints, grant_tokens=grant_tokens ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def create_key(policy=None, description=None, key_usage=None, region=None, key=None, keyid=None, profile=None): ''' Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} _policy = salt.serializers.json.serialize(policy) try: key_metadata = conn.create_key( _policy, description=description, key_usage=key_usage ) r['key_metadata'] = key_metadata['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: plaintext = conn.decrypt( ciphertext_blob, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['plaintext'] = plaintext['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def key_exists(key_id, region=None, key=None, keyid=None, profile=None): ''' Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['result'] = True except boto.exception.BotoServerError as e: if isinstance(e, boto.kms.exceptions.NotFoundException): r['result'] = False return r r['error'] = __utils__['boto.get_error'](e) return r def _get_key_id(alias, region=None, key=None, keyid=None, profile=None): ''' From an alias, get a key_id. ''' key_metadata = describe_key( alias, region, key, keyid, profile )['key_metadata'] return key_metadata['KeyId'] def describe_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Get detailed information about a key. CLI example:: salt myminion boto_kms.describe_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['key_metadata'] = key['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def disable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def disable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.disable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as enabled. CLI example:: salt myminion boto_kms.enable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.enable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ciphertext = conn.encrypt( key_id, plaintext, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['ciphertext'] = ciphertext['CiphertextBlob'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key_without_plaintext( key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None ): ''' Generate a secure data key without a plaintext copy of the key. CLI example:: salt myminion boto_kms.generate_data_key_without_plaintext 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key_without_plaintext( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_random(number_of_bytes=None, region=None, key=None, keyid=None, profile=None): ''' Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: random = conn.generate_random(number_of_bytes) r['random'] = random['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_policy = conn.get_key_policy(key_id, policy_name) r['key_policy'] = salt.serializers.json.deserialize( key_policy['Policy'], object_pairs_hook=odict.OrderedDict ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_rotation_status(key_id, region=None, key=None, keyid=None, profile=None): ''' Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_rotation_status = conn.get_key_rotation_status(key_id) r['result'] = key_rotation_status['KeyRotationEnabled'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_grants(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: _grants = [] next_marker = None while True: grants = conn.list_grants( key_id, limit=limit, marker=next_marker ) for grant in grants['Grants']: _grants.append(grant) if 'NextMarker' in grants: next_marker = grants['NextMarker'] else: break r['grants'] = _grants except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def put_key_policy(key_id, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.put_key_policy(key_id, policy_name, salt.serializers.json.serialize(policy)) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context=None, destination_encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Reencrypt encrypted data with a new master key. CLI example:: salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}' ''' conn = _get_conn( region=region, key=key, keyid=keyid, profile=profile ) r = {} try: ciphertext = conn.re_encrypt( ciphertext_blob, destination_key_id, source_encryption_context, destination_encryption_context, grant_tokens ) r['ciphertext'] = ciphertext except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None, profile=None): ''' Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j... ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: conn.revoke_grant(key_id, grant_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def update_key_description(key_id, description, region=None, key=None, keyid=None, profile=None): ''' Update a key's description. CLI example:: salt myminion boto_kms.update_key_description 'alias/mykey' 'My key' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.update_key_description(key_id, description) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
saltstack/salt
salt/modules/boto_kms.py
put_key_policy
python
def put_key_policy(key_id, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.put_key_policy(key_id, policy_name, salt.serializers.json.serialize(policy)) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L520-L538
[ "def serialize(obj, **options):\n '''\n Serialize Python data to JSON.\n\n :param obj: the data structure to serialize\n :param options: options given to lower json/simplejson module.\n '''\n\n try:\n if 'fp' in options:\n return salt.utils.json.dump(obj, _json_module=_json, **options)\n else:\n return salt.utils.json.dumps(obj, _json_module=_json, **options)\n except Exception as error:\n raise SerializationError(error)\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon KMS .. versionadded:: 2015.8.0 :configuration: This module accepts explicit kms credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at:: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file:: kms.keyid: GKTADJGHEIQSXMKKRBJ08H kms.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration:: kms.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import Salt libs import salt.utils.compat import salt.utils.odict as odict import salt.serializers.json import salt.utils.versions log = logging.getLogger(__name__) # Import third party libs try: # pylint: disable=unused-import import boto import boto.kms # pylint: enable=unused-import logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except (ImportError, AttributeError): HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( boto_ver='2.38.0', check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'kms', pack=__salt__) def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): ''' Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.create_alias(alias_name, target_key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def create_grant(key_id, grantee_principal, retiring_principal=None, operations=None, constraints=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Adds a grant to a key to specify who can access the key and under what conditions. CLI example:: salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: r['grant'] = conn.create_grant( key_id, grantee_principal, retiring_principal=retiring_principal, operations=operations, constraints=constraints, grant_tokens=grant_tokens ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def create_key(policy=None, description=None, key_usage=None, region=None, key=None, keyid=None, profile=None): ''' Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} _policy = salt.serializers.json.serialize(policy) try: key_metadata = conn.create_key( _policy, description=description, key_usage=key_usage ) r['key_metadata'] = key_metadata['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: plaintext = conn.decrypt( ciphertext_blob, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['plaintext'] = plaintext['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def key_exists(key_id, region=None, key=None, keyid=None, profile=None): ''' Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['result'] = True except boto.exception.BotoServerError as e: if isinstance(e, boto.kms.exceptions.NotFoundException): r['result'] = False return r r['error'] = __utils__['boto.get_error'](e) return r def _get_key_id(alias, region=None, key=None, keyid=None, profile=None): ''' From an alias, get a key_id. ''' key_metadata = describe_key( alias, region, key, keyid, profile )['key_metadata'] return key_metadata['KeyId'] def describe_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Get detailed information about a key. CLI example:: salt myminion boto_kms.describe_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['key_metadata'] = key['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def disable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def disable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.disable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as enabled. CLI example:: salt myminion boto_kms.enable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.enable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ciphertext = conn.encrypt( key_id, plaintext, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['ciphertext'] = ciphertext['CiphertextBlob'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key_without_plaintext( key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None ): ''' Generate a secure data key without a plaintext copy of the key. CLI example:: salt myminion boto_kms.generate_data_key_without_plaintext 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key_without_plaintext( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_random(number_of_bytes=None, region=None, key=None, keyid=None, profile=None): ''' Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: random = conn.generate_random(number_of_bytes) r['random'] = random['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_policy = conn.get_key_policy(key_id, policy_name) r['key_policy'] = salt.serializers.json.deserialize( key_policy['Policy'], object_pairs_hook=odict.OrderedDict ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_rotation_status(key_id, region=None, key=None, keyid=None, profile=None): ''' Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_rotation_status = conn.get_key_rotation_status(key_id) r['result'] = key_rotation_status['KeyRotationEnabled'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_grants(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: _grants = [] next_marker = None while True: grants = conn.list_grants( key_id, limit=limit, marker=next_marker ) for grant in grants['Grants']: _grants.append(grant) if 'NextMarker' in grants: next_marker = grants['NextMarker'] else: break r['grants'] = _grants except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_key_policies(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: key_policies = conn.list_key_policies( key_id, limit=limit, marker=marker ) # TODO: handle limit, marker and truncation automatically. r['key_policies'] = key_policies['PolicyNames'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context=None, destination_encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Reencrypt encrypted data with a new master key. CLI example:: salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}' ''' conn = _get_conn( region=region, key=key, keyid=keyid, profile=profile ) r = {} try: ciphertext = conn.re_encrypt( ciphertext_blob, destination_key_id, source_encryption_context, destination_encryption_context, grant_tokens ) r['ciphertext'] = ciphertext except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None, profile=None): ''' Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j... ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: conn.revoke_grant(key_id, grant_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def update_key_description(key_id, description, region=None, key=None, keyid=None, profile=None): ''' Update a key's description. CLI example:: salt myminion boto_kms.update_key_description 'alias/mykey' 'My key' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.update_key_description(key_id, description) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
saltstack/salt
salt/modules/boto_kms.py
re_encrypt
python
def re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context=None, destination_encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Reencrypt encrypted data with a new master key. CLI example:: salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}' ''' conn = _get_conn( region=region, key=key, keyid=keyid, profile=profile ) r = {} try: ciphertext = conn.re_encrypt( ciphertext_blob, destination_key_id, source_encryption_context, destination_encryption_context, grant_tokens ) r['ciphertext'] = ciphertext except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r
Reencrypt encrypted data with a new master key. CLI example:: salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L541-L568
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon KMS .. versionadded:: 2015.8.0 :configuration: This module accepts explicit kms credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at:: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file:: kms.keyid: GKTADJGHEIQSXMKKRBJ08H kms.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration:: kms.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import Salt libs import salt.utils.compat import salt.utils.odict as odict import salt.serializers.json import salt.utils.versions log = logging.getLogger(__name__) # Import third party libs try: # pylint: disable=unused-import import boto import boto.kms # pylint: enable=unused-import logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except (ImportError, AttributeError): HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( boto_ver='2.38.0', check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'kms', pack=__salt__) def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): ''' Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.create_alias(alias_name, target_key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def create_grant(key_id, grantee_principal, retiring_principal=None, operations=None, constraints=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Adds a grant to a key to specify who can access the key and under what conditions. CLI example:: salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: r['grant'] = conn.create_grant( key_id, grantee_principal, retiring_principal=retiring_principal, operations=operations, constraints=constraints, grant_tokens=grant_tokens ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def create_key(policy=None, description=None, key_usage=None, region=None, key=None, keyid=None, profile=None): ''' Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} _policy = salt.serializers.json.serialize(policy) try: key_metadata = conn.create_key( _policy, description=description, key_usage=key_usage ) r['key_metadata'] = key_metadata['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: plaintext = conn.decrypt( ciphertext_blob, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['plaintext'] = plaintext['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def key_exists(key_id, region=None, key=None, keyid=None, profile=None): ''' Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['result'] = True except boto.exception.BotoServerError as e: if isinstance(e, boto.kms.exceptions.NotFoundException): r['result'] = False return r r['error'] = __utils__['boto.get_error'](e) return r def _get_key_id(alias, region=None, key=None, keyid=None, profile=None): ''' From an alias, get a key_id. ''' key_metadata = describe_key( alias, region, key, keyid, profile )['key_metadata'] return key_metadata['KeyId'] def describe_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Get detailed information about a key. CLI example:: salt myminion boto_kms.describe_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['key_metadata'] = key['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def disable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def disable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.disable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as enabled. CLI example:: salt myminion boto_kms.enable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.enable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ciphertext = conn.encrypt( key_id, plaintext, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['ciphertext'] = ciphertext['CiphertextBlob'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key_without_plaintext( key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None ): ''' Generate a secure data key without a plaintext copy of the key. CLI example:: salt myminion boto_kms.generate_data_key_without_plaintext 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key_without_plaintext( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_random(number_of_bytes=None, region=None, key=None, keyid=None, profile=None): ''' Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: random = conn.generate_random(number_of_bytes) r['random'] = random['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_policy = conn.get_key_policy(key_id, policy_name) r['key_policy'] = salt.serializers.json.deserialize( key_policy['Policy'], object_pairs_hook=odict.OrderedDict ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_rotation_status(key_id, region=None, key=None, keyid=None, profile=None): ''' Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_rotation_status = conn.get_key_rotation_status(key_id) r['result'] = key_rotation_status['KeyRotationEnabled'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_grants(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: _grants = [] next_marker = None while True: grants = conn.list_grants( key_id, limit=limit, marker=next_marker ) for grant in grants['Grants']: _grants.append(grant) if 'NextMarker' in grants: next_marker = grants['NextMarker'] else: break r['grants'] = _grants except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_key_policies(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: key_policies = conn.list_key_policies( key_id, limit=limit, marker=marker ) # TODO: handle limit, marker and truncation automatically. r['key_policies'] = key_policies['PolicyNames'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def put_key_policy(key_id, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.put_key_policy(key_id, policy_name, salt.serializers.json.serialize(policy)) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None, profile=None): ''' Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j... ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: conn.revoke_grant(key_id, grant_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def update_key_description(key_id, description, region=None, key=None, keyid=None, profile=None): ''' Update a key's description. CLI example:: salt myminion boto_kms.update_key_description 'alias/mykey' 'My key' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.update_key_description(key_id, description) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
saltstack/salt
salt/modules/boto_kms.py
revoke_grant
python
def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None, profile=None): ''' Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j... ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: conn.revoke_grant(key_id, grant_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
Revoke a grant from a key. CLI example:: salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j...
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L571-L591
[ "def _get_key_id(alias, region=None, key=None, keyid=None, profile=None):\n '''\n From an alias, get a key_id.\n '''\n key_metadata = describe_key(\n alias, region, key, keyid, profile\n )['key_metadata']\n return key_metadata['KeyId']\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon KMS .. versionadded:: 2015.8.0 :configuration: This module accepts explicit kms credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at:: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file:: kms.keyid: GKTADJGHEIQSXMKKRBJ08H kms.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration:: kms.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import Salt libs import salt.utils.compat import salt.utils.odict as odict import salt.serializers.json import salt.utils.versions log = logging.getLogger(__name__) # Import third party libs try: # pylint: disable=unused-import import boto import boto.kms # pylint: enable=unused-import logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except (ImportError, AttributeError): HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( boto_ver='2.38.0', check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'kms', pack=__salt__) def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): ''' Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.create_alias(alias_name, target_key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def create_grant(key_id, grantee_principal, retiring_principal=None, operations=None, constraints=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Adds a grant to a key to specify who can access the key and under what conditions. CLI example:: salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: r['grant'] = conn.create_grant( key_id, grantee_principal, retiring_principal=retiring_principal, operations=operations, constraints=constraints, grant_tokens=grant_tokens ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def create_key(policy=None, description=None, key_usage=None, region=None, key=None, keyid=None, profile=None): ''' Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} _policy = salt.serializers.json.serialize(policy) try: key_metadata = conn.create_key( _policy, description=description, key_usage=key_usage ) r['key_metadata'] = key_metadata['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: plaintext = conn.decrypt( ciphertext_blob, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['plaintext'] = plaintext['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def key_exists(key_id, region=None, key=None, keyid=None, profile=None): ''' Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['result'] = True except boto.exception.BotoServerError as e: if isinstance(e, boto.kms.exceptions.NotFoundException): r['result'] = False return r r['error'] = __utils__['boto.get_error'](e) return r def _get_key_id(alias, region=None, key=None, keyid=None, profile=None): ''' From an alias, get a key_id. ''' key_metadata = describe_key( alias, region, key, keyid, profile )['key_metadata'] return key_metadata['KeyId'] def describe_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Get detailed information about a key. CLI example:: salt myminion boto_kms.describe_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.describe_key(key_id) # TODO: add to context cache r['key_metadata'] = key['KeyMetadata'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def disable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def disable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.disable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as enabled. CLI example:: salt myminion boto_kms.enable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def enable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): ''' Disable key rotation for specified key. CLI example:: salt myminion boto_kms.enable_key_rotation 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.enable_key_rotation(key_id) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ciphertext = conn.encrypt( key_id, plaintext, encryption_context=encryption_context, grant_tokens=grant_tokens ) r['ciphertext'] = ciphertext['CiphertextBlob'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_data_key_without_plaintext( key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None ): ''' Generate a secure data key without a plaintext copy of the key. CLI example:: salt myminion boto_kms.generate_data_key_without_plaintext 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key_without_plaintext( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def generate_random(number_of_bytes=None, region=None, key=None, keyid=None, profile=None): ''' Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: random = conn.generate_random(number_of_bytes) r['random'] = random['Plaintext'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_policy = conn.get_key_policy(key_id, policy_name) r['key_policy'] = salt.serializers.json.deserialize( key_policy['Policy'], object_pairs_hook=odict.OrderedDict ) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def get_key_rotation_status(key_id, region=None, key=None, keyid=None, profile=None): ''' Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key_rotation_status = conn.get_key_rotation_status(key_id) r['result'] = key_rotation_status['KeyRotationEnabled'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_grants(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: _grants = [] next_marker = None while True: grants = conn.list_grants( key_id, limit=limit, marker=next_marker ) for grant in grants['Grants']: _grants.append(grant) if 'NextMarker' in grants: next_marker = grants['NextMarker'] else: break r['grants'] = _grants except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def list_key_policies(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: key_policies = conn.list_key_policies( key_id, limit=limit, marker=marker ) # TODO: handle limit, marker and truncation automatically. r['key_policies'] = key_policies['PolicyNames'] except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def put_key_policy(key_id, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.put_key_policy(key_id, policy_name, salt.serializers.json.serialize(policy)) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r def re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context=None, destination_encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Reencrypt encrypted data with a new master key. CLI example:: salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}' ''' conn = _get_conn( region=region, key=key, keyid=keyid, profile=profile ) r = {} try: ciphertext = conn.re_encrypt( ciphertext_blob, destination_key_id, source_encryption_context, destination_encryption_context, grant_tokens ) r['ciphertext'] = ciphertext except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r def update_key_description(key_id, description, region=None, key=None, keyid=None, profile=None): ''' Update a key's description. CLI example:: salt myminion boto_kms.update_key_description 'alias/mykey' 'My key' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: conn.update_key_description(key_id, description) r['result'] = True except boto.exception.BotoServerError as e: r['result'] = False r['error'] = __utils__['boto.get_error'](e) return r
saltstack/salt
salt/utils/debug.py
_makepretty
python
def _makepretty(printout, stack): ''' Pretty print the stack trace and environment information for debugging those hard to reproduce user problems. :) ''' printout.write('======== Salt Debug Stack Trace =========\n') traceback.print_stack(stack, file=printout) printout.write('=========================================\n')
Pretty print the stack trace and environment information for debugging those hard to reproduce user problems. :)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/debug.py#L21-L28
null
# -*- coding: utf-8 -*- ''' Print a stacktrace when sent a SIGUSR1 for debugging ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import sys import time import signal import tempfile import traceback import inspect # Import salt libs import salt.utils.files import salt.utils.stringutils def _handle_sigusr1(sig, stack): ''' Signal handler for SIGUSR1, only available on Unix-like systems ''' # When running in the foreground, do the right thing # and spit out the debug info straight to the console if sys.stderr.isatty(): output = sys.stderr _makepretty(output, stack) else: filename = 'salt-debug-{0}.log'.format(int(time.time())) destfile = os.path.join(tempfile.gettempdir(), filename) with salt.utils.files.fopen(destfile, 'w') as output: _makepretty(output, stack) def _handle_sigusr2(sig, stack): ''' Signal handler for SIGUSR2, only available on Unix-like systems ''' try: import yappi except ImportError: return if yappi.is_running(): yappi.stop() filename = 'callgrind.salt-{0}-{1}'.format(int(time.time()), os.getpid()) destfile = os.path.join(tempfile.gettempdir(), filename) yappi.get_func_stats().save(destfile, type='CALLGRIND') if sys.stderr.isatty(): sys.stderr.write('Saved profiling data to: {0}\n'.format(destfile)) yappi.clear_stats() else: if sys.stderr.isatty(): sys.stderr.write('Profiling started\n') yappi.start() def enable_sig_handler(signal_name, handler): ''' Add signal handler for signal name if it exists on given platform ''' if hasattr(signal, signal_name): signal.signal(getattr(signal, signal_name), handler) def enable_sigusr1_handler(): ''' Pretty print a stack trace to the console or a debug log under /tmp when any of the salt daemons such as salt-master are sent a SIGUSR1 ''' enable_sig_handler('SIGUSR1', _handle_sigusr1) # Also canonical BSD-way of printing progress is SIGINFO # which on BSD-derivatives can be sent via Ctrl+T enable_sig_handler('SIGINFO', _handle_sigusr1) def enable_sigusr2_handler(): ''' Toggle YAPPI profiler ''' enable_sig_handler('SIGUSR2', _handle_sigusr2) def inspect_stack(): ''' Return a string of which function we are currently in. ''' return {'co_name': inspect.stack()[1][3]} def caller_name(skip=2, include_lineno=False): ''' Get a name of a caller in the format module.class.method `skip` specifies how many levels of stack to skip while getting caller name. skip=1 means "who calls me", skip=2 "who calls my caller" etc. An empty string is returned if skipped levels exceed stack height Source: https://gist.github.com/techtonik/2151727 ''' stack = inspect.stack() start = 0 + skip if len(stack) < start + 1: return '' parentframe = stack[start][0] name = [] if include_lineno is True: try: lineno = inspect.getframeinfo(parentframe).lineno except: # pylint: disable=bare-except lineno = None module = inspect.getmodule(parentframe) # `modname` can be None when frame is executed directly in console # TODO(techtonik): consider using __main__ if module: name.append(module.__name__) # detect classname if 'self' in parentframe.f_locals: # I don't know any way to detect call from the object method # XXX: there seems to be no way to detect static method call - it will # be just a function call name.append(parentframe.f_locals['self'].__class__.__name__) codename = parentframe.f_code.co_name if codename != '<module>': # top level usually name.append(codename) # function or a method del parentframe fullname = '.'.join(name) if include_lineno and lineno: fullname += ':{}'.format(lineno) return fullname
saltstack/salt
salt/utils/debug.py
_handle_sigusr1
python
def _handle_sigusr1(sig, stack): ''' Signal handler for SIGUSR1, only available on Unix-like systems ''' # When running in the foreground, do the right thing # and spit out the debug info straight to the console if sys.stderr.isatty(): output = sys.stderr _makepretty(output, stack) else: filename = 'salt-debug-{0}.log'.format(int(time.time())) destfile = os.path.join(tempfile.gettempdir(), filename) with salt.utils.files.fopen(destfile, 'w') as output: _makepretty(output, stack)
Signal handler for SIGUSR1, only available on Unix-like systems
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/debug.py#L31-L44
null
# -*- coding: utf-8 -*- ''' Print a stacktrace when sent a SIGUSR1 for debugging ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import sys import time import signal import tempfile import traceback import inspect # Import salt libs import salt.utils.files import salt.utils.stringutils def _makepretty(printout, stack): ''' Pretty print the stack trace and environment information for debugging those hard to reproduce user problems. :) ''' printout.write('======== Salt Debug Stack Trace =========\n') traceback.print_stack(stack, file=printout) printout.write('=========================================\n') def _handle_sigusr2(sig, stack): ''' Signal handler for SIGUSR2, only available on Unix-like systems ''' try: import yappi except ImportError: return if yappi.is_running(): yappi.stop() filename = 'callgrind.salt-{0}-{1}'.format(int(time.time()), os.getpid()) destfile = os.path.join(tempfile.gettempdir(), filename) yappi.get_func_stats().save(destfile, type='CALLGRIND') if sys.stderr.isatty(): sys.stderr.write('Saved profiling data to: {0}\n'.format(destfile)) yappi.clear_stats() else: if sys.stderr.isatty(): sys.stderr.write('Profiling started\n') yappi.start() def enable_sig_handler(signal_name, handler): ''' Add signal handler for signal name if it exists on given platform ''' if hasattr(signal, signal_name): signal.signal(getattr(signal, signal_name), handler) def enable_sigusr1_handler(): ''' Pretty print a stack trace to the console or a debug log under /tmp when any of the salt daemons such as salt-master are sent a SIGUSR1 ''' enable_sig_handler('SIGUSR1', _handle_sigusr1) # Also canonical BSD-way of printing progress is SIGINFO # which on BSD-derivatives can be sent via Ctrl+T enable_sig_handler('SIGINFO', _handle_sigusr1) def enable_sigusr2_handler(): ''' Toggle YAPPI profiler ''' enable_sig_handler('SIGUSR2', _handle_sigusr2) def inspect_stack(): ''' Return a string of which function we are currently in. ''' return {'co_name': inspect.stack()[1][3]} def caller_name(skip=2, include_lineno=False): ''' Get a name of a caller in the format module.class.method `skip` specifies how many levels of stack to skip while getting caller name. skip=1 means "who calls me", skip=2 "who calls my caller" etc. An empty string is returned if skipped levels exceed stack height Source: https://gist.github.com/techtonik/2151727 ''' stack = inspect.stack() start = 0 + skip if len(stack) < start + 1: return '' parentframe = stack[start][0] name = [] if include_lineno is True: try: lineno = inspect.getframeinfo(parentframe).lineno except: # pylint: disable=bare-except lineno = None module = inspect.getmodule(parentframe) # `modname` can be None when frame is executed directly in console # TODO(techtonik): consider using __main__ if module: name.append(module.__name__) # detect classname if 'self' in parentframe.f_locals: # I don't know any way to detect call from the object method # XXX: there seems to be no way to detect static method call - it will # be just a function call name.append(parentframe.f_locals['self'].__class__.__name__) codename = parentframe.f_code.co_name if codename != '<module>': # top level usually name.append(codename) # function or a method del parentframe fullname = '.'.join(name) if include_lineno and lineno: fullname += ':{}'.format(lineno) return fullname
saltstack/salt
salt/utils/debug.py
_handle_sigusr2
python
def _handle_sigusr2(sig, stack): ''' Signal handler for SIGUSR2, only available on Unix-like systems ''' try: import yappi except ImportError: return if yappi.is_running(): yappi.stop() filename = 'callgrind.salt-{0}-{1}'.format(int(time.time()), os.getpid()) destfile = os.path.join(tempfile.gettempdir(), filename) yappi.get_func_stats().save(destfile, type='CALLGRIND') if sys.stderr.isatty(): sys.stderr.write('Saved profiling data to: {0}\n'.format(destfile)) yappi.clear_stats() else: if sys.stderr.isatty(): sys.stderr.write('Profiling started\n') yappi.start()
Signal handler for SIGUSR2, only available on Unix-like systems
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/debug.py#L47-L66
null
# -*- coding: utf-8 -*- ''' Print a stacktrace when sent a SIGUSR1 for debugging ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import sys import time import signal import tempfile import traceback import inspect # Import salt libs import salt.utils.files import salt.utils.stringutils def _makepretty(printout, stack): ''' Pretty print the stack trace and environment information for debugging those hard to reproduce user problems. :) ''' printout.write('======== Salt Debug Stack Trace =========\n') traceback.print_stack(stack, file=printout) printout.write('=========================================\n') def _handle_sigusr1(sig, stack): ''' Signal handler for SIGUSR1, only available on Unix-like systems ''' # When running in the foreground, do the right thing # and spit out the debug info straight to the console if sys.stderr.isatty(): output = sys.stderr _makepretty(output, stack) else: filename = 'salt-debug-{0}.log'.format(int(time.time())) destfile = os.path.join(tempfile.gettempdir(), filename) with salt.utils.files.fopen(destfile, 'w') as output: _makepretty(output, stack) def enable_sig_handler(signal_name, handler): ''' Add signal handler for signal name if it exists on given platform ''' if hasattr(signal, signal_name): signal.signal(getattr(signal, signal_name), handler) def enable_sigusr1_handler(): ''' Pretty print a stack trace to the console or a debug log under /tmp when any of the salt daemons such as salt-master are sent a SIGUSR1 ''' enable_sig_handler('SIGUSR1', _handle_sigusr1) # Also canonical BSD-way of printing progress is SIGINFO # which on BSD-derivatives can be sent via Ctrl+T enable_sig_handler('SIGINFO', _handle_sigusr1) def enable_sigusr2_handler(): ''' Toggle YAPPI profiler ''' enable_sig_handler('SIGUSR2', _handle_sigusr2) def inspect_stack(): ''' Return a string of which function we are currently in. ''' return {'co_name': inspect.stack()[1][3]} def caller_name(skip=2, include_lineno=False): ''' Get a name of a caller in the format module.class.method `skip` specifies how many levels of stack to skip while getting caller name. skip=1 means "who calls me", skip=2 "who calls my caller" etc. An empty string is returned if skipped levels exceed stack height Source: https://gist.github.com/techtonik/2151727 ''' stack = inspect.stack() start = 0 + skip if len(stack) < start + 1: return '' parentframe = stack[start][0] name = [] if include_lineno is True: try: lineno = inspect.getframeinfo(parentframe).lineno except: # pylint: disable=bare-except lineno = None module = inspect.getmodule(parentframe) # `modname` can be None when frame is executed directly in console # TODO(techtonik): consider using __main__ if module: name.append(module.__name__) # detect classname if 'self' in parentframe.f_locals: # I don't know any way to detect call from the object method # XXX: there seems to be no way to detect static method call - it will # be just a function call name.append(parentframe.f_locals['self'].__class__.__name__) codename = parentframe.f_code.co_name if codename != '<module>': # top level usually name.append(codename) # function or a method del parentframe fullname = '.'.join(name) if include_lineno and lineno: fullname += ':{}'.format(lineno) return fullname
saltstack/salt
salt/utils/debug.py
enable_sig_handler
python
def enable_sig_handler(signal_name, handler): ''' Add signal handler for signal name if it exists on given platform ''' if hasattr(signal, signal_name): signal.signal(getattr(signal, signal_name), handler)
Add signal handler for signal name if it exists on given platform
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/debug.py#L69-L74
null
# -*- coding: utf-8 -*- ''' Print a stacktrace when sent a SIGUSR1 for debugging ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import sys import time import signal import tempfile import traceback import inspect # Import salt libs import salt.utils.files import salt.utils.stringutils def _makepretty(printout, stack): ''' Pretty print the stack trace and environment information for debugging those hard to reproduce user problems. :) ''' printout.write('======== Salt Debug Stack Trace =========\n') traceback.print_stack(stack, file=printout) printout.write('=========================================\n') def _handle_sigusr1(sig, stack): ''' Signal handler for SIGUSR1, only available on Unix-like systems ''' # When running in the foreground, do the right thing # and spit out the debug info straight to the console if sys.stderr.isatty(): output = sys.stderr _makepretty(output, stack) else: filename = 'salt-debug-{0}.log'.format(int(time.time())) destfile = os.path.join(tempfile.gettempdir(), filename) with salt.utils.files.fopen(destfile, 'w') as output: _makepretty(output, stack) def _handle_sigusr2(sig, stack): ''' Signal handler for SIGUSR2, only available on Unix-like systems ''' try: import yappi except ImportError: return if yappi.is_running(): yappi.stop() filename = 'callgrind.salt-{0}-{1}'.format(int(time.time()), os.getpid()) destfile = os.path.join(tempfile.gettempdir(), filename) yappi.get_func_stats().save(destfile, type='CALLGRIND') if sys.stderr.isatty(): sys.stderr.write('Saved profiling data to: {0}\n'.format(destfile)) yappi.clear_stats() else: if sys.stderr.isatty(): sys.stderr.write('Profiling started\n') yappi.start() def enable_sigusr1_handler(): ''' Pretty print a stack trace to the console or a debug log under /tmp when any of the salt daemons such as salt-master are sent a SIGUSR1 ''' enable_sig_handler('SIGUSR1', _handle_sigusr1) # Also canonical BSD-way of printing progress is SIGINFO # which on BSD-derivatives can be sent via Ctrl+T enable_sig_handler('SIGINFO', _handle_sigusr1) def enable_sigusr2_handler(): ''' Toggle YAPPI profiler ''' enable_sig_handler('SIGUSR2', _handle_sigusr2) def inspect_stack(): ''' Return a string of which function we are currently in. ''' return {'co_name': inspect.stack()[1][3]} def caller_name(skip=2, include_lineno=False): ''' Get a name of a caller in the format module.class.method `skip` specifies how many levels of stack to skip while getting caller name. skip=1 means "who calls me", skip=2 "who calls my caller" etc. An empty string is returned if skipped levels exceed stack height Source: https://gist.github.com/techtonik/2151727 ''' stack = inspect.stack() start = 0 + skip if len(stack) < start + 1: return '' parentframe = stack[start][0] name = [] if include_lineno is True: try: lineno = inspect.getframeinfo(parentframe).lineno except: # pylint: disable=bare-except lineno = None module = inspect.getmodule(parentframe) # `modname` can be None when frame is executed directly in console # TODO(techtonik): consider using __main__ if module: name.append(module.__name__) # detect classname if 'self' in parentframe.f_locals: # I don't know any way to detect call from the object method # XXX: there seems to be no way to detect static method call - it will # be just a function call name.append(parentframe.f_locals['self'].__class__.__name__) codename = parentframe.f_code.co_name if codename != '<module>': # top level usually name.append(codename) # function or a method del parentframe fullname = '.'.join(name) if include_lineno and lineno: fullname += ':{}'.format(lineno) return fullname
saltstack/salt
salt/utils/debug.py
caller_name
python
def caller_name(skip=2, include_lineno=False): ''' Get a name of a caller in the format module.class.method `skip` specifies how many levels of stack to skip while getting caller name. skip=1 means "who calls me", skip=2 "who calls my caller" etc. An empty string is returned if skipped levels exceed stack height Source: https://gist.github.com/techtonik/2151727 ''' stack = inspect.stack() start = 0 + skip if len(stack) < start + 1: return '' parentframe = stack[start][0] name = [] if include_lineno is True: try: lineno = inspect.getframeinfo(parentframe).lineno except: # pylint: disable=bare-except lineno = None module = inspect.getmodule(parentframe) # `modname` can be None when frame is executed directly in console # TODO(techtonik): consider using __main__ if module: name.append(module.__name__) # detect classname if 'self' in parentframe.f_locals: # I don't know any way to detect call from the object method # XXX: there seems to be no way to detect static method call - it will # be just a function call name.append(parentframe.f_locals['self'].__class__.__name__) codename = parentframe.f_code.co_name if codename != '<module>': # top level usually name.append(codename) # function or a method del parentframe fullname = '.'.join(name) if include_lineno and lineno: fullname += ':{}'.format(lineno) return fullname
Get a name of a caller in the format module.class.method `skip` specifies how many levels of stack to skip while getting caller name. skip=1 means "who calls me", skip=2 "who calls my caller" etc. An empty string is returned if skipped levels exceed stack height Source: https://gist.github.com/techtonik/2151727
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/debug.py#L102-L143
null
# -*- coding: utf-8 -*- ''' Print a stacktrace when sent a SIGUSR1 for debugging ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import sys import time import signal import tempfile import traceback import inspect # Import salt libs import salt.utils.files import salt.utils.stringutils def _makepretty(printout, stack): ''' Pretty print the stack trace and environment information for debugging those hard to reproduce user problems. :) ''' printout.write('======== Salt Debug Stack Trace =========\n') traceback.print_stack(stack, file=printout) printout.write('=========================================\n') def _handle_sigusr1(sig, stack): ''' Signal handler for SIGUSR1, only available on Unix-like systems ''' # When running in the foreground, do the right thing # and spit out the debug info straight to the console if sys.stderr.isatty(): output = sys.stderr _makepretty(output, stack) else: filename = 'salt-debug-{0}.log'.format(int(time.time())) destfile = os.path.join(tempfile.gettempdir(), filename) with salt.utils.files.fopen(destfile, 'w') as output: _makepretty(output, stack) def _handle_sigusr2(sig, stack): ''' Signal handler for SIGUSR2, only available on Unix-like systems ''' try: import yappi except ImportError: return if yappi.is_running(): yappi.stop() filename = 'callgrind.salt-{0}-{1}'.format(int(time.time()), os.getpid()) destfile = os.path.join(tempfile.gettempdir(), filename) yappi.get_func_stats().save(destfile, type='CALLGRIND') if sys.stderr.isatty(): sys.stderr.write('Saved profiling data to: {0}\n'.format(destfile)) yappi.clear_stats() else: if sys.stderr.isatty(): sys.stderr.write('Profiling started\n') yappi.start() def enable_sig_handler(signal_name, handler): ''' Add signal handler for signal name if it exists on given platform ''' if hasattr(signal, signal_name): signal.signal(getattr(signal, signal_name), handler) def enable_sigusr1_handler(): ''' Pretty print a stack trace to the console or a debug log under /tmp when any of the salt daemons such as salt-master are sent a SIGUSR1 ''' enable_sig_handler('SIGUSR1', _handle_sigusr1) # Also canonical BSD-way of printing progress is SIGINFO # which on BSD-derivatives can be sent via Ctrl+T enable_sig_handler('SIGINFO', _handle_sigusr1) def enable_sigusr2_handler(): ''' Toggle YAPPI profiler ''' enable_sig_handler('SIGUSR2', _handle_sigusr2) def inspect_stack(): ''' Return a string of which function we are currently in. ''' return {'co_name': inspect.stack()[1][3]}
saltstack/salt
salt/states/nxos_upgrade.py
image_running
python
def image_running(name, system_image, kickstart_image=None, issu=True, **kwargs): ''' Ensure the NX-OS system image is running on the device. name Name of the salt state task system_image Name of the system image file on bootflash: kickstart_image Name of the kickstart image file on bootflash: This is not needed if the system_image is a combined system and kickstart image Default: None issu Ensure the correct system is running on the device using an in service software upgrade, or force a disruptive upgrade by setting the option to False. Default: False timeout Timeout in seconds for long running 'install all' upgrade command. Default: 900 Examples: .. code-block:: yaml upgrade_software_image_n9k: nxos.image_running: - name: Ensure nxos.7.0.3.I7.5a.bin is running - system_image: nxos.7.0.3.I7.5a.bin - issu: True upgrade_software_image_n7k: nxos.image_running: - name: Ensure n7000-s2-kickstart.8.0.1.bin is running - kickstart_image: n7000-s2-kickstart.8.0.1.bin - system_image: n7000-s2-dk9.8.0.1.bin - issu: False ''' ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''} if kickstart_image is None: upgrade = __salt__['nxos.upgrade'](system_image=system_image, issu=issu, **kwargs) else: upgrade = __salt__['nxos.upgrade'](system_image=system_image, kickstart_image=kickstart_image, issu=issu, **kwargs) if upgrade['upgrade_in_progress']: ret['result'] = upgrade['upgrade_in_progress'] ret['changes'] = upgrade['module_data'] ret['comment'] = 'NX-OS Device Now Being Upgraded - See Change Details Below' elif upgrade['succeeded']: ret['result'] = upgrade['succeeded'] ret['comment'] = 'NX-OS Device Running Image: {}'.format(_version_info()) else: ret['comment'] = 'Upgrade Failed: {}.'.format(upgrade['error_data']) return ret
Ensure the NX-OS system image is running on the device. name Name of the salt state task system_image Name of the system image file on bootflash: kickstart_image Name of the kickstart image file on bootflash: This is not needed if the system_image is a combined system and kickstart image Default: None issu Ensure the correct system is running on the device using an in service software upgrade, or force a disruptive upgrade by setting the option to False. Default: False timeout Timeout in seconds for long running 'install all' upgrade command. Default: 900 Examples: .. code-block:: yaml upgrade_software_image_n9k: nxos.image_running: - name: Ensure nxos.7.0.3.I7.5a.bin is running - system_image: nxos.7.0.3.I7.5a.bin - issu: True upgrade_software_image_n7k: nxos.image_running: - name: Ensure n7000-s2-kickstart.8.0.1.bin is running - kickstart_image: n7000-s2-kickstart.8.0.1.bin - system_image: n7000-s2-dk9.8.0.1.bin - issu: False
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/nxos_upgrade.py#L41-L107
[ "def _version_info():\n '''\n Helper method to return running image version\n '''\n if 'NXOS' in __grains__['nxos']['software']:\n return __grains__['nxos']['software']['NXOS']\n elif 'kickstart' in __grains__['nxos']['software']:\n return __grains__['nxos']['software']['kickstart']\n else:\n return 'Unable to detect sofware version'\n" ]
# -*- coding: utf-8 -*- # Copyright (c) 2018 Cisco and/or its affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Manage NX-OS System Image Upgrades. .. versionadded: xxxx.xx.x :maturity: new :platform: nxos :codeauthor: Michael G Wiebe For documentation on setting up the nxos proxy minion look in the documentation for :mod:`salt.proxy.nxos<salt.proxy.nxos>`. ''' from __future__ import absolute_import, print_function, unicode_literals import logging __virtualname__ = 'nxos' __virtual_aliases__ = ('nxos_upgrade',) log = logging.getLogger(__name__) def __virtual__(): return __virtualname__ def _version_info(): ''' Helper method to return running image version ''' if 'NXOS' in __grains__['nxos']['software']: return __grains__['nxos']['software']['NXOS'] elif 'kickstart' in __grains__['nxos']['software']: return __grains__['nxos']['software']['kickstart'] else: return 'Unable to detect sofware version'
saltstack/salt
salt/ext/vsan/vsanapiutils.py
WaitForTasks
python
def WaitForTasks(tasks, si): pc = si.content.propertyCollector taskList = [str(task) for task in tasks] # Create filter objSpecs = [vmodl.query.PropertyCollector.ObjectSpec(obj=task) for task in tasks] propSpec = vmodl.query.PropertyCollector.PropertySpec(type=vim.Task, pathSet=[], all=True) filterSpec = vmodl.query.PropertyCollector.FilterSpec() filterSpec.objectSet = objSpecs filterSpec.propSet = [propSpec] filter = pc.CreateFilter(filterSpec, True) try: version, state = None, None # Loop looking for updates till the state moves to a completed state. while len(taskList): update = pc.WaitForUpdates(version) for filterSet in update.filterSet: for objSet in filterSet.objectSet: task = objSet.obj for change in objSet.changeSet: if change.name == 'info': state = change.val.state elif change.name == 'info.state': state = change.val else: continue if not str(task) in taskList: continue if state == vim.TaskInfo.State.success: # Remove task from taskList taskList.remove(str(task)) elif state == vim.TaskInfo.State.error: raise task.info.error # Move to next version version = update.version finally: if filter: filter.Destroy()
Given the service instance si and tasks, it returns after all the tasks are complete
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/vsan/vsanapiutils.py#L116-L165
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright 2016 VMware, Inc. All rights reserved. This module defines basic helper functions used in the sampe codes """ # pylint: skip-file __author__ = 'VMware, Inc' from pyVmomi import vim, vmodl, SoapStubAdapter #import the VSAN API python bindings import vsanmgmtObjects VSAN_API_VC_SERVICE_ENDPOINT = '/vsanHealth' VSAN_API_ESXI_SERVICE_ENDPOINT = '/vsan' #Constuct a stub for VSAN API access using VC or ESXi sessions from existing #stubs. Correspoding VC or ESXi service endpoint is required. VC service #endpoint is used as default def _GetVsanStub( stub, endpoint=VSAN_API_VC_SERVICE_ENDPOINT, context=None, version='vim.version.version10' ): hostname = stub.host.split(':')[0] vsanStub = SoapStubAdapter( host=hostname, path=endpoint, version=version, sslContext=context ) vsanStub.cookie = stub.cookie return vsanStub #Construct a stub for access VC side VSAN APIs def GetVsanVcStub(stub, context=None): return _GetVsanStub(stub, endpoint=VSAN_API_VC_SERVICE_ENDPOINT, context=context) #Construct a stub for access ESXi side VSAN APIs def GetVsanEsxStub(stub, context=None): return _GetVsanStub(stub, endpoint=VSAN_API_ESXI_SERVICE_ENDPOINT, context=context) #Construct a stub for access ESXi side VSAN APIs def GetVsanVcMos(vcStub, context=None): vsanStub = GetVsanVcStub(vcStub, context) vcMos = { 'vsan-disk-management-system' : vim.cluster.VsanVcDiskManagementSystem( 'vsan-disk-management-system', vsanStub ), 'vsan-stretched-cluster-system' : vim.cluster.VsanVcStretchedClusterSystem( 'vsan-stretched-cluster-system', vsanStub ), 'vsan-cluster-config-system' : vim.cluster.VsanVcClusterConfigSystem( 'vsan-cluster-config-system', vsanStub ), 'vsan-performance-manager' : vim.cluster.VsanPerformanceManager( 'vsan-performance-manager', vsanStub ), 'vsan-cluster-health-system' : vim.cluster.VsanVcClusterHealthSystem( 'vsan-cluster-health-system', vsanStub ), 'vsan-upgrade-systemex' : vim.VsanUpgradeSystemEx( 'vsan-upgrade-systemex', vsanStub ), 'vsan-cluster-space-report-system' : vim.cluster.VsanSpaceReportSystem( 'vsan-cluster-space-report-system', vsanStub ), 'vsan-cluster-object-system' : vim.cluster.VsanObjectSystem( 'vsan-cluster-object-system', vsanStub ), } return vcMos #Construct a stub for access ESXi side VSAN APIs def GetVsanEsxMos(esxStub, context=None): vsanStub = GetVsanEsxStub(esxStub, context) esxMos = { 'vsan-performance-manager' : vim.cluster.VsanPerformanceManager( 'vsan-performance-manager', vsanStub ), 'ha-vsan-health-system' : vim.host.VsanHealthSystem( 'ha-vsan-health-system', vsanStub ), 'vsan-object-system' : vim.cluster.VsanObjectSystem( 'vsan-object-system', vsanStub ), } return esxMos #Convert a VSAN Task to a Task MO binding to VC service #@param vsanTask the VSAN Task MO #@param stub the stub for the VC API def ConvertVsanTaskToVcTask(vsanTask, vcStub): vcTask = vim.Task(vsanTask._moId, vcStub) return vcTask
saltstack/salt
salt/modules/ddns.py
_config
python
def _config(name, key=None, **kwargs): ''' Return a value for 'name' from command line args then config file options. Specify 'key' if the config file option is not the same as 'name'. ''' if key is None: key = name if name in kwargs: value = kwargs[name] else: value = __salt__['config.option']('ddns.{0}'.format(key)) if not value: value = None return value
Return a value for 'name' from command line args then config file options. Specify 'key' if the config file option is not the same as 'name'.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ddns.py#L55-L68
null
# -*- coding: utf-8 -*- ''' Support for RFC 2136 dynamic DNS updates. :depends: - dnspython Python module :configuration: If you want to use TSIG authentication for the server, there are a couple of optional configuration parameters made available to support this (the keyname is only needed if the keyring contains more than one key):: keyfile: keyring file (default=None) keyname: key name in file (default=None) keyalgorithm: algorithm used to create the key (default='HMAC-MD5.SIG-ALG.REG.INT'). Other possible values: hmac-sha1, hmac-sha224, hmac-sha256, hmac-sha384, hmac-sha512 The keyring file needs to be in json format and the key name needs to end with an extra period in the file, similar to this: .. code-block:: json {"keyname.": "keycontent"} ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging log = logging.getLogger(__name__) try: import dns.query import dns.update import dns.tsigkeyring dns_support = True except ImportError as e: dns_support = False import salt.utils.files import salt.utils.json from salt.ext import six def __virtual__(): ''' Confirm dnspython is available. ''' if dns_support: return 'ddns' return (False, 'The ddns execution module cannot be loaded: dnspython not installed.') def _get_keyring(keyfile): keyring = None if keyfile: with salt.utils.files.fopen(keyfile) as _f: keyring = dns.tsigkeyring.from_text(salt.utils.json.load(_f)) return keyring def add_host(zone, name, ttl, ip, nameserver='127.0.0.1', replace=True, timeout=5, port=53, **kwargs): ''' Add, replace, or update the A and PTR (reverse) records for a host. CLI Example: .. code-block:: bash salt ns1 ddns.add_host example.com host1 60 10.1.1.1 ''' res = update(zone, name, ttl, 'A', ip, nameserver, timeout, replace, port, **kwargs) if res is False: return False fqdn = '{0}.{1}.'.format(name, zone) parts = ip.split('.')[::-1] popped = [] # Iterate over possible reverse zones while len(parts) > 1: p = parts.pop(0) popped.append(p) zone = '{0}.{1}'.format('.'.join(parts), 'in-addr.arpa.') name = '.'.join(popped) ptr = update(zone, name, ttl, 'PTR', fqdn, nameserver, timeout, replace, port, **kwargs) if ptr: return True return res def delete_host(zone, name, nameserver='127.0.0.1', timeout=5, port=53, **kwargs): ''' Delete the forward and reverse records for a host. Returns true if any records are deleted. CLI Example: .. code-block:: bash salt ns1 ddns.delete_host example.com host1 ''' fqdn = '{0}.{1}'.format(name, zone) request = dns.message.make_query(fqdn, 'A') answer = dns.query.udp(request, nameserver, timeout, port) try: ips = [i.address for i in answer.answer[0].items] except IndexError: ips = [] res = delete(zone, name, nameserver=nameserver, timeout=timeout, port=port, **kwargs) fqdn = fqdn + '.' for ip in ips: parts = ip.split('.')[::-1] popped = [] # Iterate over possible reverse zones while len(parts) > 1: p = parts.pop(0) popped.append(p) zone = '{0}.{1}'.format('.'.join(parts), 'in-addr.arpa.') name = '.'.join(popped) ptr = delete(zone, name, 'PTR', fqdn, nameserver=nameserver, timeout=timeout, port=port, **kwargs) if ptr: res = True return res def update(zone, name, ttl, rdtype, data, nameserver='127.0.0.1', timeout=5, replace=False, port=53, **kwargs): ''' Add, replace, or update a DNS record. nameserver must be an IP address and the minion running this module must have update privileges on that server. If replace is true, first deletes all records for this name and type. CLI Example: .. code-block:: bash salt ns1 ddns.update example.com host1 60 A 10.0.0.1 ''' name = six.text_type(name) if name[-1:] == '.': fqdn = name else: fqdn = '{0}.{1}'.format(name, zone) request = dns.message.make_query(fqdn, rdtype) answer = dns.query.udp(request, nameserver, timeout, port) rdtype = dns.rdatatype.from_text(rdtype) rdata = dns.rdata.from_text(dns.rdataclass.IN, rdtype, data) keyring = _get_keyring(_config('keyfile', **kwargs)) keyname = _config('keyname', **kwargs) keyalgorithm = _config('keyalgorithm', **kwargs) or 'HMAC-MD5.SIG-ALG.REG.INT' is_exist = False for rrset in answer.answer: if rdata in rrset.items: if ttl == rrset.ttl: if len(answer.answer) >= 1 or len(rrset.items) >= 1: is_exist = True break dns_update = dns.update.Update(zone, keyring=keyring, keyname=keyname, keyalgorithm=keyalgorithm) if replace: dns_update.replace(name, ttl, rdata) elif not is_exist: dns_update.add(name, ttl, rdata) else: return None answer = dns.query.udp(dns_update, nameserver, timeout, port) if answer.rcode() > 0: return False return True def delete(zone, name, rdtype=None, data=None, nameserver='127.0.0.1', timeout=5, port=53, **kwargs): ''' Delete a DNS record. CLI Example: .. code-block:: bash salt ns1 ddns.delete example.com host1 A ''' name = six.text_type(name) if name[-1:] == '.': fqdn = name else: fqdn = '{0}.{1}'.format(name, zone) request = dns.message.make_query(fqdn, (rdtype or 'ANY')) answer = dns.query.udp(request, nameserver, timeout, port) if not answer.answer: return None keyring = _get_keyring(_config('keyfile', **kwargs)) keyname = _config('keyname', **kwargs) keyalgorithm = _config('keyalgorithm', **kwargs) or 'HMAC-MD5.SIG-ALG.REG.INT' dns_update = dns.update.Update(zone, keyring=keyring, keyname=keyname, keyalgorithm=keyalgorithm) if rdtype: rdtype = dns.rdatatype.from_text(rdtype) if data: rdata = dns.rdata.from_text(dns.rdataclass.IN, rdtype, data) dns_update.delete(name, rdata) else: dns_update.delete(name, rdtype) else: dns_update.delete(name) answer = dns.query.udp(dns_update, nameserver, timeout, port) if answer.rcode() > 0: return False return True
saltstack/salt
salt/modules/ddns.py
add_host
python
def add_host(zone, name, ttl, ip, nameserver='127.0.0.1', replace=True, timeout=5, port=53, **kwargs): ''' Add, replace, or update the A and PTR (reverse) records for a host. CLI Example: .. code-block:: bash salt ns1 ddns.add_host example.com host1 60 10.1.1.1 ''' res = update(zone, name, ttl, 'A', ip, nameserver, timeout, replace, port, **kwargs) if res is False: return False fqdn = '{0}.{1}.'.format(name, zone) parts = ip.split('.')[::-1] popped = [] # Iterate over possible reverse zones while len(parts) > 1: p = parts.pop(0) popped.append(p) zone = '{0}.{1}'.format('.'.join(parts), 'in-addr.arpa.') name = '.'.join(popped) ptr = update(zone, name, ttl, 'PTR', fqdn, nameserver, timeout, replace, port, **kwargs) if ptr: return True return res
Add, replace, or update the A and PTR (reverse) records for a host. CLI Example: .. code-block:: bash salt ns1 ddns.add_host example.com host1 60 10.1.1.1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ddns.py#L79-L109
[ "def update(zone, name, ttl, rdtype, data, nameserver='127.0.0.1', timeout=5,\n replace=False, port=53, **kwargs):\n '''\n Add, replace, or update a DNS record.\n nameserver must be an IP address and the minion running this module\n must have update privileges on that server.\n If replace is true, first deletes all records for this name and type.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt ns1 ddns.update example.com host1 60 A 10.0.0.1\n '''\n name = six.text_type(name)\n\n if name[-1:] == '.':\n fqdn = name\n else:\n fqdn = '{0}.{1}'.format(name, zone)\n\n request = dns.message.make_query(fqdn, rdtype)\n answer = dns.query.udp(request, nameserver, timeout, port)\n\n rdtype = dns.rdatatype.from_text(rdtype)\n rdata = dns.rdata.from_text(dns.rdataclass.IN, rdtype, data)\n\n keyring = _get_keyring(_config('keyfile', **kwargs))\n keyname = _config('keyname', **kwargs)\n keyalgorithm = _config('keyalgorithm',\n **kwargs) or 'HMAC-MD5.SIG-ALG.REG.INT'\n\n is_exist = False\n for rrset in answer.answer:\n if rdata in rrset.items:\n if ttl == rrset.ttl:\n if len(answer.answer) >= 1 or len(rrset.items) >= 1:\n is_exist = True\n break\n\n dns_update = dns.update.Update(zone, keyring=keyring, keyname=keyname,\n keyalgorithm=keyalgorithm)\n if replace:\n dns_update.replace(name, ttl, rdata)\n elif not is_exist:\n dns_update.add(name, ttl, rdata)\n else:\n return None\n answer = dns.query.udp(dns_update, nameserver, timeout, port)\n if answer.rcode() > 0:\n return False\n return True\n" ]
# -*- coding: utf-8 -*- ''' Support for RFC 2136 dynamic DNS updates. :depends: - dnspython Python module :configuration: If you want to use TSIG authentication for the server, there are a couple of optional configuration parameters made available to support this (the keyname is only needed if the keyring contains more than one key):: keyfile: keyring file (default=None) keyname: key name in file (default=None) keyalgorithm: algorithm used to create the key (default='HMAC-MD5.SIG-ALG.REG.INT'). Other possible values: hmac-sha1, hmac-sha224, hmac-sha256, hmac-sha384, hmac-sha512 The keyring file needs to be in json format and the key name needs to end with an extra period in the file, similar to this: .. code-block:: json {"keyname.": "keycontent"} ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging log = logging.getLogger(__name__) try: import dns.query import dns.update import dns.tsigkeyring dns_support = True except ImportError as e: dns_support = False import salt.utils.files import salt.utils.json from salt.ext import six def __virtual__(): ''' Confirm dnspython is available. ''' if dns_support: return 'ddns' return (False, 'The ddns execution module cannot be loaded: dnspython not installed.') def _config(name, key=None, **kwargs): ''' Return a value for 'name' from command line args then config file options. Specify 'key' if the config file option is not the same as 'name'. ''' if key is None: key = name if name in kwargs: value = kwargs[name] else: value = __salt__['config.option']('ddns.{0}'.format(key)) if not value: value = None return value def _get_keyring(keyfile): keyring = None if keyfile: with salt.utils.files.fopen(keyfile) as _f: keyring = dns.tsigkeyring.from_text(salt.utils.json.load(_f)) return keyring def delete_host(zone, name, nameserver='127.0.0.1', timeout=5, port=53, **kwargs): ''' Delete the forward and reverse records for a host. Returns true if any records are deleted. CLI Example: .. code-block:: bash salt ns1 ddns.delete_host example.com host1 ''' fqdn = '{0}.{1}'.format(name, zone) request = dns.message.make_query(fqdn, 'A') answer = dns.query.udp(request, nameserver, timeout, port) try: ips = [i.address for i in answer.answer[0].items] except IndexError: ips = [] res = delete(zone, name, nameserver=nameserver, timeout=timeout, port=port, **kwargs) fqdn = fqdn + '.' for ip in ips: parts = ip.split('.')[::-1] popped = [] # Iterate over possible reverse zones while len(parts) > 1: p = parts.pop(0) popped.append(p) zone = '{0}.{1}'.format('.'.join(parts), 'in-addr.arpa.') name = '.'.join(popped) ptr = delete(zone, name, 'PTR', fqdn, nameserver=nameserver, timeout=timeout, port=port, **kwargs) if ptr: res = True return res def update(zone, name, ttl, rdtype, data, nameserver='127.0.0.1', timeout=5, replace=False, port=53, **kwargs): ''' Add, replace, or update a DNS record. nameserver must be an IP address and the minion running this module must have update privileges on that server. If replace is true, first deletes all records for this name and type. CLI Example: .. code-block:: bash salt ns1 ddns.update example.com host1 60 A 10.0.0.1 ''' name = six.text_type(name) if name[-1:] == '.': fqdn = name else: fqdn = '{0}.{1}'.format(name, zone) request = dns.message.make_query(fqdn, rdtype) answer = dns.query.udp(request, nameserver, timeout, port) rdtype = dns.rdatatype.from_text(rdtype) rdata = dns.rdata.from_text(dns.rdataclass.IN, rdtype, data) keyring = _get_keyring(_config('keyfile', **kwargs)) keyname = _config('keyname', **kwargs) keyalgorithm = _config('keyalgorithm', **kwargs) or 'HMAC-MD5.SIG-ALG.REG.INT' is_exist = False for rrset in answer.answer: if rdata in rrset.items: if ttl == rrset.ttl: if len(answer.answer) >= 1 or len(rrset.items) >= 1: is_exist = True break dns_update = dns.update.Update(zone, keyring=keyring, keyname=keyname, keyalgorithm=keyalgorithm) if replace: dns_update.replace(name, ttl, rdata) elif not is_exist: dns_update.add(name, ttl, rdata) else: return None answer = dns.query.udp(dns_update, nameserver, timeout, port) if answer.rcode() > 0: return False return True def delete(zone, name, rdtype=None, data=None, nameserver='127.0.0.1', timeout=5, port=53, **kwargs): ''' Delete a DNS record. CLI Example: .. code-block:: bash salt ns1 ddns.delete example.com host1 A ''' name = six.text_type(name) if name[-1:] == '.': fqdn = name else: fqdn = '{0}.{1}'.format(name, zone) request = dns.message.make_query(fqdn, (rdtype or 'ANY')) answer = dns.query.udp(request, nameserver, timeout, port) if not answer.answer: return None keyring = _get_keyring(_config('keyfile', **kwargs)) keyname = _config('keyname', **kwargs) keyalgorithm = _config('keyalgorithm', **kwargs) or 'HMAC-MD5.SIG-ALG.REG.INT' dns_update = dns.update.Update(zone, keyring=keyring, keyname=keyname, keyalgorithm=keyalgorithm) if rdtype: rdtype = dns.rdatatype.from_text(rdtype) if data: rdata = dns.rdata.from_text(dns.rdataclass.IN, rdtype, data) dns_update.delete(name, rdata) else: dns_update.delete(name, rdtype) else: dns_update.delete(name) answer = dns.query.udp(dns_update, nameserver, timeout, port) if answer.rcode() > 0: return False return True
saltstack/salt
salt/modules/ddns.py
delete_host
python
def delete_host(zone, name, nameserver='127.0.0.1', timeout=5, port=53, **kwargs): ''' Delete the forward and reverse records for a host. Returns true if any records are deleted. CLI Example: .. code-block:: bash salt ns1 ddns.delete_host example.com host1 ''' fqdn = '{0}.{1}'.format(name, zone) request = dns.message.make_query(fqdn, 'A') answer = dns.query.udp(request, nameserver, timeout, port) try: ips = [i.address for i in answer.answer[0].items] except IndexError: ips = [] res = delete(zone, name, nameserver=nameserver, timeout=timeout, port=port, **kwargs) fqdn = fqdn + '.' for ip in ips: parts = ip.split('.')[::-1] popped = [] # Iterate over possible reverse zones while len(parts) > 1: p = parts.pop(0) popped.append(p) zone = '{0}.{1}'.format('.'.join(parts), 'in-addr.arpa.') name = '.'.join(popped) ptr = delete(zone, name, 'PTR', fqdn, nameserver=nameserver, timeout=timeout, port=port, **kwargs) if ptr: res = True return res
Delete the forward and reverse records for a host. Returns true if any records are deleted. CLI Example: .. code-block:: bash salt ns1 ddns.delete_host example.com host1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ddns.py#L112-L151
[ "def delete(zone, name, rdtype=None, data=None, nameserver='127.0.0.1',\n timeout=5, port=53, **kwargs):\n '''\n Delete a DNS record.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt ns1 ddns.delete example.com host1 A\n '''\n name = six.text_type(name)\n\n if name[-1:] == '.':\n fqdn = name\n else:\n fqdn = '{0}.{1}'.format(name, zone)\n\n request = dns.message.make_query(fqdn, (rdtype or 'ANY'))\n answer = dns.query.udp(request, nameserver, timeout, port)\n if not answer.answer:\n return None\n\n keyring = _get_keyring(_config('keyfile', **kwargs))\n keyname = _config('keyname', **kwargs)\n keyalgorithm = _config('keyalgorithm',\n **kwargs) or 'HMAC-MD5.SIG-ALG.REG.INT'\n\n dns_update = dns.update.Update(zone, keyring=keyring, keyname=keyname,\n keyalgorithm=keyalgorithm)\n\n if rdtype:\n rdtype = dns.rdatatype.from_text(rdtype)\n if data:\n rdata = dns.rdata.from_text(dns.rdataclass.IN, rdtype, data)\n dns_update.delete(name, rdata)\n else:\n dns_update.delete(name, rdtype)\n else:\n dns_update.delete(name)\n\n answer = dns.query.udp(dns_update, nameserver, timeout, port)\n if answer.rcode() > 0:\n return False\n return True\n" ]
# -*- coding: utf-8 -*- ''' Support for RFC 2136 dynamic DNS updates. :depends: - dnspython Python module :configuration: If you want to use TSIG authentication for the server, there are a couple of optional configuration parameters made available to support this (the keyname is only needed if the keyring contains more than one key):: keyfile: keyring file (default=None) keyname: key name in file (default=None) keyalgorithm: algorithm used to create the key (default='HMAC-MD5.SIG-ALG.REG.INT'). Other possible values: hmac-sha1, hmac-sha224, hmac-sha256, hmac-sha384, hmac-sha512 The keyring file needs to be in json format and the key name needs to end with an extra period in the file, similar to this: .. code-block:: json {"keyname.": "keycontent"} ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging log = logging.getLogger(__name__) try: import dns.query import dns.update import dns.tsigkeyring dns_support = True except ImportError as e: dns_support = False import salt.utils.files import salt.utils.json from salt.ext import six def __virtual__(): ''' Confirm dnspython is available. ''' if dns_support: return 'ddns' return (False, 'The ddns execution module cannot be loaded: dnspython not installed.') def _config(name, key=None, **kwargs): ''' Return a value for 'name' from command line args then config file options. Specify 'key' if the config file option is not the same as 'name'. ''' if key is None: key = name if name in kwargs: value = kwargs[name] else: value = __salt__['config.option']('ddns.{0}'.format(key)) if not value: value = None return value def _get_keyring(keyfile): keyring = None if keyfile: with salt.utils.files.fopen(keyfile) as _f: keyring = dns.tsigkeyring.from_text(salt.utils.json.load(_f)) return keyring def add_host(zone, name, ttl, ip, nameserver='127.0.0.1', replace=True, timeout=5, port=53, **kwargs): ''' Add, replace, or update the A and PTR (reverse) records for a host. CLI Example: .. code-block:: bash salt ns1 ddns.add_host example.com host1 60 10.1.1.1 ''' res = update(zone, name, ttl, 'A', ip, nameserver, timeout, replace, port, **kwargs) if res is False: return False fqdn = '{0}.{1}.'.format(name, zone) parts = ip.split('.')[::-1] popped = [] # Iterate over possible reverse zones while len(parts) > 1: p = parts.pop(0) popped.append(p) zone = '{0}.{1}'.format('.'.join(parts), 'in-addr.arpa.') name = '.'.join(popped) ptr = update(zone, name, ttl, 'PTR', fqdn, nameserver, timeout, replace, port, **kwargs) if ptr: return True return res def update(zone, name, ttl, rdtype, data, nameserver='127.0.0.1', timeout=5, replace=False, port=53, **kwargs): ''' Add, replace, or update a DNS record. nameserver must be an IP address and the minion running this module must have update privileges on that server. If replace is true, first deletes all records for this name and type. CLI Example: .. code-block:: bash salt ns1 ddns.update example.com host1 60 A 10.0.0.1 ''' name = six.text_type(name) if name[-1:] == '.': fqdn = name else: fqdn = '{0}.{1}'.format(name, zone) request = dns.message.make_query(fqdn, rdtype) answer = dns.query.udp(request, nameserver, timeout, port) rdtype = dns.rdatatype.from_text(rdtype) rdata = dns.rdata.from_text(dns.rdataclass.IN, rdtype, data) keyring = _get_keyring(_config('keyfile', **kwargs)) keyname = _config('keyname', **kwargs) keyalgorithm = _config('keyalgorithm', **kwargs) or 'HMAC-MD5.SIG-ALG.REG.INT' is_exist = False for rrset in answer.answer: if rdata in rrset.items: if ttl == rrset.ttl: if len(answer.answer) >= 1 or len(rrset.items) >= 1: is_exist = True break dns_update = dns.update.Update(zone, keyring=keyring, keyname=keyname, keyalgorithm=keyalgorithm) if replace: dns_update.replace(name, ttl, rdata) elif not is_exist: dns_update.add(name, ttl, rdata) else: return None answer = dns.query.udp(dns_update, nameserver, timeout, port) if answer.rcode() > 0: return False return True def delete(zone, name, rdtype=None, data=None, nameserver='127.0.0.1', timeout=5, port=53, **kwargs): ''' Delete a DNS record. CLI Example: .. code-block:: bash salt ns1 ddns.delete example.com host1 A ''' name = six.text_type(name) if name[-1:] == '.': fqdn = name else: fqdn = '{0}.{1}'.format(name, zone) request = dns.message.make_query(fqdn, (rdtype or 'ANY')) answer = dns.query.udp(request, nameserver, timeout, port) if not answer.answer: return None keyring = _get_keyring(_config('keyfile', **kwargs)) keyname = _config('keyname', **kwargs) keyalgorithm = _config('keyalgorithm', **kwargs) or 'HMAC-MD5.SIG-ALG.REG.INT' dns_update = dns.update.Update(zone, keyring=keyring, keyname=keyname, keyalgorithm=keyalgorithm) if rdtype: rdtype = dns.rdatatype.from_text(rdtype) if data: rdata = dns.rdata.from_text(dns.rdataclass.IN, rdtype, data) dns_update.delete(name, rdata) else: dns_update.delete(name, rdtype) else: dns_update.delete(name) answer = dns.query.udp(dns_update, nameserver, timeout, port) if answer.rcode() > 0: return False return True
saltstack/salt
salt/modules/ddns.py
update
python
def update(zone, name, ttl, rdtype, data, nameserver='127.0.0.1', timeout=5, replace=False, port=53, **kwargs): ''' Add, replace, or update a DNS record. nameserver must be an IP address and the minion running this module must have update privileges on that server. If replace is true, first deletes all records for this name and type. CLI Example: .. code-block:: bash salt ns1 ddns.update example.com host1 60 A 10.0.0.1 ''' name = six.text_type(name) if name[-1:] == '.': fqdn = name else: fqdn = '{0}.{1}'.format(name, zone) request = dns.message.make_query(fqdn, rdtype) answer = dns.query.udp(request, nameserver, timeout, port) rdtype = dns.rdatatype.from_text(rdtype) rdata = dns.rdata.from_text(dns.rdataclass.IN, rdtype, data) keyring = _get_keyring(_config('keyfile', **kwargs)) keyname = _config('keyname', **kwargs) keyalgorithm = _config('keyalgorithm', **kwargs) or 'HMAC-MD5.SIG-ALG.REG.INT' is_exist = False for rrset in answer.answer: if rdata in rrset.items: if ttl == rrset.ttl: if len(answer.answer) >= 1 or len(rrset.items) >= 1: is_exist = True break dns_update = dns.update.Update(zone, keyring=keyring, keyname=keyname, keyalgorithm=keyalgorithm) if replace: dns_update.replace(name, ttl, rdata) elif not is_exist: dns_update.add(name, ttl, rdata) else: return None answer = dns.query.udp(dns_update, nameserver, timeout, port) if answer.rcode() > 0: return False return True
Add, replace, or update a DNS record. nameserver must be an IP address and the minion running this module must have update privileges on that server. If replace is true, first deletes all records for this name and type. CLI Example: .. code-block:: bash salt ns1 ddns.update example.com host1 60 A 10.0.0.1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ddns.py#L154-L205
[ "def _config(name, key=None, **kwargs):\n '''\n Return a value for 'name' from command line args then config file options.\n Specify 'key' if the config file option is not the same as 'name'.\n '''\n if key is None:\n key = name\n if name in kwargs:\n value = kwargs[name]\n else:\n value = __salt__['config.option']('ddns.{0}'.format(key))\n if not value:\n value = None\n return value\n", "def _get_keyring(keyfile):\n keyring = None\n if keyfile:\n with salt.utils.files.fopen(keyfile) as _f:\n keyring = dns.tsigkeyring.from_text(salt.utils.json.load(_f))\n return keyring\n" ]
# -*- coding: utf-8 -*- ''' Support for RFC 2136 dynamic DNS updates. :depends: - dnspython Python module :configuration: If you want to use TSIG authentication for the server, there are a couple of optional configuration parameters made available to support this (the keyname is only needed if the keyring contains more than one key):: keyfile: keyring file (default=None) keyname: key name in file (default=None) keyalgorithm: algorithm used to create the key (default='HMAC-MD5.SIG-ALG.REG.INT'). Other possible values: hmac-sha1, hmac-sha224, hmac-sha256, hmac-sha384, hmac-sha512 The keyring file needs to be in json format and the key name needs to end with an extra period in the file, similar to this: .. code-block:: json {"keyname.": "keycontent"} ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging log = logging.getLogger(__name__) try: import dns.query import dns.update import dns.tsigkeyring dns_support = True except ImportError as e: dns_support = False import salt.utils.files import salt.utils.json from salt.ext import six def __virtual__(): ''' Confirm dnspython is available. ''' if dns_support: return 'ddns' return (False, 'The ddns execution module cannot be loaded: dnspython not installed.') def _config(name, key=None, **kwargs): ''' Return a value for 'name' from command line args then config file options. Specify 'key' if the config file option is not the same as 'name'. ''' if key is None: key = name if name in kwargs: value = kwargs[name] else: value = __salt__['config.option']('ddns.{0}'.format(key)) if not value: value = None return value def _get_keyring(keyfile): keyring = None if keyfile: with salt.utils.files.fopen(keyfile) as _f: keyring = dns.tsigkeyring.from_text(salt.utils.json.load(_f)) return keyring def add_host(zone, name, ttl, ip, nameserver='127.0.0.1', replace=True, timeout=5, port=53, **kwargs): ''' Add, replace, or update the A and PTR (reverse) records for a host. CLI Example: .. code-block:: bash salt ns1 ddns.add_host example.com host1 60 10.1.1.1 ''' res = update(zone, name, ttl, 'A', ip, nameserver, timeout, replace, port, **kwargs) if res is False: return False fqdn = '{0}.{1}.'.format(name, zone) parts = ip.split('.')[::-1] popped = [] # Iterate over possible reverse zones while len(parts) > 1: p = parts.pop(0) popped.append(p) zone = '{0}.{1}'.format('.'.join(parts), 'in-addr.arpa.') name = '.'.join(popped) ptr = update(zone, name, ttl, 'PTR', fqdn, nameserver, timeout, replace, port, **kwargs) if ptr: return True return res def delete_host(zone, name, nameserver='127.0.0.1', timeout=5, port=53, **kwargs): ''' Delete the forward and reverse records for a host. Returns true if any records are deleted. CLI Example: .. code-block:: bash salt ns1 ddns.delete_host example.com host1 ''' fqdn = '{0}.{1}'.format(name, zone) request = dns.message.make_query(fqdn, 'A') answer = dns.query.udp(request, nameserver, timeout, port) try: ips = [i.address for i in answer.answer[0].items] except IndexError: ips = [] res = delete(zone, name, nameserver=nameserver, timeout=timeout, port=port, **kwargs) fqdn = fqdn + '.' for ip in ips: parts = ip.split('.')[::-1] popped = [] # Iterate over possible reverse zones while len(parts) > 1: p = parts.pop(0) popped.append(p) zone = '{0}.{1}'.format('.'.join(parts), 'in-addr.arpa.') name = '.'.join(popped) ptr = delete(zone, name, 'PTR', fqdn, nameserver=nameserver, timeout=timeout, port=port, **kwargs) if ptr: res = True return res def delete(zone, name, rdtype=None, data=None, nameserver='127.0.0.1', timeout=5, port=53, **kwargs): ''' Delete a DNS record. CLI Example: .. code-block:: bash salt ns1 ddns.delete example.com host1 A ''' name = six.text_type(name) if name[-1:] == '.': fqdn = name else: fqdn = '{0}.{1}'.format(name, zone) request = dns.message.make_query(fqdn, (rdtype or 'ANY')) answer = dns.query.udp(request, nameserver, timeout, port) if not answer.answer: return None keyring = _get_keyring(_config('keyfile', **kwargs)) keyname = _config('keyname', **kwargs) keyalgorithm = _config('keyalgorithm', **kwargs) or 'HMAC-MD5.SIG-ALG.REG.INT' dns_update = dns.update.Update(zone, keyring=keyring, keyname=keyname, keyalgorithm=keyalgorithm) if rdtype: rdtype = dns.rdatatype.from_text(rdtype) if data: rdata = dns.rdata.from_text(dns.rdataclass.IN, rdtype, data) dns_update.delete(name, rdata) else: dns_update.delete(name, rdtype) else: dns_update.delete(name) answer = dns.query.udp(dns_update, nameserver, timeout, port) if answer.rcode() > 0: return False return True
saltstack/salt
salt/modules/ansiblegate.py
_set_callables
python
def _set_callables(modules): ''' Set all Ansible modules callables :return: ''' def _set_function(cmd_name, doc): ''' Create a Salt function for the Ansible module. ''' def _cmd(*args, **kw): ''' Call an Ansible module as a function from the Salt. ''' kwargs = {} if kw.get('__pub_arg'): for _kw in kw.get('__pub_arg', []): if isinstance(_kw, dict): kwargs = _kw break return _caller.call(cmd_name, *args, **kwargs) _cmd.__doc__ = doc return _cmd for mod in modules: setattr(sys.modules[__name__], mod, _set_function(mod, 'Available'))
Set all Ansible modules callables :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ansiblegate.py#L190-L215
null
# -*- coding: utf-8 -*- # # Author: Bo Maryniuk <bo@suse.de> # # Copyright 2017 SUSE LLC # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Ansible Support =============== This module can have an optional minion-level configuration in /etc/salt/minion.d/ as follows: ansible_timeout: 1200 The timeout is how many seconds Salt should wait for any Ansible module to respond. ''' from __future__ import absolute_import, print_function, unicode_literals import json import os import sys import logging import importlib import fnmatch import subprocess import salt.utils.json from salt.exceptions import LoaderError, CommandExecutionError from salt.utils.decorators import depends import salt.utils.decorators.path import salt.utils.platform import salt.utils.timed_subprocess import salt.utils.yaml from salt.ext import six try: import ansible import ansible.constants import ansible.modules except ImportError: ansible = None __virtualname__ = 'ansible' log = logging.getLogger(__name__) class AnsibleModuleResolver(object): ''' This class is to resolve all available modules in Ansible. ''' def __init__(self, opts): self.opts = opts self._modules_map = {} def _get_modules_map(self, path=None): ''' Get installed Ansible modules :return: ''' paths = {} root = ansible.modules.__path__[0] if not path: path = root for p_el in os.listdir(path): p_el_path = os.path.join(path, p_el) if os.path.islink(p_el_path): continue if os.path.isdir(p_el_path): paths.update(self._get_modules_map(p_el_path)) else: if (any(p_el.startswith(elm) for elm in ['__', '.']) or not p_el.endswith('.py') or p_el in ansible.constants.IGNORE_FILES): continue p_el_path = p_el_path.replace(root, '').split('.')[0] als_name = p_el_path.replace('.', '').replace('/', '', 1).replace('/', '.') paths[als_name] = p_el_path return paths def load_module(self, module): ''' Introspect Ansible module. :param module: :return: ''' m_ref = self._modules_map.get(module) if m_ref is None: raise LoaderError('Module "{0}" was not found'.format(module)) mod = importlib.import_module('ansible.modules{0}'.format( '.'.join([elm.split('.')[0] for elm in m_ref.split(os.path.sep)]))) return mod def get_modules_list(self, pattern=None): ''' Return module map references. :return: ''' if pattern and '*' not in pattern: pattern = '*{0}*'.format(pattern) modules = [] for m_name, m_path in self._modules_map.items(): m_path = m_path.split('.')[0] m_name = '.'.join([elm for elm in m_path.split(os.path.sep) if elm]) if pattern and fnmatch.fnmatch(m_name, pattern) or not pattern: modules.append(m_name) return sorted(modules) def resolve(self): log.debug('Resolving Ansible modules') self._modules_map = self._get_modules_map() return self def install(self): log.debug('Installing Ansible modules') return self class AnsibleModuleCaller(object): DEFAULT_TIMEOUT = 1200 # seconds (20 minutes) OPT_TIMEOUT_KEY = 'ansible_timeout' def __init__(self, resolver): self._resolver = resolver self.timeout = self._resolver.opts.get(self.OPT_TIMEOUT_KEY, self.DEFAULT_TIMEOUT) def call(self, module, *args, **kwargs): ''' Call an Ansible module by invoking it. :param module: the name of the module. :param args: Arguments to the module :param kwargs: keywords to the module :return: ''' module = self._resolver.load_module(module) if not hasattr(module, 'main'): raise CommandExecutionError('This module is not callable ' '(see "ansible.help {0}")'.format(module.__name__.replace('ansible.modules.', ''))) if args: kwargs['_raw_params'] = ' '.join(args) js_args = str('{{"ANSIBLE_MODULE_ARGS": {args}}}') # future lint: disable=blacklisted-function js_args = js_args.format(args=salt.utils.json.dumps(kwargs)) proc_out = salt.utils.timed_subprocess.TimedProc( ["echo", "{0}".format(js_args)], stdout=subprocess.PIPE, timeout=self.timeout) proc_out.run() proc_exc = salt.utils.timed_subprocess.TimedProc( ['python', module.__file__], stdin=proc_out.stdout, stdout=subprocess.PIPE, timeout=self.timeout) proc_exc.run() try: out = salt.utils.json.loads(proc_exc.stdout) except ValueError as ex: out = {'Error': (proc_exc.stderr and (proc_exc.stderr + '.') or six.text_type(ex))} if proc_exc.stdout: out['Given JSON output'] = proc_exc.stdout return out if 'invocation' in out: del out['invocation'] out['timeout'] = self.timeout return out _resolver = None _caller = None def __virtual__(): ''' Ansible module caller. :return: ''' if salt.utils.platform.is_windows(): return False, "The ansiblegate module isn't supported on Windows" ret = ansible is not None msg = not ret and "Ansible is not installed on this system" or None if ret: global _resolver global _caller _resolver = AnsibleModuleResolver(__opts__).resolve().install() _caller = AnsibleModuleCaller(_resolver) _set_callables(list()) return __virtualname__ @depends('ansible') def help(module=None, *args): ''' Display help on Ansible standard module. :param module: :return: ''' if not module: raise CommandExecutionError('Please tell me what module you want to have helped with. ' 'Or call "ansible.list" to know what is available.') try: module = _resolver.load_module(module) except (ImportError, LoaderError) as err: raise CommandExecutionError('Module "{0}" is currently not functional on your system.'.format(module)) doc = {} ret = {} for docset in module.DOCUMENTATION.split('---'): try: docset = salt.utils.yaml.safe_load(docset) if docset: doc.update(docset) except Exception as err: log.error("Error parsing doc section: %s", err) if not args: if 'description' in doc: description = doc.get('description') or '' del doc['description'] ret['Description'] = description ret['Available sections on module "{}"'.format(module.__name__.replace('ansible.modules.', ''))] = doc.keys() else: for arg in args: info = doc.get(arg) if info is not None: ret[arg] = info return ret @depends('ansible') def list(pattern=None): ''' Lists available modules. :return: ''' return _resolver.get_modules_list(pattern=pattern) @salt.utils.decorators.path.which('ansible-playbook') def playbooks(playbook, rundir=None, check=False, diff=False, extra_vars=None, flush_cache=False, forks=5, inventory=None, limit=None, list_hosts=False, list_tags=False, list_tasks=False, module_path=None, skip_tags=None, start_at_task=None, syntax_check=False, tags=None, playbook_kwargs=None): ''' Run Ansible Playbooks :param playbook: Which playbook to run. :param rundir: Directory to run `ansible-playbook` in. (Default: None) :param check: don't make any changes; instead, try to predict some of the changes that may occur (Default: False) :param diff: when changing (small) files and templates, show the differences in those files; works great with --check (default: False) :param extra_vars: set additional variables as key=value or YAML/JSON, if filename prepend with @, (default: None) :param flush_cache: clear the fact cache for every host in inventory (default: False) :param forks: specify number of parallel processes to use (Default: 5) :param inventory: specify inventory host path or comma separated host list. (Default: None) (Ansible's default is /etc/ansible/hosts) :param limit: further limit selected hosts to an additional pattern (Default: None) :param list_hosts: outputs a list of matching hosts; does not execute anything else (Default: False) :param list_tags: list all available tags (Default: False) :param list_tasks: list all tasks that would be executed (Default: False) :param module_path: prepend colon-separated path(s) to module library. (Default: None) :param skip_tags: only run plays and tasks whose tags do not match these values (Default: False) :param start_at_task: start the playbook at the task matching this name (Default: None) :param: syntax_check: perform a syntax check on the playbook, but do not execute it (Default: False) :param tags: only run plays and tasks tagged with these values (Default: None) :return: Playbook return CLI Example: .. code-block:: bash salt 'ansiblehost' ansible.playbook playbook=/srv/playbooks/play.yml ''' command = ['ansible-playbook', playbook] if check: command.append('--check') if diff: command.append('--diff') if isinstance(extra_vars, dict): command.append("--extra-vars='{0}'".format(json.dumps(extra_vars))) elif isinstance(extra_vars, six.text_type) and extra_vars.startswith('@'): command.append('--extra-vars={0}'.format(extra_vars)) if flush_cache: command.append('--flush-cache') if inventory: command.append('--inventory={0}'.format(inventory)) if limit: command.append('--limit={0}'.format(limit)) if list_hosts: command.append('--list-hosts') if list_tags: command.append('--list-tags') if list_tasks: command.append('--list-tasks') if module_path: command.append('--module-path={0}'.format(module_path)) if skip_tags: command.append('--skip-tags={0}'.format(skip_tags)) if start_at_task: command.append('--start-at-task={0}'.format(start_at_task)) if syntax_check: command.append('--syntax-check') if tags: command.append('--tags={0}'.format(tags)) if playbook_kwargs: for key, value in six.iteritems(playbook_kwargs): key = key.replace('_', '-') if value is True: command.append('--{0}'.format(key)) elif isinstance(value, six.text_type): command.append('--{0}={1}'.format(key, value)) elif isinstance(value, dict): command.append('--{0}={1}'.format(key, json.dumps(value))) command.append('--forks={0}'.format(forks)) cmd_kwargs = { 'env': {'ANSIBLE_STDOUT_CALLBACK': 'json', 'ANSIBLE_RETRY_FILES_ENABLED': '0'}, 'cwd': rundir, 'cmd': ' '.join(command) } ret = __salt__['cmd.run_all'](**cmd_kwargs) log.debug('Ansible Playbook Return: %s', ret) retdata = json.loads(ret['stdout']) if ret['retcode']: __context__['retcode'] = ret['retcode'] return retdata
saltstack/salt
salt/modules/ansiblegate.py
help
python
def help(module=None, *args): ''' Display help on Ansible standard module. :param module: :return: ''' if not module: raise CommandExecutionError('Please tell me what module you want to have helped with. ' 'Or call "ansible.list" to know what is available.') try: module = _resolver.load_module(module) except (ImportError, LoaderError) as err: raise CommandExecutionError('Module "{0}" is currently not functional on your system.'.format(module)) doc = {} ret = {} for docset in module.DOCUMENTATION.split('---'): try: docset = salt.utils.yaml.safe_load(docset) if docset: doc.update(docset) except Exception as err: log.error("Error parsing doc section: %s", err) if not args: if 'description' in doc: description = doc.get('description') or '' del doc['description'] ret['Description'] = description ret['Available sections on module "{}"'.format(module.__name__.replace('ansible.modules.', ''))] = doc.keys() else: for arg in args: info = doc.get(arg) if info is not None: ret[arg] = info return ret
Display help on Ansible standard module. :param module: :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ansiblegate.py#L237-L273
[ "def safe_load(stream, Loader=SaltYamlSafeLoader):\n '''\n .. versionadded:: 2018.3.0\n\n Helper function which automagically uses our custom loader.\n '''\n return yaml.load(stream, Loader=Loader)\n" ]
# -*- coding: utf-8 -*- # # Author: Bo Maryniuk <bo@suse.de> # # Copyright 2017 SUSE LLC # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Ansible Support =============== This module can have an optional minion-level configuration in /etc/salt/minion.d/ as follows: ansible_timeout: 1200 The timeout is how many seconds Salt should wait for any Ansible module to respond. ''' from __future__ import absolute_import, print_function, unicode_literals import json import os import sys import logging import importlib import fnmatch import subprocess import salt.utils.json from salt.exceptions import LoaderError, CommandExecutionError from salt.utils.decorators import depends import salt.utils.decorators.path import salt.utils.platform import salt.utils.timed_subprocess import salt.utils.yaml from salt.ext import six try: import ansible import ansible.constants import ansible.modules except ImportError: ansible = None __virtualname__ = 'ansible' log = logging.getLogger(__name__) class AnsibleModuleResolver(object): ''' This class is to resolve all available modules in Ansible. ''' def __init__(self, opts): self.opts = opts self._modules_map = {} def _get_modules_map(self, path=None): ''' Get installed Ansible modules :return: ''' paths = {} root = ansible.modules.__path__[0] if not path: path = root for p_el in os.listdir(path): p_el_path = os.path.join(path, p_el) if os.path.islink(p_el_path): continue if os.path.isdir(p_el_path): paths.update(self._get_modules_map(p_el_path)) else: if (any(p_el.startswith(elm) for elm in ['__', '.']) or not p_el.endswith('.py') or p_el in ansible.constants.IGNORE_FILES): continue p_el_path = p_el_path.replace(root, '').split('.')[0] als_name = p_el_path.replace('.', '').replace('/', '', 1).replace('/', '.') paths[als_name] = p_el_path return paths def load_module(self, module): ''' Introspect Ansible module. :param module: :return: ''' m_ref = self._modules_map.get(module) if m_ref is None: raise LoaderError('Module "{0}" was not found'.format(module)) mod = importlib.import_module('ansible.modules{0}'.format( '.'.join([elm.split('.')[0] for elm in m_ref.split(os.path.sep)]))) return mod def get_modules_list(self, pattern=None): ''' Return module map references. :return: ''' if pattern and '*' not in pattern: pattern = '*{0}*'.format(pattern) modules = [] for m_name, m_path in self._modules_map.items(): m_path = m_path.split('.')[0] m_name = '.'.join([elm for elm in m_path.split(os.path.sep) if elm]) if pattern and fnmatch.fnmatch(m_name, pattern) or not pattern: modules.append(m_name) return sorted(modules) def resolve(self): log.debug('Resolving Ansible modules') self._modules_map = self._get_modules_map() return self def install(self): log.debug('Installing Ansible modules') return self class AnsibleModuleCaller(object): DEFAULT_TIMEOUT = 1200 # seconds (20 minutes) OPT_TIMEOUT_KEY = 'ansible_timeout' def __init__(self, resolver): self._resolver = resolver self.timeout = self._resolver.opts.get(self.OPT_TIMEOUT_KEY, self.DEFAULT_TIMEOUT) def call(self, module, *args, **kwargs): ''' Call an Ansible module by invoking it. :param module: the name of the module. :param args: Arguments to the module :param kwargs: keywords to the module :return: ''' module = self._resolver.load_module(module) if not hasattr(module, 'main'): raise CommandExecutionError('This module is not callable ' '(see "ansible.help {0}")'.format(module.__name__.replace('ansible.modules.', ''))) if args: kwargs['_raw_params'] = ' '.join(args) js_args = str('{{"ANSIBLE_MODULE_ARGS": {args}}}') # future lint: disable=blacklisted-function js_args = js_args.format(args=salt.utils.json.dumps(kwargs)) proc_out = salt.utils.timed_subprocess.TimedProc( ["echo", "{0}".format(js_args)], stdout=subprocess.PIPE, timeout=self.timeout) proc_out.run() proc_exc = salt.utils.timed_subprocess.TimedProc( ['python', module.__file__], stdin=proc_out.stdout, stdout=subprocess.PIPE, timeout=self.timeout) proc_exc.run() try: out = salt.utils.json.loads(proc_exc.stdout) except ValueError as ex: out = {'Error': (proc_exc.stderr and (proc_exc.stderr + '.') or six.text_type(ex))} if proc_exc.stdout: out['Given JSON output'] = proc_exc.stdout return out if 'invocation' in out: del out['invocation'] out['timeout'] = self.timeout return out _resolver = None _caller = None def _set_callables(modules): ''' Set all Ansible modules callables :return: ''' def _set_function(cmd_name, doc): ''' Create a Salt function for the Ansible module. ''' def _cmd(*args, **kw): ''' Call an Ansible module as a function from the Salt. ''' kwargs = {} if kw.get('__pub_arg'): for _kw in kw.get('__pub_arg', []): if isinstance(_kw, dict): kwargs = _kw break return _caller.call(cmd_name, *args, **kwargs) _cmd.__doc__ = doc return _cmd for mod in modules: setattr(sys.modules[__name__], mod, _set_function(mod, 'Available')) def __virtual__(): ''' Ansible module caller. :return: ''' if salt.utils.platform.is_windows(): return False, "The ansiblegate module isn't supported on Windows" ret = ansible is not None msg = not ret and "Ansible is not installed on this system" or None if ret: global _resolver global _caller _resolver = AnsibleModuleResolver(__opts__).resolve().install() _caller = AnsibleModuleCaller(_resolver) _set_callables(list()) return __virtualname__ @depends('ansible') @depends('ansible') def list(pattern=None): ''' Lists available modules. :return: ''' return _resolver.get_modules_list(pattern=pattern) @salt.utils.decorators.path.which('ansible-playbook') def playbooks(playbook, rundir=None, check=False, diff=False, extra_vars=None, flush_cache=False, forks=5, inventory=None, limit=None, list_hosts=False, list_tags=False, list_tasks=False, module_path=None, skip_tags=None, start_at_task=None, syntax_check=False, tags=None, playbook_kwargs=None): ''' Run Ansible Playbooks :param playbook: Which playbook to run. :param rundir: Directory to run `ansible-playbook` in. (Default: None) :param check: don't make any changes; instead, try to predict some of the changes that may occur (Default: False) :param diff: when changing (small) files and templates, show the differences in those files; works great with --check (default: False) :param extra_vars: set additional variables as key=value or YAML/JSON, if filename prepend with @, (default: None) :param flush_cache: clear the fact cache for every host in inventory (default: False) :param forks: specify number of parallel processes to use (Default: 5) :param inventory: specify inventory host path or comma separated host list. (Default: None) (Ansible's default is /etc/ansible/hosts) :param limit: further limit selected hosts to an additional pattern (Default: None) :param list_hosts: outputs a list of matching hosts; does not execute anything else (Default: False) :param list_tags: list all available tags (Default: False) :param list_tasks: list all tasks that would be executed (Default: False) :param module_path: prepend colon-separated path(s) to module library. (Default: None) :param skip_tags: only run plays and tasks whose tags do not match these values (Default: False) :param start_at_task: start the playbook at the task matching this name (Default: None) :param: syntax_check: perform a syntax check on the playbook, but do not execute it (Default: False) :param tags: only run plays and tasks tagged with these values (Default: None) :return: Playbook return CLI Example: .. code-block:: bash salt 'ansiblehost' ansible.playbook playbook=/srv/playbooks/play.yml ''' command = ['ansible-playbook', playbook] if check: command.append('--check') if diff: command.append('--diff') if isinstance(extra_vars, dict): command.append("--extra-vars='{0}'".format(json.dumps(extra_vars))) elif isinstance(extra_vars, six.text_type) and extra_vars.startswith('@'): command.append('--extra-vars={0}'.format(extra_vars)) if flush_cache: command.append('--flush-cache') if inventory: command.append('--inventory={0}'.format(inventory)) if limit: command.append('--limit={0}'.format(limit)) if list_hosts: command.append('--list-hosts') if list_tags: command.append('--list-tags') if list_tasks: command.append('--list-tasks') if module_path: command.append('--module-path={0}'.format(module_path)) if skip_tags: command.append('--skip-tags={0}'.format(skip_tags)) if start_at_task: command.append('--start-at-task={0}'.format(start_at_task)) if syntax_check: command.append('--syntax-check') if tags: command.append('--tags={0}'.format(tags)) if playbook_kwargs: for key, value in six.iteritems(playbook_kwargs): key = key.replace('_', '-') if value is True: command.append('--{0}'.format(key)) elif isinstance(value, six.text_type): command.append('--{0}={1}'.format(key, value)) elif isinstance(value, dict): command.append('--{0}={1}'.format(key, json.dumps(value))) command.append('--forks={0}'.format(forks)) cmd_kwargs = { 'env': {'ANSIBLE_STDOUT_CALLBACK': 'json', 'ANSIBLE_RETRY_FILES_ENABLED': '0'}, 'cwd': rundir, 'cmd': ' '.join(command) } ret = __salt__['cmd.run_all'](**cmd_kwargs) log.debug('Ansible Playbook Return: %s', ret) retdata = json.loads(ret['stdout']) if ret['retcode']: __context__['retcode'] = ret['retcode'] return retdata
saltstack/salt
salt/modules/ansiblegate.py
playbooks
python
def playbooks(playbook, rundir=None, check=False, diff=False, extra_vars=None, flush_cache=False, forks=5, inventory=None, limit=None, list_hosts=False, list_tags=False, list_tasks=False, module_path=None, skip_tags=None, start_at_task=None, syntax_check=False, tags=None, playbook_kwargs=None): ''' Run Ansible Playbooks :param playbook: Which playbook to run. :param rundir: Directory to run `ansible-playbook` in. (Default: None) :param check: don't make any changes; instead, try to predict some of the changes that may occur (Default: False) :param diff: when changing (small) files and templates, show the differences in those files; works great with --check (default: False) :param extra_vars: set additional variables as key=value or YAML/JSON, if filename prepend with @, (default: None) :param flush_cache: clear the fact cache for every host in inventory (default: False) :param forks: specify number of parallel processes to use (Default: 5) :param inventory: specify inventory host path or comma separated host list. (Default: None) (Ansible's default is /etc/ansible/hosts) :param limit: further limit selected hosts to an additional pattern (Default: None) :param list_hosts: outputs a list of matching hosts; does not execute anything else (Default: False) :param list_tags: list all available tags (Default: False) :param list_tasks: list all tasks that would be executed (Default: False) :param module_path: prepend colon-separated path(s) to module library. (Default: None) :param skip_tags: only run plays and tasks whose tags do not match these values (Default: False) :param start_at_task: start the playbook at the task matching this name (Default: None) :param: syntax_check: perform a syntax check on the playbook, but do not execute it (Default: False) :param tags: only run plays and tasks tagged with these values (Default: None) :return: Playbook return CLI Example: .. code-block:: bash salt 'ansiblehost' ansible.playbook playbook=/srv/playbooks/play.yml ''' command = ['ansible-playbook', playbook] if check: command.append('--check') if diff: command.append('--diff') if isinstance(extra_vars, dict): command.append("--extra-vars='{0}'".format(json.dumps(extra_vars))) elif isinstance(extra_vars, six.text_type) and extra_vars.startswith('@'): command.append('--extra-vars={0}'.format(extra_vars)) if flush_cache: command.append('--flush-cache') if inventory: command.append('--inventory={0}'.format(inventory)) if limit: command.append('--limit={0}'.format(limit)) if list_hosts: command.append('--list-hosts') if list_tags: command.append('--list-tags') if list_tasks: command.append('--list-tasks') if module_path: command.append('--module-path={0}'.format(module_path)) if skip_tags: command.append('--skip-tags={0}'.format(skip_tags)) if start_at_task: command.append('--start-at-task={0}'.format(start_at_task)) if syntax_check: command.append('--syntax-check') if tags: command.append('--tags={0}'.format(tags)) if playbook_kwargs: for key, value in six.iteritems(playbook_kwargs): key = key.replace('_', '-') if value is True: command.append('--{0}'.format(key)) elif isinstance(value, six.text_type): command.append('--{0}={1}'.format(key, value)) elif isinstance(value, dict): command.append('--{0}={1}'.format(key, json.dumps(value))) command.append('--forks={0}'.format(forks)) cmd_kwargs = { 'env': {'ANSIBLE_STDOUT_CALLBACK': 'json', 'ANSIBLE_RETRY_FILES_ENABLED': '0'}, 'cwd': rundir, 'cmd': ' '.join(command) } ret = __salt__['cmd.run_all'](**cmd_kwargs) log.debug('Ansible Playbook Return: %s', ret) retdata = json.loads(ret['stdout']) if ret['retcode']: __context__['retcode'] = ret['retcode'] return retdata
Run Ansible Playbooks :param playbook: Which playbook to run. :param rundir: Directory to run `ansible-playbook` in. (Default: None) :param check: don't make any changes; instead, try to predict some of the changes that may occur (Default: False) :param diff: when changing (small) files and templates, show the differences in those files; works great with --check (default: False) :param extra_vars: set additional variables as key=value or YAML/JSON, if filename prepend with @, (default: None) :param flush_cache: clear the fact cache for every host in inventory (default: False) :param forks: specify number of parallel processes to use (Default: 5) :param inventory: specify inventory host path or comma separated host list. (Default: None) (Ansible's default is /etc/ansible/hosts) :param limit: further limit selected hosts to an additional pattern (Default: None) :param list_hosts: outputs a list of matching hosts; does not execute anything else (Default: False) :param list_tags: list all available tags (Default: False) :param list_tasks: list all tasks that would be executed (Default: False) :param module_path: prepend colon-separated path(s) to module library. (Default: None) :param skip_tags: only run plays and tasks whose tags do not match these values (Default: False) :param start_at_task: start the playbook at the task matching this name (Default: None) :param: syntax_check: perform a syntax check on the playbook, but do not execute it (Default: False) :param tags: only run plays and tasks tagged with these values (Default: None) :return: Playbook return CLI Example: .. code-block:: bash salt 'ansiblehost' ansible.playbook playbook=/srv/playbooks/play.yml
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ansiblegate.py#L286-L381
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
# -*- coding: utf-8 -*- # # Author: Bo Maryniuk <bo@suse.de> # # Copyright 2017 SUSE LLC # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Ansible Support =============== This module can have an optional minion-level configuration in /etc/salt/minion.d/ as follows: ansible_timeout: 1200 The timeout is how many seconds Salt should wait for any Ansible module to respond. ''' from __future__ import absolute_import, print_function, unicode_literals import json import os import sys import logging import importlib import fnmatch import subprocess import salt.utils.json from salt.exceptions import LoaderError, CommandExecutionError from salt.utils.decorators import depends import salt.utils.decorators.path import salt.utils.platform import salt.utils.timed_subprocess import salt.utils.yaml from salt.ext import six try: import ansible import ansible.constants import ansible.modules except ImportError: ansible = None __virtualname__ = 'ansible' log = logging.getLogger(__name__) class AnsibleModuleResolver(object): ''' This class is to resolve all available modules in Ansible. ''' def __init__(self, opts): self.opts = opts self._modules_map = {} def _get_modules_map(self, path=None): ''' Get installed Ansible modules :return: ''' paths = {} root = ansible.modules.__path__[0] if not path: path = root for p_el in os.listdir(path): p_el_path = os.path.join(path, p_el) if os.path.islink(p_el_path): continue if os.path.isdir(p_el_path): paths.update(self._get_modules_map(p_el_path)) else: if (any(p_el.startswith(elm) for elm in ['__', '.']) or not p_el.endswith('.py') or p_el in ansible.constants.IGNORE_FILES): continue p_el_path = p_el_path.replace(root, '').split('.')[0] als_name = p_el_path.replace('.', '').replace('/', '', 1).replace('/', '.') paths[als_name] = p_el_path return paths def load_module(self, module): ''' Introspect Ansible module. :param module: :return: ''' m_ref = self._modules_map.get(module) if m_ref is None: raise LoaderError('Module "{0}" was not found'.format(module)) mod = importlib.import_module('ansible.modules{0}'.format( '.'.join([elm.split('.')[0] for elm in m_ref.split(os.path.sep)]))) return mod def get_modules_list(self, pattern=None): ''' Return module map references. :return: ''' if pattern and '*' not in pattern: pattern = '*{0}*'.format(pattern) modules = [] for m_name, m_path in self._modules_map.items(): m_path = m_path.split('.')[0] m_name = '.'.join([elm for elm in m_path.split(os.path.sep) if elm]) if pattern and fnmatch.fnmatch(m_name, pattern) or not pattern: modules.append(m_name) return sorted(modules) def resolve(self): log.debug('Resolving Ansible modules') self._modules_map = self._get_modules_map() return self def install(self): log.debug('Installing Ansible modules') return self class AnsibleModuleCaller(object): DEFAULT_TIMEOUT = 1200 # seconds (20 minutes) OPT_TIMEOUT_KEY = 'ansible_timeout' def __init__(self, resolver): self._resolver = resolver self.timeout = self._resolver.opts.get(self.OPT_TIMEOUT_KEY, self.DEFAULT_TIMEOUT) def call(self, module, *args, **kwargs): ''' Call an Ansible module by invoking it. :param module: the name of the module. :param args: Arguments to the module :param kwargs: keywords to the module :return: ''' module = self._resolver.load_module(module) if not hasattr(module, 'main'): raise CommandExecutionError('This module is not callable ' '(see "ansible.help {0}")'.format(module.__name__.replace('ansible.modules.', ''))) if args: kwargs['_raw_params'] = ' '.join(args) js_args = str('{{"ANSIBLE_MODULE_ARGS": {args}}}') # future lint: disable=blacklisted-function js_args = js_args.format(args=salt.utils.json.dumps(kwargs)) proc_out = salt.utils.timed_subprocess.TimedProc( ["echo", "{0}".format(js_args)], stdout=subprocess.PIPE, timeout=self.timeout) proc_out.run() proc_exc = salt.utils.timed_subprocess.TimedProc( ['python', module.__file__], stdin=proc_out.stdout, stdout=subprocess.PIPE, timeout=self.timeout) proc_exc.run() try: out = salt.utils.json.loads(proc_exc.stdout) except ValueError as ex: out = {'Error': (proc_exc.stderr and (proc_exc.stderr + '.') or six.text_type(ex))} if proc_exc.stdout: out['Given JSON output'] = proc_exc.stdout return out if 'invocation' in out: del out['invocation'] out['timeout'] = self.timeout return out _resolver = None _caller = None def _set_callables(modules): ''' Set all Ansible modules callables :return: ''' def _set_function(cmd_name, doc): ''' Create a Salt function for the Ansible module. ''' def _cmd(*args, **kw): ''' Call an Ansible module as a function from the Salt. ''' kwargs = {} if kw.get('__pub_arg'): for _kw in kw.get('__pub_arg', []): if isinstance(_kw, dict): kwargs = _kw break return _caller.call(cmd_name, *args, **kwargs) _cmd.__doc__ = doc return _cmd for mod in modules: setattr(sys.modules[__name__], mod, _set_function(mod, 'Available')) def __virtual__(): ''' Ansible module caller. :return: ''' if salt.utils.platform.is_windows(): return False, "The ansiblegate module isn't supported on Windows" ret = ansible is not None msg = not ret and "Ansible is not installed on this system" or None if ret: global _resolver global _caller _resolver = AnsibleModuleResolver(__opts__).resolve().install() _caller = AnsibleModuleCaller(_resolver) _set_callables(list()) return __virtualname__ @depends('ansible') def help(module=None, *args): ''' Display help on Ansible standard module. :param module: :return: ''' if not module: raise CommandExecutionError('Please tell me what module you want to have helped with. ' 'Or call "ansible.list" to know what is available.') try: module = _resolver.load_module(module) except (ImportError, LoaderError) as err: raise CommandExecutionError('Module "{0}" is currently not functional on your system.'.format(module)) doc = {} ret = {} for docset in module.DOCUMENTATION.split('---'): try: docset = salt.utils.yaml.safe_load(docset) if docset: doc.update(docset) except Exception as err: log.error("Error parsing doc section: %s", err) if not args: if 'description' in doc: description = doc.get('description') or '' del doc['description'] ret['Description'] = description ret['Available sections on module "{}"'.format(module.__name__.replace('ansible.modules.', ''))] = doc.keys() else: for arg in args: info = doc.get(arg) if info is not None: ret[arg] = info return ret @depends('ansible') def list(pattern=None): ''' Lists available modules. :return: ''' return _resolver.get_modules_list(pattern=pattern) @salt.utils.decorators.path.which('ansible-playbook')
saltstack/salt
salt/modules/ansiblegate.py
AnsibleModuleResolver._get_modules_map
python
def _get_modules_map(self, path=None): ''' Get installed Ansible modules :return: ''' paths = {} root = ansible.modules.__path__[0] if not path: path = root for p_el in os.listdir(path): p_el_path = os.path.join(path, p_el) if os.path.islink(p_el_path): continue if os.path.isdir(p_el_path): paths.update(self._get_modules_map(p_el_path)) else: if (any(p_el.startswith(elm) for elm in ['__', '.']) or not p_el.endswith('.py') or p_el in ansible.constants.IGNORE_FILES): continue p_el_path = p_el_path.replace(root, '').split('.')[0] als_name = p_el_path.replace('.', '').replace('/', '', 1).replace('/', '.') paths[als_name] = p_el_path return paths
Get installed Ansible modules :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ansiblegate.py#L68-L92
null
class AnsibleModuleResolver(object): ''' This class is to resolve all available modules in Ansible. ''' def __init__(self, opts): self.opts = opts self._modules_map = {} def load_module(self, module): ''' Introspect Ansible module. :param module: :return: ''' m_ref = self._modules_map.get(module) if m_ref is None: raise LoaderError('Module "{0}" was not found'.format(module)) mod = importlib.import_module('ansible.modules{0}'.format( '.'.join([elm.split('.')[0] for elm in m_ref.split(os.path.sep)]))) return mod def get_modules_list(self, pattern=None): ''' Return module map references. :return: ''' if pattern and '*' not in pattern: pattern = '*{0}*'.format(pattern) modules = [] for m_name, m_path in self._modules_map.items(): m_path = m_path.split('.')[0] m_name = '.'.join([elm for elm in m_path.split(os.path.sep) if elm]) if pattern and fnmatch.fnmatch(m_name, pattern) or not pattern: modules.append(m_name) return sorted(modules) def resolve(self): log.debug('Resolving Ansible modules') self._modules_map = self._get_modules_map() return self def install(self): log.debug('Installing Ansible modules') return self
saltstack/salt
salt/modules/ansiblegate.py
AnsibleModuleResolver.load_module
python
def load_module(self, module): ''' Introspect Ansible module. :param module: :return: ''' m_ref = self._modules_map.get(module) if m_ref is None: raise LoaderError('Module "{0}" was not found'.format(module)) mod = importlib.import_module('ansible.modules{0}'.format( '.'.join([elm.split('.')[0] for elm in m_ref.split(os.path.sep)]))) return mod
Introspect Ansible module. :param module: :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ansiblegate.py#L94-L107
null
class AnsibleModuleResolver(object): ''' This class is to resolve all available modules in Ansible. ''' def __init__(self, opts): self.opts = opts self._modules_map = {} def _get_modules_map(self, path=None): ''' Get installed Ansible modules :return: ''' paths = {} root = ansible.modules.__path__[0] if not path: path = root for p_el in os.listdir(path): p_el_path = os.path.join(path, p_el) if os.path.islink(p_el_path): continue if os.path.isdir(p_el_path): paths.update(self._get_modules_map(p_el_path)) else: if (any(p_el.startswith(elm) for elm in ['__', '.']) or not p_el.endswith('.py') or p_el in ansible.constants.IGNORE_FILES): continue p_el_path = p_el_path.replace(root, '').split('.')[0] als_name = p_el_path.replace('.', '').replace('/', '', 1).replace('/', '.') paths[als_name] = p_el_path return paths def get_modules_list(self, pattern=None): ''' Return module map references. :return: ''' if pattern and '*' not in pattern: pattern = '*{0}*'.format(pattern) modules = [] for m_name, m_path in self._modules_map.items(): m_path = m_path.split('.')[0] m_name = '.'.join([elm for elm in m_path.split(os.path.sep) if elm]) if pattern and fnmatch.fnmatch(m_name, pattern) or not pattern: modules.append(m_name) return sorted(modules) def resolve(self): log.debug('Resolving Ansible modules') self._modules_map = self._get_modules_map() return self def install(self): log.debug('Installing Ansible modules') return self
saltstack/salt
salt/modules/ansiblegate.py
AnsibleModuleResolver.get_modules_list
python
def get_modules_list(self, pattern=None): ''' Return module map references. :return: ''' if pattern and '*' not in pattern: pattern = '*{0}*'.format(pattern) modules = [] for m_name, m_path in self._modules_map.items(): m_path = m_path.split('.')[0] m_name = '.'.join([elm for elm in m_path.split(os.path.sep) if elm]) if pattern and fnmatch.fnmatch(m_name, pattern) or not pattern: modules.append(m_name) return sorted(modules)
Return module map references. :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ansiblegate.py#L109-L122
null
class AnsibleModuleResolver(object): ''' This class is to resolve all available modules in Ansible. ''' def __init__(self, opts): self.opts = opts self._modules_map = {} def _get_modules_map(self, path=None): ''' Get installed Ansible modules :return: ''' paths = {} root = ansible.modules.__path__[0] if not path: path = root for p_el in os.listdir(path): p_el_path = os.path.join(path, p_el) if os.path.islink(p_el_path): continue if os.path.isdir(p_el_path): paths.update(self._get_modules_map(p_el_path)) else: if (any(p_el.startswith(elm) for elm in ['__', '.']) or not p_el.endswith('.py') or p_el in ansible.constants.IGNORE_FILES): continue p_el_path = p_el_path.replace(root, '').split('.')[0] als_name = p_el_path.replace('.', '').replace('/', '', 1).replace('/', '.') paths[als_name] = p_el_path return paths def load_module(self, module): ''' Introspect Ansible module. :param module: :return: ''' m_ref = self._modules_map.get(module) if m_ref is None: raise LoaderError('Module "{0}" was not found'.format(module)) mod = importlib.import_module('ansible.modules{0}'.format( '.'.join([elm.split('.')[0] for elm in m_ref.split(os.path.sep)]))) return mod def resolve(self): log.debug('Resolving Ansible modules') self._modules_map = self._get_modules_map() return self def install(self): log.debug('Installing Ansible modules') return self
saltstack/salt
salt/modules/ansiblegate.py
AnsibleModuleCaller.call
python
def call(self, module, *args, **kwargs): ''' Call an Ansible module by invoking it. :param module: the name of the module. :param args: Arguments to the module :param kwargs: keywords to the module :return: ''' module = self._resolver.load_module(module) if not hasattr(module, 'main'): raise CommandExecutionError('This module is not callable ' '(see "ansible.help {0}")'.format(module.__name__.replace('ansible.modules.', ''))) if args: kwargs['_raw_params'] = ' '.join(args) js_args = str('{{"ANSIBLE_MODULE_ARGS": {args}}}') # future lint: disable=blacklisted-function js_args = js_args.format(args=salt.utils.json.dumps(kwargs)) proc_out = salt.utils.timed_subprocess.TimedProc( ["echo", "{0}".format(js_args)], stdout=subprocess.PIPE, timeout=self.timeout) proc_out.run() proc_exc = salt.utils.timed_subprocess.TimedProc( ['python', module.__file__], stdin=proc_out.stdout, stdout=subprocess.PIPE, timeout=self.timeout) proc_exc.run() try: out = salt.utils.json.loads(proc_exc.stdout) except ValueError as ex: out = {'Error': (proc_exc.stderr and (proc_exc.stderr + '.') or six.text_type(ex))} if proc_exc.stdout: out['Given JSON output'] = proc_exc.stdout return out if 'invocation' in out: del out['invocation'] out['timeout'] = self.timeout return out
Call an Ansible module by invoking it. :param module: the name of the module. :param args: Arguments to the module :param kwargs: keywords to the module :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ansiblegate.py#L142-L183
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n", "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def run(self):\n '''\n wait for subprocess to terminate and return subprocess' return code.\n If timeout is reached, throw TimedProcTimeoutError\n '''\n def receive():\n if self.with_communicate:\n self.stdout, self.stderr = self.process.communicate(input=self.stdin)\n elif self.wait:\n self.process.wait()\n\n if not self.timeout:\n receive()\n else:\n rt = threading.Thread(target=receive)\n rt.start()\n rt.join(self.timeout)\n if rt.isAlive():\n # Subprocess cleanup (best effort)\n self.process.kill()\n\n def terminate():\n if rt.isAlive():\n self.process.terminate()\n threading.Timer(10, terminate).start()\n raise salt.exceptions.TimedProcTimeoutError(\n '{0} : Timed out after {1} seconds'.format(\n self.command,\n six.text_type(self.timeout),\n )\n )\n return self.process.returncode\n" ]
class AnsibleModuleCaller(object): DEFAULT_TIMEOUT = 1200 # seconds (20 minutes) OPT_TIMEOUT_KEY = 'ansible_timeout' def __init__(self, resolver): self._resolver = resolver self.timeout = self._resolver.opts.get(self.OPT_TIMEOUT_KEY, self.DEFAULT_TIMEOUT)
saltstack/salt
salt/modules/file.py
__clean_tmp
python
def __clean_tmp(sfn): ''' Clean out a template temp file ''' if sfn.startswith(os.path.join(tempfile.gettempdir(), salt.utils.files.TEMPFILE_PREFIX)): # Don't remove if it exists in file_roots (any saltenv) all_roots = itertools.chain.from_iterable( six.itervalues(__opts__['file_roots'])) in_roots = any(sfn.startswith(root) for root in all_roots) # Only clean up files that exist if os.path.exists(sfn) and not in_roots: os.remove(sfn)
Clean out a template temp file
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L88-L100
[ "def itervalues(d, **kw):\n return d.itervalues(**kw)\n" ]
# -*- coding: utf-8 -*- ''' Manage information about regular files, directories, and special files on the minion, set/read user, group, mode, and data ''' # TODO: We should add the capability to do u+r type operations here # some time in the future from __future__ import absolute_import, print_function, unicode_literals # Import python libs import datetime import errno import fnmatch import io import itertools import logging import operator import os import re import shutil import stat import string import sys import tempfile import time import glob import hashlib import mmap from collections import Iterable, Mapping from functools import reduce # pylint: disable=redefined-builtin # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range, zip from salt.ext.six.moves.urllib.parse import urlparse as _urlparse # pylint: enable=import-error,no-name-in-module,redefined-builtin try: import grp import pwd except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.atomicfile import salt.utils.data import salt.utils.dictupdate import salt.utils.filebuffer import salt.utils.files import salt.utils.find import salt.utils.functools import salt.utils.hashutils import salt.utils.itertools import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.templates import salt.utils.url import salt.utils.user from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError, get_error_message as _get_error_message from salt.utils.files import HASHES, HASHES_REVMAP log = logging.getLogger(__name__) __func_alias__ = { 'makedirs_': 'makedirs' } def __virtual__(): ''' Only work on POSIX-like systems ''' # win_file takes care of windows if salt.utils.platform.is_windows(): return ( False, 'The file execution module cannot be loaded: only available on ' 'non-Windows systems - use win_file instead.' ) return True def _error(ret, err_msg): ''' Common function for setting error information for return dicts ''' ret['result'] = False ret['comment'] = err_msg return ret def _binary_replace(old, new): ''' This function does NOT do any diffing, it just checks the old and new files to see if either is binary, and provides an appropriate string noting the difference between the two files. If neither file is binary, an empty string is returned. This function should only be run AFTER it has been determined that the files differ. ''' old_isbin = not __utils__['files.is_text'](old) new_isbin = not __utils__['files.is_text'](new) if any((old_isbin, new_isbin)): if all((old_isbin, new_isbin)): return 'Replace binary file' elif old_isbin: return 'Replace binary file with text file' elif new_isbin: return 'Replace text file with binary file' return '' def _get_bkroot(): ''' Get the location of the backup dir in the minion cache ''' # Get the cachedir from the minion config return os.path.join(__salt__['config.get']('cachedir'), 'file_backup') def _splitlines_preserving_trailing_newline(str): ''' Returns a list of the lines in the string, breaking at line boundaries and preserving a trailing newline (if present). Essentially, this works like ``str.striplines(False)`` but preserves an empty line at the end. This is equivalent to the following code: .. code-block:: python lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') ''' lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') return lines def gid_to_group(gid): ''' Convert the group id to the group name on this system gid gid to convert to a group name CLI Example: .. code-block:: bash salt '*' file.gid_to_group 0 ''' try: gid = int(gid) except ValueError: # This is not an integer, maybe it's already the group name? gid = group_to_gid(gid) if gid == '': # Don't even bother to feed it to grp return '' try: return grp.getgrgid(gid).gr_name except (KeyError, NameError): # If group is not present, fall back to the gid. return gid def group_to_gid(group): ''' Convert the group to the gid on this system group group to convert to its gid CLI Example: .. code-block:: bash salt '*' file.group_to_gid root ''' if group is None: return '' try: if isinstance(group, int): return group return grp.getgrnam(group).gr_gid except KeyError: return '' def get_gid(path, follow_symlinks=True): ''' Return the id of the group that owns a given file path file or directory of which to get the gid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_gid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('gid', -1) def get_group(path, follow_symlinks=True): ''' Return the group that owns a given file path file or directory of which to get the group follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_group /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('group', False) def uid_to_user(uid): ''' Convert a uid to a user name uid uid to convert to a username CLI Example: .. code-block:: bash salt '*' file.uid_to_user 0 ''' try: return pwd.getpwuid(uid).pw_name except (KeyError, NameError): # If user is not present, fall back to the uid. return uid def user_to_uid(user): ''' Convert user name to a uid user user name to convert to its uid CLI Example: .. code-block:: bash salt '*' file.user_to_uid root ''' if user is None: user = salt.utils.user.get_user() try: if isinstance(user, int): return user return pwd.getpwnam(user).pw_uid except KeyError: return '' def get_uid(path, follow_symlinks=True): ''' Return the id of the user that owns a given file path file or directory of which to get the uid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_uid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('uid', -1) def get_user(path, follow_symlinks=True): ''' Return the user that owns a given file path file or directory of which to get the user follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_user /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('user', False) def get_mode(path, follow_symlinks=True): ''' Return the mode of a file path file or directory of which to get the mode follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_mode /etc/passwd .. versionchanged:: 2014.1.0 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('mode', '') def set_mode(path, mode): ''' Set the mode of a file path file or directory of which to set the mode mode mode to set the path to CLI Example: .. code-block:: bash salt '*' file.set_mode /etc/passwd 0644 ''' path = os.path.expanduser(path) mode = six.text_type(mode).lstrip('0Oo') if not mode: mode = '0' if not os.path.exists(path): raise CommandExecutionError('{0}: File not found'.format(path)) try: os.chmod(path, int(mode, 8)) except Exception: return 'Invalid Mode ' + mode return get_mode(path) def lchown(path, user, group): ''' Chown a file, pass the file the desired user and group without following symlinks. path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 return os.lchown(path, uid, gid) def chown(path, user, group): ''' Chown a file, pass the file the desired user and group path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 if not os.path.exists(path): try: # Broken symlinks will return false, but still need to be chowned return os.lchown(path, uid, gid) except OSError: pass err += 'File not found' if err: return err return os.chown(path, uid, gid) def chgrp(path, group): ''' Change the group of a file path path to the file or directory group group owner CLI Example: .. code-block:: bash salt '*' file.chgrp /etc/passwd root ''' path = os.path.expanduser(path) user = get_user(path) return chown(path, user, group) def _cmp_attrs(path, attrs): ''' .. versionadded:: 2018.3.0 Compare attributes of a given file to given attributes. Returns a pair (list) where first item are attributes to add and second item are to be removed. Please take into account when using this function that some minions will not have lsattr installed. path path to file to compare attributes with. attrs string of attributes to compare against a given file ''' diff = [None, None] # lsattr for AIX is not the same thing as lsattr for linux. if salt.utils.platform.is_aix(): return None try: lattrs = lsattr(path).get(path, '') except AttributeError: # lsattr not installed return None old = [chr for chr in lattrs if chr not in attrs] if old: diff[1] = ''.join(old) new = [chr for chr in attrs if chr not in lattrs] if new: diff[0] = ''.join(new) return diff def lsattr(path): ''' .. versionadded:: 2018.3.0 .. versionchanged:: 2018.3.1 If ``lsattr`` is not installed on the system, ``None`` is returned. .. versionchanged:: 2018.3.4 If on ``AIX``, ``None`` is returned even if in filesystem as lsattr on ``AIX`` is not the same thing as the linux version. Obtain the modifiable attributes of the given file. If path is to a directory, an empty list is returned. path path to file to obtain attributes of. File/directory must exist. CLI Example: .. code-block:: bash salt '*' file.lsattr foo1.txt ''' if not salt.utils.path.which('lsattr') or salt.utils.platform.is_aix(): return None if not os.path.exists(path): raise SaltInvocationError("File or directory does not exist: " + path) cmd = ['lsattr', path] result = __salt__['cmd.run'](cmd, ignore_retcode=True, python_shell=False) results = {} for line in result.splitlines(): if not line.startswith('lsattr: '): vals = line.split(None, 1) results[vals[1]] = re.findall(r"[aAcCdDeijPsStTu]", vals[0]) return results def chattr(*files, **kwargs): ''' .. versionadded:: 2018.3.0 Change the attributes of files. This function accepts one or more files and the following options: operator Can be wither ``add`` or ``remove``. Determines whether attributes should be added or removed from files attributes One or more of the following characters: ``aAcCdDeijPsStTu``, representing attributes to add to/remove from files version a version number to assign to the file(s) flags One or more of the following characters: ``RVf``, representing flags to assign to chattr (recurse, verbose, suppress most errors) CLI Example: .. code-block:: bash salt '*' file.chattr foo1.txt foo2.txt operator=add attributes=ai salt '*' file.chattr foo3.txt operator=remove attributes=i version=2 ''' operator = kwargs.pop('operator', None) attributes = kwargs.pop('attributes', None) flags = kwargs.pop('flags', None) version = kwargs.pop('version', None) if (operator is None) or (operator not in ('add', 'remove')): raise SaltInvocationError( "Need an operator: 'add' or 'remove' to modify attributes.") if attributes is None: raise SaltInvocationError("Need attributes: [aAcCdDeijPsStTu]") cmd = ['chattr'] if operator == "add": attrs = '+{0}'.format(attributes) elif operator == "remove": attrs = '-{0}'.format(attributes) cmd.append(attrs) if flags is not None: cmd.append('-{0}'.format(flags)) if version is not None: cmd.extend(['-v', version]) cmd.extend(files) result = __salt__['cmd.run'](cmd, python_shell=False) if bool(result): raise CommandExecutionError( "chattr failed to run, possibly due to bad parameters.") return True def get_sum(path, form='sha256'): ''' Return the checksum for the given file. The following checksum algorithms are supported: * md5 * sha1 * sha224 * sha256 **(default)** * sha384 * sha512 path path to the file or directory form desired sum format CLI Example: .. code-block:: bash salt '*' file.get_sum /etc/passwd sha512 ''' path = os.path.expanduser(path) if not os.path.isfile(path): return 'File not found' return salt.utils.hashutils.get_hash(path, form, 4096) def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` path path to the file or directory form desired sum format chunk_size amount to sum at once CLI Example: .. code-block:: bash salt '*' file.get_hash /etc/shadow ''' return salt.utils.hashutils.get_hash(os.path.expanduser(path), form, chunk_size) def get_source_sum(file_name='', source='', source_hash=None, source_hash_name=None, saltenv='base'): ''' .. versionadded:: 2016.11.0 Used by :py:func:`file.get_managed <salt.modules.file.get_managed>` to obtain the hash and hash type from the parameters specified below. file_name Optional file name being managed, for matching with :py:func:`file.extract_hash <salt.modules.file.extract_hash>`. source Source file, as used in :py:mod:`file <salt.states.file>` and other states. If ``source_hash`` refers to a file containing hashes, then this filename will be used to match a filename in that file. If the ``source_hash`` is a hash expression, then this argument will be ignored. source_hash Hash file/expression, as used in :py:mod:`file <salt.states.file>` and other states. If this value refers to a remote URL or absolute path to a local file, it will be cached and :py:func:`file.extract_hash <salt.modules.file.extract_hash>` will be used to obtain a hash from it. source_hash_name Specific file name to look for when ``source_hash`` refers to a remote file, used to disambiguate ambiguous matches. saltenv : base Salt fileserver environment from which to retrieve the source_hash. This value will only be used when ``source_hash`` refers to a file on the Salt fileserver (i.e. one beginning with ``salt://``). CLI Example: .. code-block:: bash salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=499ae16dcae71eeb7c3a30c75ea7a1a6 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 source_hash_name=./dir2/foo.tar.gz ''' def _invalid_source_hash_format(): ''' DRY helper for reporting invalid source_hash input ''' raise CommandExecutionError( 'Source hash {0} format is invalid. The supported formats are: ' '1) a hash, 2) an expression in the format <hash_type>=<hash>, or ' '3) either a path to a local file containing hashes, or a URI of ' 'a remote hash file. Supported protocols for remote hash files ' 'are: {1}. The hash may also not be of a valid length, the ' 'following are supported hash types and lengths: {2}.'.format( source_hash, ', '.join(salt.utils.files.VALID_PROTOS), ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) hash_fn = None if os.path.isabs(source_hash): hash_fn = source_hash else: try: proto = _urlparse(source_hash).scheme if proto in salt.utils.files.VALID_PROTOS: hash_fn = __salt__['cp.cache_file'](source_hash, saltenv) if not hash_fn: raise CommandExecutionError( 'Source hash file {0} not found'.format(source_hash) ) else: if proto != '': # Some unsupported protocol (e.g. foo://) is being used. # We'll get into this else block if a hash expression # (like md5=<md5 checksum here>), but in those cases, the # protocol will be an empty string, in which case we avoid # this error condition. _invalid_source_hash_format() except (AttributeError, TypeError): _invalid_source_hash_format() if hash_fn is not None: ret = extract_hash(hash_fn, '', file_name, source, source_hash_name) if ret is None: _invalid_source_hash_format() ret['hsum'] = ret['hsum'].lower() return ret else: # The source_hash is a hash expression ret = {} try: ret['hash_type'], ret['hsum'] = \ [x.strip() for x in source_hash.split('=', 1)] except AttributeError: _invalid_source_hash_format() except ValueError: # No hash type, try to figure out by hash length if not re.match('^[{0}]+$'.format(string.hexdigits), source_hash): _invalid_source_hash_format() ret['hsum'] = source_hash source_hash_len = len(source_hash) if source_hash_len in HASHES_REVMAP: ret['hash_type'] = HASHES_REVMAP[source_hash_len] else: _invalid_source_hash_format() if ret['hash_type'] not in HASHES: raise CommandExecutionError( 'Invalid hash type \'{0}\'. Supported hash types are: {1}. ' 'Either remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to a supported type.' .format(ret['hash_type'], ', '.join(HASHES), ret['hsum']) ) else: hsum_len = len(ret['hsum']) if hsum_len not in HASHES_REVMAP: _invalid_source_hash_format() elif hsum_len != HASHES[ret['hash_type']]: raise CommandExecutionError( 'Invalid length ({0}) for hash type \'{1}\'. Either ' 'remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to \'{3}\''.format( hsum_len, ret['hash_type'], ret['hsum'], HASHES_REVMAP[hsum_len], ) ) ret['hsum'] = ret['hsum'].lower() return ret def check_hash(path, file_hash): ''' Check if a file matches the given hash string Returns ``True`` if the hash matches, otherwise ``False``. path Path to a file local to the minion. hash The hash to check against the file specified in the ``path`` argument. .. versionchanged:: 2016.11.4 For this and newer versions the hash can be specified without an accompanying hash type (e.g. ``e138491e9d5b97023cea823fe17bac22``), but for earlier releases it is necessary to also specify the hash type in the format ``<hash_type>=<hash_value>`` (e.g. ``md5=e138491e9d5b97023cea823fe17bac22``). CLI Example: .. code-block:: bash salt '*' file.check_hash /etc/fstab e138491e9d5b97023cea823fe17bac22 salt '*' file.check_hash /etc/fstab md5=e138491e9d5b97023cea823fe17bac22 ''' path = os.path.expanduser(path) if not isinstance(file_hash, six.string_types): raise SaltInvocationError('hash must be a string') for sep in (':', '='): if sep in file_hash: hash_type, hash_value = file_hash.split(sep, 1) break else: hash_value = file_hash hash_len = len(file_hash) hash_type = HASHES_REVMAP.get(hash_len) if hash_type is None: raise SaltInvocationError( 'Hash {0} (length: {1}) could not be matched to a supported ' 'hash type. The supported hash types and lengths are: ' '{2}'.format( file_hash, hash_len, ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) return get_hash(path, hash_type) == hash_value def find(path, *args, **kwargs): ''' Approximate the Unix ``find(1)`` command and return a list of paths that meet the specified criteria. The options include match criteria: .. code-block:: text name = path-glob # case sensitive iname = path-glob # case insensitive regex = path-regex # case sensitive iregex = path-regex # case insensitive type = file-types # match any listed type user = users # match any listed user group = groups # match any listed group size = [+-]number[size-unit] # default unit = byte mtime = interval # modified since date grep = regex # search file contents and/or actions: .. code-block:: text delete [= file-types] # default type = 'f' exec = command [arg ...] # where {} is replaced by pathname print [= print-opts] and/or depth criteria: .. code-block:: text maxdepth = maximum depth to transverse in path mindepth = minimum depth to transverse before checking files or directories The default action is ``print=path`` ``path-glob``: .. code-block:: text * = match zero or more chars ? = match any char [abc] = match a, b, or c [!abc] or [^abc] = match anything except a, b, and c [x-y] = match chars x through y [!x-y] or [^x-y] = match anything except chars x through y {a,b,c} = match a or b or c ``path-regex``: a Python Regex (regular expression) pattern to match pathnames ``file-types``: a string of one or more of the following: .. code-block:: text a: all file types b: block device c: character device d: directory p: FIFO (named pipe) f: plain file l: symlink s: socket ``users``: a space and/or comma separated list of user names and/or uids ``groups``: a space and/or comma separated list of group names and/or gids ``size-unit``: .. code-block:: text b: bytes k: kilobytes m: megabytes g: gigabytes t: terabytes interval: .. code-block:: text [<num>w] [<num>d] [<num>h] [<num>m] [<num>s] where: w: week d: day h: hour m: minute s: second print-opts: a comma and/or space separated list of one or more of the following: .. code-block:: text group: group name md5: MD5 digest of file contents mode: file permissions (as integer) mtime: last modification time (as time_t) name: file basename path: file absolute path size: file size in bytes type: file type user: user name CLI Examples: .. code-block:: bash salt '*' file.find / type=f name=\\*.bak size=+10m salt '*' file.find /var mtime=+30d size=+10m print=path,size,mtime salt '*' file.find /var/log name=\\*.[0-9] mtime=+30d size=+10m delete ''' if 'delete' in args: kwargs['delete'] = 'f' elif 'print' in args: kwargs['print'] = 'path' try: finder = salt.utils.find.Finder(kwargs) except ValueError as ex: return 'error: {0}'.format(ex) ret = [item for i in [finder.find(p) for p in glob.glob(os.path.expanduser(path))] for item in i] ret.sort() return ret def _sed_esc(string, escape_all=False): ''' Escape single quotes and forward slashes ''' special_chars = "^.[$()|*+?{" string = string.replace("'", "'\"'\"'").replace("/", "\\/") if escape_all is True: for char in special_chars: string = string.replace(char, "\\" + char) return string def sed(path, before, after, limit='', backup='.bak', options='-r -e', flags='g', escape_all=False, negate_match=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup options : ``-r -e`` Options to pass to sed flags : ``g`` Flags to modify the sed search; e.g., ``i`` for case-insensitive pattern matching negate_match : False Negate the search command (``!``) .. versionadded:: 0.17.0 Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # path = os.path.expanduser(path) if not os.path.exists(path): return False # Mandate that before and after are strings before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.append('-i{0}'.format(backup) if backup else '-i') cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}{negate_match}s/{before}/{after}/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', negate_match='!' if negate_match else '', before=before, after=after, flags=flags ) ) cmd.append(path) return __salt__['cmd.run_all'](cmd, python_shell=False) def sed_contains(path, text, limit='', flags='g'): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the file at ``path`` contains ``text``. Utilizes sed to perform the search (line-wise search). Note: the ``p`` flag will be added to any flags you pass in. CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' # Largely inspired by Fabric's contrib.files.contains() path = os.path.expanduser(path) if not os.path.exists(path): return False before = _sed_esc(six.text_type(text), False) limit = _sed_esc(six.text_type(limit), False) options = '-n -r -e' if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}s/{before}/$/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', before=before, flags='p{0}'.format(flags) ) ) cmd.append(path) result = __salt__['cmd.run'](cmd, python_shell=False) return bool(result) def psed(path, before, after, limit='', backup='.bak', flags='gMS', escape_all=False, multi=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file (pure Python version) Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup flags : ``gMS`` Flags to modify the search. Valid values are: - ``g``: Replace all occurrences of the pattern, not just the first. - ``I``: Ignore case. - ``L``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\s`` and ``\\S`` dependent on the locale. - ``M``: Treat multiple lines as a single line. - ``S``: Make `.` match all characters, including newlines. - ``U``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\d``, ``\\D``, ``\\s`` and ``\\S`` dependent on Unicode. - ``X``: Verbose (whitespace is ignored). multi: ``False`` If True, treat the entire file as a single line Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # # Mandate that before and after are strings path = os.path.expanduser(path) multi = bool(multi) before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) # The pattern to replace with does not need to be escaped!!! # after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) shutil.copy2(path, '{0}{1}'.format(path, backup)) with salt.utils.files.fopen(path, 'w') as ofile: with salt.utils.files.fopen('{0}{1}'.format(path, backup), 'r') as ifile: if multi is True: for line in ifile.readline(): ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(line), before, after, limit, flags ) ) ) else: ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(ifile.read()), before, after, limit, flags ) ) ) RE_FLAG_TABLE = {'I': re.I, 'L': re.L, 'M': re.M, 'S': re.S, 'U': re.U, 'X': re.X} def _psed(text, before, after, limit, flags): ''' Does the actual work for file.psed, so that single lines can be passed in ''' atext = text if limit: limit = re.compile(limit) comps = text.split(limit) atext = ''.join(comps[1:]) count = 1 if 'g' in flags: count = 0 flags = flags.replace('g', '') aflags = 0 for flag in flags: aflags |= RE_FLAG_TABLE[flag] before = re.compile(before, flags=aflags) text = re.sub(before, after, atext, count=count) return text def uncomment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Uncomment specified commented lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be uncommented. This regex should not include the comment character. A leading ``^`` character will be stripped for convenience (for easily switching between comment() and uncomment()). char : ``#`` The character to remove in order to uncomment a line backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup CLI Example: .. code-block:: bash salt '*' file.uncomment /etc/hosts.deny 'ALL: PARANOID' ''' return comment_line(path=path, regex=regex, char=char, cmnt=False, backup=backup) def comment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Comment out specified lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be commented; this pattern will be wrapped in parenthesis and will move any preceding/trailing ``^`` or ``$`` characters outside the parenthesis (e.g., the pattern ``^foo$`` will be rewritten as ``^(foo)$``) char : ``#`` The character to be inserted at the beginning of a line in order to comment it out backup : ``.bak`` The file will be backed up before edit with this file extension .. warning:: This backup will be overwritten each time ``sed`` / ``comment`` / ``uncomment`` is called. Meaning the backup will only be useful after the first invocation. CLI Example: .. code-block:: bash salt '*' file.comment /etc/modules pcspkr ''' return comment_line(path=path, regex=regex, char=char, cmnt=True, backup=backup) def comment_line(path, regex, char='#', cmnt=True, backup='.bak'): r''' Comment or Uncomment a line in a text file. :param path: string The full path to the text file. :param regex: string A regex expression that begins with ``^`` that will find the line you wish to comment. Can be as simple as ``^color =`` :param char: string The character used to comment a line in the type of file you're referencing. Default is ``#`` :param cmnt: boolean True to comment the line. False to uncomment the line. Default is True. :param backup: string The file extension to give the backup file. Default is ``.bak`` Set to False/None to not keep a backup. :return: boolean Returns True if successful, False if not CLI Example: The following example will comment out the ``pcspkr`` line in the ``/etc/modules`` file using the default ``#`` character and create a backup file named ``modules.bak`` .. code-block:: bash salt '*' file.comment_line '/etc/modules' '^pcspkr' CLI Example: The following example will uncomment the ``log_level`` setting in ``minion`` config file if it is set to either ``warning``, ``info``, or ``debug`` using the ``#`` character and create a backup file named ``minion.bk`` .. code-block:: bash salt '*' file.comment_line 'C:\salt\conf\minion' '^log_level: (warning|info|debug)' '#' False '.bk' ''' # Get the regex for comment or uncomment if cmnt: regex = '{0}({1}){2}'.format( '^' if regex.startswith('^') else '', regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') else: regex = r'^{0}\s*({1}){2}'.format( char, regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') # Load the real path to the file path = os.path.realpath(os.path.expanduser(path)) # Make sure the file exists if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) # Make sure it is a text file if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}'.format(path)) # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes found = False # Dictionaries for comparing changes orig_file = [] new_file = [] # Buffer size for fopen bufsize = os.path.getsize(path) try: # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: # Is it in this line line = salt.utils.stringutils.to_unicode(line) if re.match(regex, line): # Load lines into dictionaries, set found to True orig_file.append(line) if cmnt: new_file.append('{0}{1}'.format(char, line)) else: new_file.append(line.lstrip(char)) found = True except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) # We've searched the whole file. If we didn't find anything, return False if not found: return False if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Create a copy to read from and to use as a backup later try: temp_file = _mkstemp_copy(path=path, preserve_inode=False) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) try: # Open the file in write mode mode = 'wb' if six.PY2 and salt.utils.platform.is_windows() else 'w' with salt.utils.files.fopen(path, mode=mode, buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: line = salt.utils.stringutils.to_unicode(line) try: # Is it in this line if re.match(regex, line): # Write the new line if cmnt: wline = '{0}{1}'.format(char, line) else: wline = line.lstrip(char) else: # Write the existing line (no change) wline = line wline = salt.utils.stringutils.to_bytes(wline) \ if six.PY2 and salt.utils.platform.is_windows() \ else salt.utils.stringutils.to_str(wline) w_file.write(wline) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if backup: # Move the backup file to the original directory backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: os.remove(temp_file) if not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) # Return a diff using the two dictionaries return __utils__['stringutils.get_diff'](orig_file, new_file) def _get_flags(flags): ''' Return an integer appropriate for use as a flag for the re module from a list of human-readable strings .. code-block:: python >>> _get_flags(['MULTILINE', 'IGNORECASE']) 10 >>> _get_flags('MULTILINE') 8 >>> _get_flags(2) 2 ''' if isinstance(flags, six.string_types): flags = [flags] if isinstance(flags, Iterable) and not isinstance(flags, Mapping): _flags_acc = [] for flag in flags: _flag = getattr(re, six.text_type(flag).upper()) if not isinstance(_flag, six.integer_types): raise SaltInvocationError( 'Invalid re flag given: {0}'.format(flag) ) _flags_acc.append(_flag) return reduce(operator.__or__, _flags_acc) elif isinstance(flags, six.integer_types): return flags else: raise SaltInvocationError( 'Invalid re flags: "{0}", must be given either as a single flag ' 'string, a list of strings, or as an integer'.format(flags) ) def _add_flags(flags, new_flags): ''' Combine ``flags`` and ``new_flags`` ''' flags = _get_flags(flags) new_flags = _get_flags(new_flags) return flags | new_flags def _mkstemp_copy(path, preserve_inode=True): ''' Create a temp file and move/copy the contents of ``path`` to the temp file. Return the path to the temp file. path The full path to the file whose contents will be moved/copied to a temp file. Whether it's moved or copied depends on the value of ``preserve_inode``. preserve_inode Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). Default is ``True``. ''' temp_file = None # Create the temp file try: temp_file = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to create temp file. " "Exception: {0}".format(exc) ) # use `copy` to preserve the inode of the # original file, and thus preserve hardlinks # to the inode. otherwise, use `move` to # preserve prior behavior, which results in # writing the file to a new inode. if preserve_inode: try: shutil.copy2(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to copy file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: try: shutil.move(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) return temp_file def _starts_till(src, probe, strip_comments=True): ''' Returns True if src and probe at least matches at the beginning till some point. ''' def _strip_comments(txt): ''' Strip possible comments. Usually comments are one or two symbols at the beginning of the line, separated with space ''' buff = txt.split(" ", 1) return len(buff) == 2 and len(buff[0]) < 2 and buff[1] or txt def _to_words(txt): ''' Split by words ''' return txt and [w for w in txt.strip().split(" ") if w.strip()] or txt no_match = -1 equal = 0 if not src or not probe: return no_match src = src.rstrip('\n\r') probe = probe.rstrip('\n\r') if src == probe: return equal src = _to_words(strip_comments and _strip_comments(src) or src) probe = _to_words(strip_comments and _strip_comments(probe) or probe) a_buff, b_buff = len(src) < len(probe) and (src, probe) or (probe, src) b_buff = ' '.join(b_buff) for idx in range(len(a_buff)): prb = ' '.join(a_buff[:-(idx + 1)]) if prb and b_buff.startswith(prb): return idx return no_match def _regex_to_static(src, regex): ''' Expand regular expression to static match. ''' if not src or not regex: return None try: compiled = re.compile(regex, re.DOTALL) src = [line for line in src if compiled.search(line) or line.count(regex)] except Exception as ex: raise CommandExecutionError("{0}: '{1}'".format(_get_error_message(ex), regex)) return src and src or [] def _assert_occurrence(probe, target, amount=1): ''' Raise an exception, if there are different amount of specified occurrences in src. ''' occ = len(probe) if occ > amount: msg = 'more than' elif occ < amount: msg = 'less than' elif not occ: msg = 'no' else: msg = None if msg: raise CommandExecutionError('Found {0} expected occurrences in "{1}" expression'.format(msg, target)) return occ def _set_line_indent(src, line, indent): ''' Indent the line with the source line. ''' if not indent: return line idt = [] for c in src: if c not in ['\t', ' ']: break idt.append(c) return ''.join(idt) + line.lstrip() def _get_eol(line): match = re.search('((?<!\r)\n|\r(?!\n)|\r\n)$', line) return match and match.group() or '' def _set_line_eol(src, line): ''' Add line ending ''' line_ending = _get_eol(src) or os.linesep return line.rstrip() + line_ending def _insert_line_before(idx, body, content, indent): if not idx or (idx and _starts_till(body[idx - 1], content) < 0): cnd = _set_line_indent(body[idx], content, indent) body.insert(idx, cnd) return body def _insert_line_after(idx, body, content, indent): # No duplicates or append, if "after" is the last line next_line = idx + 1 < len(body) and body[idx + 1] or None if next_line is None or _starts_till(next_line, content) < 0: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) return body def line(path, content=None, match=None, mode=None, location=None, before=None, after=None, show_changes=True, backup=False, quiet=False, indent=True): ''' .. versionadded:: 2015.8.0 Edit a line in the configuration file. The ``path`` and ``content`` arguments are required, as well as passing in one of the ``mode`` options. path Filesystem path to the file to be edited. content Content of the line. Allowed to be empty if mode=delete. match Match the target line for an action by a fragment of a string or regular expression. If neither ``before`` nor ``after`` are provided, and ``match`` is also ``None``, match becomes the ``content`` value. mode Defines how to edit a line. One of the following options is required: - ensure If line does not exist, it will be added. This is based on the ``content`` argument. - replace If line already exists, it will be replaced. - delete Delete the line, once found. - insert Insert a line. .. note:: If ``mode=insert`` is used, at least one of the following options must also be defined: ``location``, ``before``, or ``after``. If ``location`` is used, it takes precedence over the other two options. location Defines where to place content in the line. Note this option is only used when ``mode=insert`` is specified. If a location is passed in, it takes precedence over both the ``before`` and ``after`` kwargs. Valid locations are: - start Place the content at the beginning of the file. - end Place the content at the end of the file. before Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. after Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. show_changes Output a unified diff of the old file and the new file. If ``False`` return a boolean if any changes were made. Default is ``True`` .. note:: Using this option will store two copies of the file in-memory (the original version and the edited version) in order to generate the diff. backup Create a backup of the original file with the extension: "Year-Month-Day-Hour-Minutes-Seconds". quiet Do not raise any exceptions. E.g. ignore the fact that the file that is tried to be edited does not exist and nothing really happened. indent Keep indentation with the previous line. This option is not considered when the ``delete`` mode is specified. CLI Example: .. code-block:: bash salt '*' file.line /etc/nsswitch.conf "networks:\tfiles dns" after="hosts:.*?" mode='ensure' .. note:: If an equal sign (``=``) appears in an argument to a Salt command, it is interpreted as a keyword argument in the format of ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.line /path/to/file content="CREATEMAIL_SPOOL=no" match="CREATE_MAIL_SPOOL=yes" mode="replace" ''' path = os.path.realpath(os.path.expanduser(path)) if not os.path.isfile(path): if not quiet: raise CommandExecutionError('File "{0}" does not exists or is not a file.'.format(path)) return False # No changes had happened mode = mode and mode.lower() or mode if mode not in ['insert', 'ensure', 'delete', 'replace']: if mode is None: raise CommandExecutionError('Mode was not defined. How to process the file?') else: raise CommandExecutionError('Unknown mode: "{0}"'.format(mode)) # We've set the content to be empty in the function params but we want to make sure # it gets passed when needed. Feature #37092 empty_content_modes = ['delete'] if mode not in empty_content_modes and content is None: raise CommandExecutionError('Content can only be empty if mode is "{0}"'.format(', '.join(empty_content_modes))) del empty_content_modes # Before/after has privilege. If nothing defined, match is used by content. if before is None and after is None and not match: match = content with salt.utils.files.fopen(path, mode='r') as fp_: body = salt.utils.data.decode_list(fp_.readlines()) body_before = hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() # Add empty line at the end if last line ends with eol. # Allows simpler code if body and _get_eol(body[-1]): body.append('') after = _regex_to_static(body, after) before = _regex_to_static(body, before) match = _regex_to_static(body, match) if os.stat(path).st_size == 0 and mode in ('delete', 'replace'): log.warning('Cannot find text to %s. File \'%s\' is empty.', mode, path) body = [] elif mode == 'delete' and match: body = [line for line in body if line != match[0]] elif mode == 'replace' and match: idx = body.index(match[0]) file_line = body.pop(idx) body.insert(idx, _set_line_indent(file_line, content, indent)) elif mode == 'insert': if not location and not before and not after: raise CommandExecutionError('On insert must be defined either "location" or "before/after" conditions.') if not location: if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') out = [] in_range = False for line in body: if line == after[0]: in_range = True elif line == before[0] and in_range: cnd = _set_line_indent(line, content, indent) out.append(cnd) out.append(line) body = out if before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif after and not before: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: if location == 'start': if body: body.insert(0, _set_line_eol(body[0], content)) else: body.append(content + os.linesep) elif location == 'end': body.append(_set_line_indent(body[-1], content, indent) if body else content) elif mode == 'ensure': if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') is_there = bool([l for l in body if l.count(content)]) if not is_there: idx = body.index(after[0]) if idx < (len(body) - 1) and body[idx + 1] == before[0]: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) else: raise CommandExecutionError('Found more than one line between ' 'boundaries "before" and "after".') elif before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif not before and after: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: raise CommandExecutionError("Wrong conditions? " "Unable to ensure line without knowing " "where to put it before and/or after.") if body: for idx, line in enumerate(body): if not _get_eol(line) and idx+1 < len(body): prev = idx and idx-1 or 1 body[idx] = _set_line_eol(body[prev], line) # We do not need empty line at the end anymore if '' == body[-1]: body.pop() changed = body_before != hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() if backup and changed and __opts__['test'] is False: try: temp_file = _mkstemp_copy(path=path, preserve_inode=True) shutil.move(temp_file, '{0}.{1}'.format(path, time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime()))) except (OSError, IOError) as exc: raise CommandExecutionError("Unable to create the backup file of {0}. Exception: {1}".format(path, exc)) changes_diff = None if changed: if show_changes: with salt.utils.files.fopen(path, 'r') as fp_: path_content = salt.utils.data.decode_list(fp_.read().splitlines(True)) changes_diff = __utils__['stringutils.get_diff'](path_content, body) if __opts__['test'] is False: fh_ = None try: # Make sure we match the file mode from salt.utils.files.fopen if six.PY2 and salt.utils.platform.is_windows(): mode = 'wb' body = salt.utils.data.encode_list(body) else: mode = 'w' body = salt.utils.data.decode_list(body, to_str=True) fh_ = salt.utils.atomicfile.atomic_open(path, mode) fh_.writelines(body) finally: if fh_: fh_.close() return show_changes and changes_diff or changed def replace(path, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, backup='.bak', dry_run=False, search_only=False, show_changes=True, ignore_if_missing=False, preserve_inode=True, backslash_literal=False, ): ''' .. versionadded:: 0.17.0 Replace occurrences of a pattern in a file. If ``show_changes`` is ``True``, then a diff of what changed will be returned, otherwise a ``True`` will be returned when changes are made, and ``False`` when no changes are made. This is a pure Python implementation that wraps Python's :py:func:`~re.sub`. path Filesystem path to the file to be edited. If a symlink is specified, it will be resolved to its target. pattern A regular expression, to be matched using Python's :py:func:`~re.search`. repl The replacement text count : 0 Maximum number of pattern occurrences to be replaced. If count is a positive integer ``n``, only ``n`` occurrences will be replaced, otherwise all occurrences will be replaced. flags (list or int) A list of flags defined in the ``re`` module documentation from the Python standard library. Each list item should be a string that will correlate to the human-friendly flag name. E.g., ``['IGNORECASE', 'MULTILINE']``. Optionally, ``flags`` may be an int, with a value corresponding to the XOR (``|``) of all the desired flags. Defaults to 8 (which supports 'MULTILINE'). bufsize (int or str) How much of the file to buffer into memory at once. The default value ``1`` processes one line at a time. The special value ``file`` may be specified which will read the entire file into memory before processing. append_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True``, and pattern is not found, then the content will be appended to the file. prepend_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True`` and pattern is not found, then the content will be prepended to the file. not_found_content .. versionadded:: 2014.7.0 Content to use for append/prepend if not found. If None (default), uses ``repl``. Useful when ``repl`` uses references to group in pattern. backup : .bak The file extension to use for a backup of the file before editing. Set to ``False`` to skip making a backup. dry_run : False If set to ``True``, no changes will be made to the file, the function will just return the changes that would have been made (or a ``True``/``False`` value if ``show_changes`` is set to ``False``). search_only : False If set to true, this no changes will be performed on the file, and this function will simply return ``True`` if the pattern was matched, and ``False`` if not. show_changes : True If ``True``, return a diff of changes made. Otherwise, return ``True`` if changes were made, and ``False`` if not. .. note:: Using this option will store two copies of the file in memory (the original version and the edited version) in order to generate the diff. This may not normally be a concern, but could impact performance if used with large files. ignore_if_missing : False .. versionadded:: 2015.8.0 If set to ``True``, this function will simply return ``False`` if the file doesn't exist. Otherwise, an error will be thrown. preserve_inode : True .. versionadded:: 2015.8.0 Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). backslash_literal : False .. versionadded:: 2016.11.7 Interpret backslashes as literal backslashes for the repl and not escape characters. This will help when using append/prepend so that the backslashes are not interpreted for the repl on the second run of the state. If an equal sign (``=``) appears in an argument to a Salt command it is interpreted as a keyword argument in the format ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.replace /path/to/file pattern='=' repl=':' salt '*' file.replace /path/to/file pattern="bind-address\\s*=" repl='bind-address:' CLI Examples: .. code-block:: bash salt '*' file.replace /etc/httpd/httpd.conf pattern='LogLevel warn' repl='LogLevel info' salt '*' file.replace /some/file pattern='before' repl='after' flags='[MULTILINE, IGNORECASE]' ''' symlink = False if is_link(path): symlink = True target_path = os.readlink(path) given_path = os.path.expanduser(path) path = os.path.realpath(os.path.expanduser(path)) if not os.path.exists(path): if ignore_if_missing: return False else: raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if search_only and (append_if_not_found or prepend_if_not_found): raise SaltInvocationError( 'search_only cannot be used with append/prepend_if_not_found' ) if append_if_not_found and prepend_if_not_found: raise SaltInvocationError( 'Only one of append and prepend_if_not_found is permitted' ) flags_num = _get_flags(flags) cpattern = re.compile(salt.utils.stringutils.to_bytes(pattern), flags_num) filesize = os.path.getsize(path) if bufsize == 'file': bufsize = filesize # Search the file; track if any changes have been made for the return val has_changes = False orig_file = [] # used for show_changes and change detection new_file = [] # used for show_changes and change detection if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Avoid TypeErrors by forcing repl to be bytearray related to mmap # Replacement text may contains integer: 123 for example repl = salt.utils.stringutils.to_bytes(six.text_type(repl)) if not_found_content: not_found_content = salt.utils.stringutils.to_bytes(not_found_content) found = False temp_file = None content = salt.utils.stringutils.to_unicode(not_found_content) \ if not_found_content and (prepend_if_not_found or append_if_not_found) \ else salt.utils.stringutils.to_unicode(repl) try: # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes r_data = None # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: try: # mmap throws a ValueError if the file is empty. r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) except (ValueError, mmap.error): # size of file in /proc is 0, but contains data r_data = salt.utils.stringutils.to_bytes("".join(r_file)) if search_only: # Just search; bail as early as a match is found if re.search(cpattern, r_data): return True # `with` block handles file closure else: return False else: result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) # found anything? (even if no change) if nrepl > 0: found = True # Identity check the potential change has_changes = True if pattern != repl else has_changes if prepend_if_not_found or append_if_not_found: # Search for content, to avoid pre/appending the # content if it was pre/appended in a previous run. if re.search(salt.utils.stringutils.to_bytes('^{0}($|(?=\r\n))'.format(re.escape(content))), r_data, flags=flags_num): # Content was found, so set found. found = True orig_file = r_data.read(filesize).splitlines(True) \ if isinstance(r_data, mmap.mmap) \ else r_data.splitlines(True) new_file = result.splitlines(True) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() if has_changes and not dry_run: # Write the replacement text in this block. try: # Create a copy to read from and to use as a backup later temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) r_data = None try: # Open the file in write mode with salt.utils.files.fopen(path, mode='w', buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='r', buffering=bufsize) as r_file: r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) try: w_file.write(salt.utils.stringutils.to_str(result)) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if not found and (append_if_not_found or prepend_if_not_found): if not_found_content is None: not_found_content = repl if prepend_if_not_found: new_file.insert(0, not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) else: # append_if_not_found # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(salt.utils.stringutils.to_bytes(os.linesep)): new_file[-1] += salt.utils.stringutils.to_bytes(os.linesep) new_file.append(not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) has_changes = True if not dry_run: try: # Create a copy to read from and for later use as a backup temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line)) finally: fh_.close() if backup and has_changes and not dry_run: # keep the backup only if it was requested # and only if there were any changes backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) if symlink: symlink_backup = '{0}{1}'.format(given_path, backup) target_backup = '{0}{1}'.format(target_path, backup) # Always clobber any existing symlink backup # to match the behaviour of the 'backup' option try: os.symlink(target_backup, symlink_backup) except OSError: os.remove(symlink_backup) os.symlink(target_backup, symlink_backup) except Exception: raise CommandExecutionError( "Unable create backup symlink '{0}'. " "Target was '{1}'. " "Exception: {2}".format(symlink_backup, target_backup, exc) ) elif temp_file: try: os.remove(temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to delete temp file '{0}'. " "Exception: {1}".format(temp_file, exc) ) if not dry_run and not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) differences = __utils__['stringutils.get_diff'](orig_file, new_file) if show_changes: return differences # We may have found a regex line match but don't need to change the line # (for situations where the pattern also matches the repl). Revert the # has_changes flag to False if the final result is unchanged. if not differences: has_changes = False return has_changes def blockreplace(path, marker_start='#-- start managed zone --', marker_end='#-- end managed zone --', content='', append_if_not_found=False, prepend_if_not_found=False, backup='.bak', dry_run=False, show_changes=True, append_newline=False, insert_before_match=None, insert_after_match=None): ''' .. versionadded:: 2014.1.0 Replace content of a text block in a file, delimited by line markers A block of content delimited by comments can help you manage several lines entries without worrying about old entries removal. .. note:: This function will store two copies of the file in-memory (the original version and the edited version) in order to detect changes and only edit the targeted file if necessary. path Filesystem path to the file to be edited marker_start The line content identifying a line as the start of the content block. Note that the whole line containing this marker will be considered, so whitespace or extra content before or after the marker is included in final output marker_end The line content identifying the end of the content block. As of versions 2017.7.5 and 2018.3.1, everything up to the text matching the marker will be replaced, so it's important to ensure that your marker includes the beginning of the text you wish to replace. content The content to be used between the two lines identified by marker_start and marker_stop. append_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be appended to the file. prepend_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be prepended to the file. insert_before_match If markers are not found, this parameter can be set to a regex which will insert the block before the first found occurrence in the file. .. versionadded:: Neon insert_after_match If markers are not found, this parameter can be set to a regex which will insert the block after the first found occurrence in the file. .. versionadded:: Neon backup The file extension to use for a backup of the file if any edit is made. Set to ``False`` to skip making a backup. dry_run : False If ``True``, do not make any edits to the file and simply return the changes that *would* be made. show_changes : True Controls how changes are presented. If ``True``, this function will return a unified diff of the changes made. If False, then it will return a boolean (``True`` if any changes were made, otherwise ``False``). append_newline : False Controls whether or not a newline is appended to the content block. If the value of this argument is ``True`` then a newline will be added to the content block. If it is ``False``, then a newline will *not* be added to the content block. If it is ``None`` then a newline will only be added to the content block if it does not already end in a newline. .. versionadded:: 2016.3.4 .. versionchanged:: 2017.7.5,2018.3.1 New behavior added when value is ``None``. .. versionchanged:: 2019.2.0 The default value of this argument will change to ``None`` to match the behavior of the :py:func:`file.blockreplace state <salt.states.file.blockreplace>` CLI Example: .. code-block:: bash salt '*' file.blockreplace /etc/hosts '#-- start managed zone foobar : DO NOT EDIT --' \\ '#-- end managed zone foobar --' $'10.0.1.1 foo.foobar\\n10.0.1.2 bar.foobar' True ''' exclusive_params = [append_if_not_found, prepend_if_not_found, bool(insert_before_match), bool(insert_after_match)] if sum(exclusive_params) > 1: raise SaltInvocationError( 'Only one of append_if_not_found, prepend_if_not_found,' ' insert_before_match, and insert_after_match is permitted' ) path = os.path.expanduser(path) if not os.path.exists(path): raise SaltInvocationError('File not found: {0}'.format(path)) try: file_encoding = __utils__['files.get_encoding'](path) except CommandExecutionError: file_encoding = None if __utils__['files.is_binary'](path): if not file_encoding: raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if insert_before_match or insert_after_match: if insert_before_match: if not isinstance(insert_before_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_before_match parameter.' ) elif insert_after_match: if not isinstance(insert_after_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_after_match parameter.' ) if append_newline is None and not content.endswith((os.linesep, '\n')): append_newline = True # Split the content into a list of lines, removing newline characters. To # ensure that we handle both Windows and POSIX newlines, first split on # Windows newlines, and then split on POSIX newlines. split_content = [] for win_line in content.split('\r\n'): for content_line in win_line.split('\n'): split_content.append(content_line) line_count = len(split_content) has_changes = False orig_file = [] new_file = [] in_block = False block_found = False linesep = None def _add_content(linesep, lines=None, include_marker_start=True, end_line=None): if lines is None: lines = [] include_marker_start = True if end_line is None: end_line = marker_end end_line = end_line.rstrip('\r\n') + linesep if include_marker_start: lines.append(marker_start + linesep) if split_content: for index, content_line in enumerate(split_content, 1): if index != line_count: lines.append(content_line + linesep) else: # We're on the last line of the content block if append_newline: lines.append(content_line + linesep) lines.append(end_line) else: lines.append(content_line + end_line) else: lines.append(end_line) return lines # We do not use in-place editing to avoid file attrs modifications when # no changes are required and to avoid any file access on a partially # written file. try: fi_file = io.open(path, mode='r', encoding=file_encoding, newline='') for line in fi_file: write_line_to_new_file = True if linesep is None: # Auto-detect line separator if line.endswith('\r\n'): linesep = '\r\n' elif line.endswith('\n'): linesep = '\n' else: # No newline(s) in file, fall back to system's linesep linesep = os.linesep if marker_start in line: # We've entered the content block in_block = True else: if in_block: # We're not going to write the lines from the old file to # the new file until we have exited the block. write_line_to_new_file = False marker_end_pos = line.find(marker_end) if marker_end_pos != -1: # End of block detected in_block = False # We've found and exited the block block_found = True _add_content(linesep, lines=new_file, include_marker_start=False, end_line=line[marker_end_pos:]) # Save the line from the original file orig_file.append(line) if write_line_to_new_file: new_file.append(line) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read from {0}: {1}'.format(path, exc) ) finally: if linesep is None: # If the file was empty, we will not have set linesep yet. Assume # the system's line separator. This is needed for when we # prepend/append later on. linesep = os.linesep try: fi_file.close() except Exception: pass if in_block: # unterminated block => bad, always fail raise CommandExecutionError( 'Unterminated marked block. End of file reached before marker_end.' ) if not block_found: if prepend_if_not_found: # add the markers and content at the beginning of file prepended_content = _add_content(linesep) prepended_content.extend(new_file) new_file = prepended_content block_found = True elif append_if_not_found: # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(linesep): new_file[-1] += linesep # add the markers and content at the end of file _add_content(linesep, lines=new_file) block_found = True elif insert_before_match or insert_after_match: match_regex = insert_before_match or insert_after_match match_idx = [i for i, item in enumerate(orig_file) if re.search(match_regex, item)] if match_idx: match_idx = match_idx[0] for line in _add_content(linesep): if insert_after_match: match_idx += 1 new_file.insert(match_idx, line) if insert_before_match: match_idx += 1 block_found = True if not block_found: raise CommandExecutionError( 'Cannot edit marked block. Markers were not found in file.' ) diff = __utils__['stringutils.get_diff'](orig_file, new_file) has_changes = diff is not '' if has_changes and not dry_run: # changes detected # backup file attrs perms = {} perms['user'] = get_user(path) perms['group'] = get_group(path) perms['mode'] = salt.utils.files.normalize_mode(get_mode(path)) # backup old content if backup is not False: backup_path = '{0}{1}'.format(path, backup) shutil.copy2(path, backup_path) # copy2 does not preserve ownership check_perms(backup_path, None, perms['user'], perms['group'], perms['mode']) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line, encoding=file_encoding)) finally: fh_.close() # this may have overwritten file attrs check_perms(path, None, perms['user'], perms['group'], perms['mode']) if show_changes: return diff return has_changes def search(path, pattern, flags=8, bufsize=1, ignore_if_missing=False, multiline=False ): ''' .. versionadded:: 0.17.0 Search for occurrences of a pattern in a file Except for multiline, params are identical to :py:func:`~salt.modules.file.replace`. multiline If true, inserts 'MULTILINE' into ``flags`` and sets ``bufsize`` to 'file'. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' file.search /etc/crontab 'mymaintenance.sh' ''' if multiline: flags = _add_flags(flags, 'MULTILINE') bufsize = 'file' # This function wraps file.replace on purpose in order to enforce # consistent usage, compatible regex's, expected behavior, *and* bugs. :) # Any enhancements or fixes to one should affect the other. return replace(path, pattern, '', flags=flags, bufsize=bufsize, dry_run=True, search_only=True, show_changes=False, ignore_if_missing=ignore_if_missing) def patch(originalfile, patchfile, options='', dry_run=False): ''' .. versionadded:: 0.10.4 Apply a patch to a file or directory. Equivalent to: .. code-block:: bash patch <options> -i <patchfile> <originalfile> Or, when a directory is patched: .. code-block:: bash patch <options> -i <patchfile> -d <originalfile> -p0 originalfile The full path to the file or directory to be patched patchfile A patch file to apply to ``originalfile`` options Options to pass to patch. CLI Example: .. code-block:: bash salt '*' file.patch /opt/file.txt /tmp/file.txt.patch ''' patchpath = salt.utils.path.which('patch') if not patchpath: raise CommandExecutionError( 'patch executable not found. Is the distribution\'s patch ' 'package installed?' ) cmd = [patchpath] cmd.extend(salt.utils.args.shlex_split(options)) if dry_run: if __grains__['kernel'] in ('FreeBSD', 'OpenBSD'): cmd.append('-C') else: cmd.append('--dry-run') # this argument prevents interactive prompts when the patch fails to apply. # the exit code will still be greater than 0 if that is the case. if '-N' not in cmd and '--forward' not in cmd: cmd.append('--forward') has_rejectfile_option = False for option in cmd: if option == '-r' or option.startswith('-r ') \ or option.startswith('--reject-file'): has_rejectfile_option = True break # by default, patch will write rejected patch files to <filename>.rej. # this option prevents that. if not has_rejectfile_option: cmd.append('--reject-file=-') cmd.extend(['-i', patchfile]) if os.path.isdir(originalfile): cmd.extend(['-d', originalfile]) has_strip_option = False for option in cmd: if option.startswith('-p') or option.startswith('--strip='): has_strip_option = True break if not has_strip_option: cmd.append('--strip=0') else: cmd.append(originalfile) return __salt__['cmd.run_all'](cmd, python_shell=False) def contains(path, text): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the file at ``path`` contains ``text`` CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False stripped_text = six.text_type(text).strip() try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if stripped_text in chunk: return True return False except (IOError, OSError): return False def contains_regex(path, regex, lchar=''): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the given regular expression matches on any line in the text of a given file. If the lchar argument (leading char) is specified, it will strip `lchar` from the left side of each line before trying to match CLI Example: .. code-block:: bash salt '*' file.contains_regex /etc/crontab ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.files.fopen(path, 'r') as target: for line in target: line = salt.utils.stringutils.to_unicode(line) if lchar: line = line.lstrip(lchar) if re.search(regex, line): return True return False except (IOError, OSError): return False def contains_glob(path, glob_expr): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the given glob matches a string in the named file CLI Example: .. code-block:: bash salt '*' file.contains_glob /etc/foobar '*cheese*' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if fnmatch.fnmatch(chunk, glob_expr): return True return False except (IOError, OSError): return False def append(path, *args, **kwargs): ''' .. versionadded:: 0.9.5 Append text to the end of a file path path to file `*args` strings to append to file CLI Example: .. code-block:: bash salt '*' file.append /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.append /etc/motd args='cheese=spam' salt '*' file.append /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) # Largely inspired by Fabric's contrib.files.append() if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] # Make sure we have a newline at the end of the file. Do this in binary # mode so SEEK_END with nonzero offset will work. with salt.utils.files.fopen(path, 'rb+') as ofile: linesep = salt.utils.stringutils.to_bytes(os.linesep) try: ofile.seek(-len(linesep), os.SEEK_END) except IOError as exc: if exc.errno in (errno.EINVAL, errno.ESPIPE): # Empty file, simply append lines at the beginning of the file pass else: raise else: if ofile.read(len(linesep)) != linesep: ofile.seek(0, os.SEEK_END) ofile.write(linesep) # Append lines in text mode with salt.utils.files.fopen(path, 'a') as ofile: for new_line in args: ofile.write( salt.utils.stringutils.to_str( '{0}{1}'.format(new_line, os.linesep) ) ) return 'Wrote {0} lines to "{1}"'.format(len(args), path) def prepend(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Prepend text to the beginning of a file path path to file `*args` strings to prepend to the file CLI Example: .. code-block:: bash salt '*' file.prepend /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.prepend /etc/motd args='cheese=spam' salt '*' file.prepend /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] try: with salt.utils.files.fopen(path) as fhr: contents = [salt.utils.stringutils.to_unicode(line) for line in fhr.readlines()] except IOError: contents = [] preface = [] for line in args: preface.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, 'w') as ofile: contents = preface + contents ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Prepended {0} lines to "{1}"'.format(len(args), path) def write(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Write text to a file, overwriting any existing contents. path path to file `*args` strings to write to the file CLI Example: .. code-block:: bash salt '*' file.write /etc/motd \\ "With all thine offerings thou shalt offer salt." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.write /etc/motd args='cheese=spam' salt '*' file.write /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] contents = [] for line in args: contents.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, "w") as ofile: ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Wrote {0} lines to "{1}"'.format(len(contents), path) def touch(name, atime=None, mtime=None): ''' .. versionadded:: 0.9.5 Just like the ``touch`` command, create a file if it doesn't exist or simply update the atime and mtime if it already does. atime: Access time in Unix epoch time. Set it to 0 to set atime of the file with Unix date of birth. If this parameter isn't set, atime will be set with current time. mtime: Last modification in Unix epoch time. Set it to 0 to set mtime of the file with Unix date of birth. If this parameter isn't set, mtime will be set with current time. CLI Example: .. code-block:: bash salt '*' file.touch /var/log/emptyfile ''' name = os.path.expanduser(name) if atime and atime.isdigit(): atime = int(atime) if mtime and mtime.isdigit(): mtime = int(mtime) try: if not os.path.exists(name): with salt.utils.files.fopen(name, 'a'): pass if atime is None and mtime is None: times = None elif mtime is None and atime is not None: times = (atime, time.time()) elif atime is None and mtime is not None: times = (time.time(), mtime) else: times = (atime, mtime) os.utime(name, times) except TypeError: raise SaltInvocationError('atime and mtime must be integers') except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return os.path.exists(name) def tail(path, lines): ''' .. versionadded:: Neon Read the last n lines from a file path path to file lines number of lines to read CLI Example: .. code-block:: bash salt '*' file.tail /path/to/file 10 ''' path = os.path.expanduser(path) lines_found = [] buffer_size = 4098 if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot tail a binary file: {0}'.format(path)) try: lines = int(lines) except ValueError: raise SaltInvocationError('file.tail: \'lines\' value must be an integer') try: with salt.utils.fopen(path) as tail_fh: blk_cnt = 1 size = os.stat(path).st_size if size > buffer_size: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size), os.linesep) for i in range(lines): while len(data) == 1 and ((blk_cnt * buffer_size) < size): blk_cnt += 1 line = data[0] try: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size) + line, os.linesep) except IOError: tail_fh.seek(0) data = string.split(tail_fh.read(size - (buffer_size * (blk_cnt - 1))) + line, os.linesep) line = data[-1] data.pop() lines_found.append(line) return lines_found[-lines:] except (OSError, IOError): raise CommandExecutionError('Could not tail \'{0}\''.format(path)) def seek_read(path, size, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and read it path path to file seek amount to read at once offset offset to start into the file CLI Example: .. code-block:: bash salt '*' file.seek_read /path/to/file 4096 0 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_RDONLY) try: os.lseek(seek_fh, int(offset), 0) data = os.read(seek_fh, int(size)) finally: os.close(seek_fh) return data def seek_write(path, data, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and write to it path path to file data data to write to file offset position in file to start writing CLI Example: .. code-block:: bash salt '*' file.seek_write /path/to/file 'some data' 4096 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_WRONLY) try: os.lseek(seek_fh, int(offset), 0) ret = os.write(seek_fh, data) os.fsync(seek_fh) finally: os.close(seek_fh) return ret def truncate(path, length): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and delete everything after that point path path to file length offset into file to truncate CLI Example: .. code-block:: bash salt '*' file.truncate /path/to/file 512 ''' path = os.path.expanduser(path) with salt.utils.files.fopen(path, 'rb+') as seek_fh: seek_fh.truncate(int(length)) def link(src, path): ''' .. versionadded:: 2014.1.0 Create a hard link to a file CLI Example: .. code-block:: bash salt '*' file.link /path/to/file /path/to/link ''' src = os.path.expanduser(src) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.link(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def is_link(path): ''' Check if the path is a symbolic link CLI Example: .. code-block:: bash salt '*' file.is_link /path/to/link ''' # This function exists because os.path.islink does not support Windows, # therefore a custom function will need to be called. This function # therefore helps API consistency by providing a single function to call for # both operating systems. return os.path.islink(os.path.expanduser(path)) def symlink(src, path): ''' Create a symbolic link (symlink, soft link) to a file CLI Example: .. code-block:: bash salt '*' file.symlink /path/to/file /path/to/link ''' path = os.path.expanduser(path) try: if os.path.normpath(os.readlink(path)) == os.path.normpath(src): log.debug('link already in correct state: %s -> %s', path, src) return True except OSError: pass if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: os.symlink(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def rename(src, dst): ''' Rename a file or directory CLI Example: .. code-block:: bash salt '*' file.rename /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.rename(src, dst) return True except OSError: raise CommandExecutionError( 'Could not rename \'{0}\' to \'{1}\''.format(src, dst) ) return False def copy(src, dst, recurse=False, remove_existing=False): ''' Copy a file or directory from source to dst In order to copy a directory, the recurse flag is required, and will by default overwrite files in the destination with the same path, and retain all other existing files. (similar to cp -r on unix) remove_existing will remove all files in the target directory, and then copy files from the source. .. note:: The copy function accepts paths that are local to the Salt minion. This function does not support salt://, http://, or the other additional file paths that are supported by :mod:`states.file.managed <salt.states.file.managed>` and :mod:`states.file.recurse <salt.states.file.recurse>`. CLI Example: .. code-block:: bash salt '*' file.copy /path/to/src /path/to/dst salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True remove_existing=True ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') if not os.path.exists(src): raise CommandExecutionError('No such file or directory \'{0}\''.format(src)) if not salt.utils.platform.is_windows(): pre_user = get_user(src) pre_group = get_group(src) pre_mode = salt.utils.files.normalize_mode(get_mode(src)) try: if (os.path.exists(dst) and os.path.isdir(dst)) or os.path.isdir(src): if not recurse: raise SaltInvocationError( "Cannot copy overwriting a directory without recurse flag set to true!") if remove_existing: if os.path.exists(dst): shutil.rmtree(dst) shutil.copytree(src, dst) else: salt.utils.files.recursive_copy(src, dst) else: shutil.copyfile(src, dst) except OSError: raise CommandExecutionError( 'Could not copy \'{0}\' to \'{1}\''.format(src, dst) ) if not salt.utils.platform.is_windows(): check_perms(dst, None, pre_user, pre_group, pre_mode) return True def lstat(path): ''' .. versionadded:: 2014.1.0 Returns the lstat attributes for the given file or dir. Does not support symbolic links. CLI Example: .. code-block:: bash salt '*' file.lstat /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to file must be absolute.') try: lst = os.lstat(path) return dict((key, getattr(lst, key)) for key in ('st_atime', 'st_ctime', 'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid')) except Exception: return {} def access(path, mode): ''' .. versionadded:: 2014.1.0 Test whether the Salt process has the specified access to the file. One of the following modes must be specified: .. code-block::text f: Test the existence of the path r: Test the readability of the path w: Test the writability of the path x: Test whether the path can be executed CLI Example: .. code-block:: bash salt '*' file.access /path/to/file f salt '*' file.access /path/to/file x ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') modes = {'f': os.F_OK, 'r': os.R_OK, 'w': os.W_OK, 'x': os.X_OK} if mode in modes: return os.access(path, modes[mode]) elif mode in six.itervalues(modes): return os.access(path, mode) else: raise SaltInvocationError('Invalid mode specified.') def read(path, binary=False): ''' .. versionadded:: 2017.7.0 Return the content of the file. CLI Example: .. code-block:: bash salt '*' file.read /path/to/file ''' access_mode = 'r' if binary is True: access_mode += 'b' with salt.utils.files.fopen(path, access_mode) as file_obj: return salt.utils.stringutils.to_unicode(file_obj.read()) def readlink(path, canonicalize=False): ''' .. versionadded:: 2014.1.0 Return the path that a symlink points to If canonicalize is set to True, then it return the final target CLI Example: .. code-block:: bash salt '*' file.readlink /path/to/link ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') if not os.path.islink(path): raise SaltInvocationError('A valid link was not specified.') if canonicalize: return os.path.realpath(path) else: return os.readlink(path) def readdir(path): ''' .. versionadded:: 2014.1.0 Return a list containing the contents of a directory CLI Example: .. code-block:: bash salt '*' file.readdir /path/to/dir/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Dir path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') dirents = ['.', '..'] dirents.extend(os.listdir(path)) return dirents def statvfs(path): ''' .. versionadded:: 2014.1.0 Perform a statvfs call against the filesystem that the file resides on CLI Example: .. code-block:: bash salt '*' file.statvfs /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: stv = os.statvfs(path) return dict((key, getattr(stv, key)) for key in ('f_bavail', 'f_bfree', 'f_blocks', 'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag', 'f_frsize', 'f_namemax')) except (OSError, IOError): raise CommandExecutionError('Could not statvfs \'{0}\''.format(path)) return False def stats(path, hash_type=None, follow_symlinks=True): ''' Return a dict containing the stats for a given file CLI Example: .. code-block:: bash salt '*' file.stats /etc/passwd ''' path = os.path.expanduser(path) ret = {} if not os.path.exists(path): try: # Broken symlinks will return False for os.path.exists(), but still # have a uid and gid pstat = os.lstat(path) except OSError: # Not a broken symlink, just a nonexistent path # NOTE: The file.directory state checks the content of the error # message in this exception. Any changes made to the message for this # exception will reflect the file.directory state as well, and will # likely require changes there. raise CommandExecutionError('Path not found: {0}'.format(path)) else: if follow_symlinks: pstat = os.stat(path) else: pstat = os.lstat(path) ret['inode'] = pstat.st_ino ret['uid'] = pstat.st_uid ret['gid'] = pstat.st_gid ret['group'] = gid_to_group(pstat.st_gid) ret['user'] = uid_to_user(pstat.st_uid) ret['atime'] = pstat.st_atime ret['mtime'] = pstat.st_mtime ret['ctime'] = pstat.st_ctime ret['size'] = pstat.st_size ret['mode'] = six.text_type(oct(stat.S_IMODE(pstat.st_mode))) if hash_type: ret['sum'] = get_hash(path, hash_type) ret['type'] = 'file' if stat.S_ISDIR(pstat.st_mode): ret['type'] = 'dir' if stat.S_ISCHR(pstat.st_mode): ret['type'] = 'char' if stat.S_ISBLK(pstat.st_mode): ret['type'] = 'block' if stat.S_ISREG(pstat.st_mode): ret['type'] = 'file' if stat.S_ISLNK(pstat.st_mode): ret['type'] = 'link' if stat.S_ISFIFO(pstat.st_mode): ret['type'] = 'pipe' if stat.S_ISSOCK(pstat.st_mode): ret['type'] = 'socket' ret['target'] = os.path.realpath(path) return ret def rmdir(path): ''' .. versionadded:: 2014.1.0 Remove the specified directory. Fails if a directory is not empty. CLI Example: .. code-block:: bash salt '*' file.rmdir /tmp/foo/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') try: os.rmdir(path) return True except OSError as exc: return exc.strerror def remove(path, **kwargs): ''' Remove the named file. If a directory is supplied, it will be recursively deleted. CLI Example: .. code-block:: bash salt '*' file.remove /tmp/foo ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute: {0}'.format(path)) try: if os.path.isfile(path) or os.path.islink(path): os.remove(path) return True elif os.path.isdir(path): shutil.rmtree(path) return True except (OSError, IOError) as exc: raise CommandExecutionError( 'Could not remove \'{0}\': {1}'.format(path, exc) ) return False def directory_exists(path): ''' Tests to see if path is a valid directory. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.directory_exists /etc ''' return os.path.isdir(os.path.expanduser(path)) def file_exists(path): ''' Tests to see if path is a valid file. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.file_exists /etc/passwd ''' return os.path.isfile(os.path.expanduser(path)) def path_exists_glob(path): ''' Tests to see if path after expansion is a valid path (file or directory). Expansion allows usage of ? * and character ranges []. Tilde expansion is not supported. Returns True/False. .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' file.path_exists_glob /etc/pam*/pass* ''' return True if glob.glob(os.path.expanduser(path)) else False def restorecon(path, recursive=False): ''' Reset the SELinux context on a given path CLI Example: .. code-block:: bash salt '*' file.restorecon /home/user/.ssh/authorized_keys ''' if recursive: cmd = ['restorecon', '-FR', path] else: cmd = ['restorecon', '-F', path] return not __salt__['cmd.retcode'](cmd, python_shell=False) def get_selinux_context(path): ''' Get an SELinux context from a given path CLI Example: .. code-block:: bash salt '*' file.get_selinux_context /etc/hosts ''' out = __salt__['cmd.run'](['ls', '-Z', path], python_shell=False) try: ret = re.search(r'\w+:\w+:\w+:\w+', out).group(0) except AttributeError: ret = ( 'No selinux context information is available for {0}'.format(path) ) return ret def set_selinux_context(path, user=None, role=None, type=None, # pylint: disable=W0622 range=None, # pylint: disable=W0622 persist=False): ''' .. versionchanged:: Neon Added persist option Set a specific SELinux label on a given path CLI Example: .. code-block:: bash salt '*' file.set_selinux_context path <user> <role> <type> <range> salt '*' file.set_selinux_context /etc/yum.repos.d/epel.repo system_u object_r system_conf_t s0 ''' if not any((user, role, type, range)): return False if persist: fcontext_result = __salt__['selinux.fcontext_add_policy'](path, sel_type=type, sel_user=user, sel_level=range) if fcontext_result.get('retcode', None) is not 0: # Problem setting fcontext policy raise CommandExecutionError( 'Problem setting fcontext: {0}'.format(fcontext_result) ) cmd = ['chcon'] if user: cmd.extend(['-u', user]) if role: cmd.extend(['-r', role]) if type: cmd.extend(['-t', type]) if range: cmd.extend(['-l', range]) cmd.append(path) ret = not __salt__['cmd.retcode'](cmd, python_shell=False) if ret: return get_selinux_context(path) else: return ret def source_list(source, source_hash, saltenv): ''' Check the source list and return the source to use CLI Example: .. code-block:: bash salt '*' file.source_list salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' base ''' contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv) if contextkey in __context__: return __context__[contextkey] # get the master file list if isinstance(source, list): mfiles = [(f, saltenv) for f in __salt__['cp.list_master'](saltenv)] mdirs = [(d, saltenv) for d in __salt__['cp.list_master_dirs'](saltenv)] for single in source: if isinstance(single, dict): single = next(iter(single)) path, senv = salt.utils.url.parse(single) if senv: mfiles += [(f, senv) for f in __salt__['cp.list_master'](senv)] mdirs += [(d, senv) for d in __salt__['cp.list_master_dirs'](senv)] ret = None for single in source: if isinstance(single, dict): # check the proto, if it is http or ftp then download the file # to check, if it is salt then check the master list # if it is a local file, check if the file exists if len(single) != 1: continue single_src = next(iter(single)) single_hash = single[single_src] if single[single_src] else source_hash urlparsed_single_src = _urlparse(single_src) # Fix this for Windows if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_single_src.scheme.lower() in string.ascii_lowercase: urlparsed_single_src = _urlparse('file://' + single_src) proto = urlparsed_single_src.scheme if proto == 'salt': path, senv = salt.utils.url.parse(single_src) if not senv: senv = saltenv if (path, saltenv) in mfiles or (path, saltenv) in mdirs: ret = (single_src, single_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single_src, single_hash) break elif proto == 'file' and ( os.path.exists(urlparsed_single_src.netloc) or os.path.exists(urlparsed_single_src.path) or os.path.exists(os.path.join( urlparsed_single_src.netloc, urlparsed_single_src.path))): ret = (single_src, single_hash) break elif single_src.startswith(os.sep) and os.path.exists(single_src): ret = (single_src, single_hash) break elif isinstance(single, six.string_types): path, senv = salt.utils.url.parse(single) if not senv: senv = saltenv if (path, senv) in mfiles or (path, senv) in mdirs: ret = (single, source_hash) break urlparsed_src = _urlparse(single) if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_src.scheme.lower() in string.ascii_lowercase: urlparsed_src = _urlparse('file://' + single) proto = urlparsed_src.scheme if proto == 'file' and ( os.path.exists(urlparsed_src.netloc) or os.path.exists(urlparsed_src.path) or os.path.exists(os.path.join( urlparsed_src.netloc, urlparsed_src.path))): ret = (single, source_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single, source_hash) break elif single.startswith(os.sep) and os.path.exists(single): ret = (single, source_hash) break if ret is None: # None of the list items matched raise CommandExecutionError( 'none of the specified sources were found' ) else: ret = (source, source_hash) __context__[contextkey] = ret return ret def apply_template_on_contents( contents, template, context, defaults, saltenv): ''' Return the contents after applying the templating engine contents template string template template format context Overrides default context variables passed to the template. defaults Default context passed to the template. CLI Example: .. code-block:: bash salt '*' file.apply_template_on_contents \\ contents='This is a {{ template }} string.' \\ template=jinja \\ "context={}" "defaults={'template': 'cool'}" \\ saltenv=base ''' if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) # Apply templating contents = salt.utils.templates.TEMPLATE_REGISTRY[template]( contents, from_str=True, to_str=True, context=context_dict, saltenv=saltenv, grains=__opts__['grains'], pillar=__pillar__, salt=__salt__, opts=__opts__)['data'] if six.PY2: contents = contents.encode('utf-8') elif six.PY3 and isinstance(contents, bytes): # bytes -> str contents = contents.decode('utf-8') else: ret = {} ret['result'] = False ret['comment'] = ('Specified template format {0} is not supported' ).format(template) return ret return contents def get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify=False, **kwargs): ''' Return the managed file data for file.managed name location where the file lives on the server template template format source managed source file source_hash hash of the source file source_hash_name When ``source_hash`` refers to a remote file, this specifies the filename to look for in that file. .. versionadded:: 2016.3.5 user Owner of file group Group owner of file mode Permissions of file attrs Attributes of file .. versionadded:: 2018.3.0 context Variables to add to the template context defaults Default values of for context_dict skip_verify If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' file.get_managed /etc/httpd/conf.d/httpd.conf jinja salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' None root root '755' base None None ''' # Copy the file to the minion and templatize it sfn = '' source_sum = {} def _get_local_file_source_sum(path): ''' DRY helper for getting the source_sum value from a locally cached path. ''' return {'hsum': get_hash(path, form='sha256'), 'hash_type': 'sha256'} # If we have a source defined, let's figure out what the hash is if source: urlparsed_source = _urlparse(source) if urlparsed_source.scheme in salt.utils.files.VALID_PROTOS: parsed_scheme = urlparsed_source.scheme else: parsed_scheme = '' parsed_path = os.path.join( urlparsed_source.netloc, urlparsed_source.path).rstrip(os.sep) unix_local_source = parsed_scheme in ('file', '') if parsed_scheme == '': parsed_path = sfn = source if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg elif parsed_scheme == 'file': sfn = parsed_path if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg if parsed_scheme and parsed_scheme.lower() in string.ascii_lowercase: parsed_path = ':'.join([parsed_scheme, parsed_path]) parsed_scheme = 'file' if parsed_scheme == 'salt': source_sum = __salt__['cp.hash_file'](source, saltenv) if not source_sum: return '', {}, 'Source file {0} not found in saltenv \'{1}\''.format(source, saltenv) elif not source_hash and unix_local_source: source_sum = _get_local_file_source_sum(parsed_path) elif not source_hash and source.startswith(os.sep): # This should happen on Windows source_sum = _get_local_file_source_sum(source) else: if not skip_verify: if source_hash: try: source_sum = get_source_sum(name, source, source_hash, source_hash_name, saltenv) except CommandExecutionError as exc: return '', {}, exc.strerror else: msg = ( 'Unable to verify upstream hash of source file {0}, ' 'please set source_hash or set skip_verify to True' .format(salt.utils.url.redact_http_basic_auth(source)) ) return '', {}, msg if source and (template or parsed_scheme in salt.utils.files.REMOTE_PROTOS): # Check if we have the template or remote file cached cache_refetch = False cached_dest = __salt__['cp.is_cached'](source, saltenv) if cached_dest and (source_hash or skip_verify): htype = source_sum.get('hash_type', 'sha256') cached_sum = get_hash(cached_dest, form=htype) if skip_verify: # prev: if skip_verify or cached_sum == source_sum['hsum']: # but `cached_sum == source_sum['hsum']` is elliptical as prev if sfn = cached_dest source_sum = {'hsum': cached_sum, 'hash_type': htype} elif cached_sum != source_sum.get('hsum', __opts__['hash_type']): cache_refetch = True else: sfn = cached_dest # If we didn't have the template or remote file, or the file has been # updated and the cache has to be refreshed, download the file. if not sfn or cache_refetch: try: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum.get('hsum')) except Exception as exc: # A 404 or other error code may raise an exception, catch it # and return a comment that will fail the calling state. _source = salt.utils.url.redact_http_basic_auth(source) return '', {}, 'Failed to cache {0}: {1}'.format(_source, exc) # If cache failed, sfn will be False, so do a truth check on sfn first # as invoking os.path.exists() on a bool raises a TypeError. if not sfn or not os.path.exists(sfn): _source = salt.utils.url.redact_http_basic_auth(source) return sfn, {}, 'Source file \'{0}\' not found'.format(_source) if sfn == name: raise SaltInvocationError( 'Source file cannot be the same as destination' ) if template: if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, name=name, source=source, user=user, group=group, mode=mode, attrs=attrs, saltenv=saltenv, context=context_dict, salt=__salt__, pillar=__pillar__, grains=__opts__['grains'], opts=__opts__, **kwargs) else: return sfn, {}, ('Specified template format {0} is not supported' ).format(template) if data['result']: sfn = data['data'] hsum = get_hash(sfn, form='sha256') source_sum = {'hash_type': 'sha256', 'hsum': hsum} else: __clean_tmp(sfn) return sfn, {}, data['data'] return sfn, source_sum, '' def extract_hash(hash_fn, hash_type='sha256', file_name='', source='', source_hash_name=None): ''' .. versionchanged:: 2016.3.5 Prior to this version, only the ``file_name`` argument was considered for filename matches in the hash file. This would be problematic for cases in which the user was relying on a remote checksum file that they do not control, and they wished to use a different name for that file on the minion from the filename on the remote server (and in the checksum file). For example, managing ``/tmp/myfile.tar.gz`` when the remote file was at ``https://mydomain.tld/different_name.tar.gz``. The :py:func:`file.managed <salt.states.file.managed>` state now also passes this function the source URI as well as the ``source_hash_name`` (if specified). In cases where ``source_hash_name`` is specified, it takes precedence over both the ``file_name`` and ``source``. When it is not specified, ``file_name`` takes precedence over ``source``. This allows for better capability for matching hashes. .. versionchanged:: 2016.11.0 File name and source URI matches are no longer disregarded when ``source_hash_name`` is specified. They will be used as fallback matches if there is no match to the ``source_hash_name`` value. This routine is called from the :mod:`file.managed <salt.states.file.managed>` state to pull a hash from a remote file. Regular expressions are used line by line on the ``source_hash`` file, to find a potential candidate of the indicated hash type. This avoids many problems of arbitrary file layout rules. It specifically permits pulling hash codes from debian ``*.dsc`` files. If no exact match of a hash and filename are found, then the first hash found (if any) will be returned. If no hashes at all are found, then ``None`` will be returned. For example: .. code-block:: yaml openerp_7.0-latest-1.tar.gz: file.managed: - name: /tmp/openerp_7.0-20121227-075624-1_all.deb - source: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.tar.gz - source_hash: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.dsc CLI Example: .. code-block:: bash salt '*' file.extract_hash /path/to/hash/file sha512 /etc/foo ''' hash_len = HASHES.get(hash_type) if hash_len is None: if hash_type: log.warning( 'file.extract_hash: Unsupported hash_type \'%s\', falling ' 'back to matching any supported hash_type', hash_type ) hash_type = '' hash_len_expr = '{0},{1}'.format(min(HASHES_REVMAP), max(HASHES_REVMAP)) else: hash_len_expr = six.text_type(hash_len) filename_separators = string.whitespace + r'\/' if source_hash_name: if not isinstance(source_hash_name, six.string_types): source_hash_name = six.text_type(source_hash_name) source_hash_name_idx = (len(source_hash_name) + 1) * -1 log.debug( 'file.extract_hash: Extracting %s hash for file matching ' 'source_hash_name \'%s\'', 'any supported' if not hash_type else hash_type, source_hash_name ) if file_name: if not isinstance(file_name, six.string_types): file_name = six.text_type(file_name) file_name_basename = os.path.basename(file_name) file_name_idx = (len(file_name_basename) + 1) * -1 if source: if not isinstance(source, six.string_types): source = six.text_type(source) urlparsed_source = _urlparse(source) source_basename = os.path.basename( urlparsed_source.path or urlparsed_source.netloc ) source_idx = (len(source_basename) + 1) * -1 basename_searches = [x for x in (file_name, source) if x] if basename_searches: log.debug( 'file.extract_hash: %s %s hash for file matching%s: %s', 'If no source_hash_name match found, will extract' if source_hash_name else 'Extracting', 'any supported' if not hash_type else hash_type, '' if len(basename_searches) == 1 else ' either of the following', ', '.join(basename_searches) ) partial = None found = {} with salt.utils.files.fopen(hash_fn, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line.strip()) hash_re = r'(?i)(?<![a-z0-9])([a-f0-9]{' + hash_len_expr + '})(?![a-z0-9])' hash_match = re.search(hash_re, line) matched = None if hash_match: matched_hsum = hash_match.group(1) if matched_hsum is not None: matched_type = HASHES_REVMAP.get(len(matched_hsum)) if matched_type is None: # There was a match, but it's not of the correct length # to match one of the supported hash types. matched = None else: matched = {'hsum': matched_hsum, 'hash_type': matched_type} if matched is None: log.debug( 'file.extract_hash: In line \'%s\', no %shash found', line, '' if not hash_type else hash_type + ' ' ) continue if partial is None: partial = matched def _add_to_matches(found, line, match_type, value, matched): log.debug( 'file.extract_hash: Line \'%s\' matches %s \'%s\'', line, match_type, value ) found.setdefault(match_type, []).append(matched) hash_matched = False if source_hash_name: if line.endswith(source_hash_name): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[source_hash_name_idx] in string.whitespace: _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source_hash_name) + r'\s+', line): _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True if file_name: if line.endswith(file_name_basename): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[file_name_idx] in filename_separators: _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(file_name) + r'\s+', line): _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True if source: if line.endswith(source_basename): # Same as above, we can't just do an rsplit here. try: if line[source_idx] in filename_separators: _add_to_matches(found, line, 'source', source, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source) + r'\s+', line): _add_to_matches(found, line, 'source', source, matched) hash_matched = True if not hash_matched: log.debug( 'file.extract_hash: Line \'%s\' contains %s hash ' '\'%s\', but line did not meet the search criteria', line, matched['hash_type'], matched['hsum'] ) for found_type, found_str in (('source_hash_name', source_hash_name), ('file_name', file_name), ('source', source)): if found_type in found: if len(found[found_type]) > 1: log.debug( 'file.extract_hash: Multiple %s matches for %s: %s', found_type, found_str, ', '.join( ['{0} ({1})'.format(x['hsum'], x['hash_type']) for x in found[found_type]] ) ) ret = found[found_type][0] log.debug( 'file.extract_hash: Returning %s hash \'%s\' as a match of %s', ret['hash_type'], ret['hsum'], found_str ) return ret if partial: log.debug( 'file.extract_hash: Returning the partially identified %s hash ' '\'%s\'', partial['hash_type'], partial['hsum'] ) return partial log.debug('file.extract_hash: No matches, returning None') return None def check_perms(name, ret, user, group, mode, attrs=None, follow_symlinks=False, seuser=None, serole=None, setype=None, serange=None): ''' .. versionchanged:: Neon Added selinux options Check the permissions on files, modify attributes and chown if needed. File attributes are only verified if lsattr(1) is installed. CLI Example: .. code-block:: bash salt '*' file.check_perms /etc/sudoers '{}' root root 400 ai .. versionchanged:: 2014.1.3 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': [], 'result': True} orig_comment = '' else: orig_comment = ret['comment'] ret['comment'] = [] # Check permissions perms = {} cur = stats(name, follow_symlinks=follow_symlinks) perms['luser'] = cur['user'] perms['lgroup'] = cur['group'] perms['lmode'] = salt.utils.files.normalize_mode(cur['mode']) is_dir = os.path.isdir(name) is_link = os.path.islink(name) if attrs is not None \ and not salt.utils.platform.is_windows() \ and not is_dir and not is_link: try: lattrs = lsattr(name) except SaltInvocationError: lattrs = None if lattrs is not None: # List attributes on file perms['lattrs'] = ''.join(lattrs.get(name, '')) # Remove attributes on file so changes can be enforced. if perms['lattrs']: chattr(name, operator='remove', attributes=perms['lattrs']) # user/group changes if needed, then check if it worked if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid(perms['luser']) ) or ( not salt.utils.platform.is_windows() and user != perms['luser'] ): perms['cuser'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid(perms['lgroup']) ) or ( not salt.utils.platform.is_windows() and group != perms['lgroup'] ): perms['cgroup'] = group if 'cuser' in perms or 'cgroup' in perms: if not __opts__['test']: if os.path.islink(name) and not follow_symlinks: chown_func = lchown else: chown_func = chown if user is None: user = perms['luser'] if group is None: group = perms['lgroup'] try: chown_func(name, user, group) # Python os.chown() does reset the suid and sgid, # that's why setting the right mode again is needed here. set_mode(name, mode) except OSError: ret['result'] = False if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid( get_user(name, follow_symlinks=follow_symlinks)) and user != '' ) or ( not salt.utils.platform.is_windows() and user != get_user(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['user'] = user else: ret['result'] = False ret['comment'].append('Failed to change user to {0}' .format(user)) elif 'cuser' in perms and user != '': ret['changes']['user'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid( get_group(name, follow_symlinks=follow_symlinks)) and user != '') or ( not salt.utils.platform.is_windows() and group != get_group(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['group'] = group else: ret['result'] = False ret['comment'].append('Failed to change group to {0}' .format(group)) elif 'cgroup' in perms and user != '': ret['changes']['group'] = group if not salt.utils.platform.is_windows() and not is_dir: # Replace attributes on file if it had been removed if perms.get('lattrs', ''): chattr(name, operator='add', attributes=perms['lattrs']) # Mode changes if needed if mode is not None: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: mode = salt.utils.files.normalize_mode(mode) if mode != perms['lmode']: if __opts__['test'] is True: ret['changes']['mode'] = mode else: set_mode(name, mode) if mode != salt.utils.files.normalize_mode(get_mode(name)): ret['result'] = False ret['comment'].append( 'Failed to change mode to {0}'.format(mode) ) else: ret['changes']['mode'] = mode # Modify attributes of file if needed if attrs is not None and not is_dir: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if diff_attrs[0] is not None or diff_attrs[1] is not None: if __opts__['test'] is True: ret['changes']['attrs'] = attrs else: if diff_attrs[0] is not None: chattr(name, operator="add", attributes=diff_attrs[0]) if diff_attrs[1] is not None: chattr(name, operator="remove", attributes=diff_attrs[1]) cmp_attrs = _cmp_attrs(name, attrs) if cmp_attrs[0] is not None or cmp_attrs[1] is not None: ret['result'] = False ret['comment'].append( 'Failed to change attributes to {0}'.format(attrs) ) else: ret['changes']['attrs'] = attrs # Set selinux attributes if needed if salt.utils.platform.is_linux() and (seuser or serole or setype or serange): selinux_error = False try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError: log.error('Unable to get current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to get selinux attributes' ) selinux_error = True if not selinux_error: requested_seuser = None requested_serole = None requested_setype = None requested_serange = None # Only set new selinux variables if updates are needed if seuser and seuser != current_seuser: requested_seuser = seuser if serole and serole != current_serole: requested_serole = serole if setype and setype != current_setype: requested_setype = setype if serange and serange != current_serange: requested_serange = serange if requested_seuser or requested_serole or requested_setype or requested_serange: # selinux updates needed, prep changes output selinux_change_new = '' selinux_change_orig = '' if requested_seuser: selinux_change_new += "User: {0} ".format(requested_seuser) selinux_change_orig += "User: {0} ".format(current_seuser) if requested_serole: selinux_change_new += "Role: {0} ".format(requested_serole) selinux_change_orig += "Role: {0} ".format(current_serole) if requested_setype: selinux_change_new += "Type: {0} ".format(requested_setype) selinux_change_orig += "Type: {0} ".format(current_setype) if requested_serange: selinux_change_new += "Range: {0} ".format(requested_serange) selinux_change_orig += "Range: {0} ".format(current_serange) if __opts__['test']: ret['comment'] = 'File {0} selinux context to be updated'.format(name) ret['result'] = None ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} else: try: # set_selinux_context requires type to be set on any other change if (requested_seuser or requested_serole or requested_serange) and not requested_setype: requested_setype = current_setype result = set_selinux_context(name, user=requested_seuser, role=requested_serole, type=requested_setype, range=requested_serange, persist=True) log.debug('selinux set result: %s', result) current_seuser, current_serole, current_setype, current_serange = result.split(':') except ValueError: log.error('Unable to set current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to set selinux attributes' ) selinux_error = True if not selinux_error: ret['comment'].append('The file {0} is set to be changed'.format(name)) if requested_seuser: if current_seuser != requested_seuser: ret['comment'].append("Unable to update seuser context") ret['result'] = False if requested_serole: if current_serole != requested_serole: ret['comment'].append("Unable to update serole context") ret['result'] = False if requested_setype: if current_setype != requested_setype: ret['comment'].append("Unable to update setype context") ret['result'] = False if requested_serange: if current_serange != requested_serange: ret['comment'].append("Unable to update serange context") ret['result'] = False ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} # Only combine the comment list into a string # after all comments are added above if isinstance(orig_comment, six.string_types): if orig_comment: ret['comment'].insert(0, orig_comment) ret['comment'] = '; '.join(ret['comment']) # Set result to None at the very end of the function, # after all changes have been recorded above if __opts__['test'] is True and ret['changes']: ret['result'] = None return ret, perms def check_managed( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Check to see what changes need to be made for a file CLI Example: .. code-block:: bash salt '*' file.check_managed /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) if comments: __clean_tmp(sfn) return False, comments changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) # Ignore permission for files written temporary directories # Files in any path will still be set correctly using get_managed() if name.startswith(tempfile.gettempdir()): for key in ['user', 'group', 'mode']: changes.pop(key, None) __clean_tmp(sfn) if changes: log.info(changes) comments = ['The following values are set to be changed:\n'] comments.extend('{0}: {1}\n'.format(key, val) for key, val in six.iteritems(changes)) return None, ''.join(comments) return True, 'The file {0} is in the correct state'.format(name) def check_managed_changes( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, keep_mode=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Return a dictionary of what changes need to be made for a file .. versionchanged:: Neon selinux attributes added CLI Example: .. code-block:: bash salt '*' file.check_managed_changes /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if comments: __clean_tmp(sfn) raise CommandExecutionError(comments) if sfn and source and keep_mode: if _urlparse(source).scheme in ('salt', 'file') \ or source.startswith('/'): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) __clean_tmp(sfn) return changes def check_file_meta( name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents=None, seuser=None, serole=None, setype=None, serange=None): ''' Check for the changes in the file metadata. CLI Example: .. code-block:: bash salt '*' file.check_file_meta /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' base .. note:: Supported hash types include sha512, sha384, sha256, sha224, sha1, and md5. name Path to file destination sfn Template-processed source file contents source URL to file source source_sum File checksum information as a dictionary .. code-block:: yaml {hash_type: md5, hsum: <md5sum>} user Destination file user owner group Destination file group owner mode Destination file permissions mode attrs Destination file attributes .. versionadded:: 2018.3.0 saltenv Salt environment used to resolve source files contents File contents seuser selinux user attribute .. versionadded:: Neon serole selinux role attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon ''' changes = {} if not source_sum: source_sum = dict() try: lstats = stats(name, hash_type=source_sum.get('hash_type', None), follow_symlinks=False) except CommandExecutionError: lstats = {} if not lstats: changes['newfile'] = name return changes if 'hsum' in source_sum: if source_sum['hsum'] != lstats['sum']: if not sfn and source: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum['hsum']) if sfn: try: changes['diff'] = get_diff( name, sfn, template=True, show_filenames=False) except CommandExecutionError as exc: changes['diff'] = exc.strerror else: changes['sum'] = 'Checksum differs' if contents is not None: # Write a tempfile with the static contents tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'w') as tmp_: tmp_.write(salt.utils.stringutils.to_str(contents)) # Compare the static contents with the named file try: differences = get_diff(name, tmp, show_filenames=False) except CommandExecutionError as exc: log.error('Failed to diff files: %s', exc) differences = exc.strerror __clean_tmp(tmp) if differences: if __salt__['config.option']('obfuscate_templates'): changes['diff'] = '<Obfuscated Template>' else: changes['diff'] = differences if not salt.utils.platform.is_windows(): # Check owner if (user is not None and user != lstats['user'] and user != lstats['uid']): changes['user'] = user # Check group if (group is not None and group != lstats['group'] and group != lstats['gid']): changes['group'] = group # Normalize the file mode smode = salt.utils.files.normalize_mode(lstats['mode']) mode = salt.utils.files.normalize_mode(mode) if mode is not None and mode != smode: changes['mode'] = mode if attrs: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if attrs is not None \ and (diff_attrs[0] is not None or diff_attrs[1] is not None): changes['attrs'] = attrs # Check selinux if seuser or serole or setype or serange: try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError as exc: log.error('Unable to get current selinux attributes') changes['selinux'] = exc.strerror if seuser and seuser != current_seuser: changes['selinux'] = {"user": seuser} if serole and serole != current_serole: changes['selinux'] = {"role": serole} if setype and setype != current_setype: changes['selinux'] = {"type": setype} if serange and serange != current_serange: changes['selinux'] = {"range": serange} return changes def get_diff(file1, file2, saltenv='base', show_filenames=True, show_changes=True, template=False, source_hash_file1=None, source_hash_file2=None): ''' Return unified diff of two files file1 The first file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, thuis had to be a file local to the minion. file2 The second file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, this had to be a file on the salt fileserver (i.e. ``salt://somefile.txt``) show_filenames : True Set to ``False`` to hide the filenames in the top two lines of the diff. show_changes : True If set to ``False``, and there are differences, then instead of a diff a simple message stating that show_changes is set to ``False`` will be returned. template : False Set to ``True`` if two templates are being compared. This is not useful except for within states, with the ``obfuscate_templates`` option set to ``True``. .. versionadded:: 2018.3.0 source_hash_file1 If ``file1`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 source_hash_file2 If ``file2`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 CLI Examples: .. code-block:: bash salt '*' file.get_diff /home/fred/.vimrc salt://users/fred/.vimrc salt '*' file.get_diff /tmp/foo.txt /tmp/bar.txt ''' files = (file1, file2) source_hashes = (source_hash_file1, source_hash_file2) paths = [] errors = [] for filename, source_hash in zip(files, source_hashes): try: # Local file paths will just return the same path back when passed # to cp.cache_file. cached_path = __salt__['cp.cache_file'](filename, saltenv, source_hash=source_hash) if cached_path is False: errors.append( 'File {0} not found'.format( salt.utils.stringutils.to_unicode(filename) ) ) continue paths.append(cached_path) except MinionError as exc: errors.append(salt.utils.stringutils.to_unicode(exc.__str__())) continue if errors: raise CommandExecutionError( 'Failed to cache one or more files', info=errors ) args = [] for filename in paths: try: with salt.utils.files.fopen(filename, 'rb') as fp_: args.append(fp_.readlines()) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read {0}: {1}'.format( salt.utils.stringutils.to_unicode(filename), exc.strerror ) ) if args[0] != args[1]: if template and __salt__['config.option']('obfuscate_templates'): ret = '<Obfuscated Template>' elif not show_changes: ret = '<show_changes=False>' else: bdiff = _binary_replace(*paths) # pylint: disable=no-value-for-parameter if bdiff: ret = bdiff else: if show_filenames: args.extend(paths) ret = __utils__['stringutils.get_diff'](*args) return ret return '' def manage_file(name, sfn, ret, source, source_sum, user, group, mode, attrs, saltenv, backup, makedirs=False, template=None, # pylint: disable=W0613 show_changes=True, contents=None, dir_mode=None, follow_symlinks=True, skip_verify=False, keep_mode=False, encoding=None, encoding_errors='strict', seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Checks the destination against what was retrieved with get_managed and makes the appropriate modifications (if necessary). name location to place the file sfn location of cached file on the minion This is the path to the file stored on the minion. This file is placed on the minion using cp.cache_file. If the hash sum of that file matches the source_sum, we do not transfer the file to the minion again. This file is then grabbed and if it has template set, it renders the file to be placed into the correct place on the system using salt.files.utils.copyfile() ret The initial state return data structure. Pass in ``None`` to use the default structure. source file reference on the master source_sum sum hash for source user user owner group group owner backup backup_mode attrs attributes to be set on file: '' means remove all of them .. versionadded:: 2018.3.0 makedirs make directories if they do not exist template format of templating show_changes Include diff in state return contents: contents to be placed in the file dir_mode mode for directories created with makedirs skip_verify : False If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 keep_mode : False If ``True``, and the ``source`` is a file from the Salt fileserver (or a local file on the minion), the mode of the destination file will be set to the mode of the source file. .. note:: keep_mode does not work with salt-ssh. As a consequence of how the files are transferred to the minion, and the inability to connect back to the master with salt-ssh, salt is unable to stat the file as it exists on the fileserver and thus cannot mirror the mode on the salt-ssh minion encoding If specified, then the specified encoding will be used. Otherwise, the file will be encoded using the system locale (usually UTF-8). See https://docs.python.org/3/library/codecs.html#standard-encodings for the list of available encodings. .. versionadded:: 2017.7.0 encoding_errors : 'strict' Default is ```'strict'```. See https://docs.python.org/2/library/codecs.html#codec-base-classes for the error handling schemes. .. versionadded:: 2017.7.0 seuser selinux user attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon CLI Example: .. code-block:: bash salt '*' file.manage_file /etc/httpd/conf.d/httpd.conf '' '{}' salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' '' base '' .. versionchanged:: 2014.7.0 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if source: if not sfn: # File is not present, cache it sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) htype = source_sum.get('hash_type', __opts__['hash_type']) # Recalculate source sum now that file has been cached source_sum = { 'hash_type': htype, 'hsum': get_hash(sfn, form=htype) } if keep_mode: if _urlparse(source).scheme in ('salt', 'file', ''): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) # Check changes if the target file exists if os.path.isfile(name) or os.path.islink(name): if os.path.islink(name) and follow_symlinks: real_name = os.path.realpath(name) else: real_name = name # Only test the checksums on files with managed contents if source and not (not follow_symlinks and os.path.islink(real_name)): name_sum = get_hash(real_name, source_sum.get('hash_type', __opts__['hash_type'])) else: name_sum = None # Check if file needs to be replaced if source and (name_sum is None or source_sum.get('hsum', __opts__['hash_type']) != name_sum): if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server or local # source, and we are not skipping checksum verification, then # verify that it matches the specified checksum. if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3}). If the \'source_hash\' value ' 'refers to a remote file with multiple possible ' 'matches, then it may be necessary to set ' '\'source_hash_name\'.'.format( source_sum['hash_type'], source, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # Print a diff equivalent to diff -u old new if __salt__['config.option']('obfuscate_templates'): ret['changes']['diff'] = '<Obfuscated Template>' elif not show_changes: ret['changes']['diff'] = '<show_changes=False>' else: try: ret['changes']['diff'] = get_diff( real_name, sfn, show_filenames=False) except CommandExecutionError as exc: ret['changes']['diff'] = exc.strerror # Pre requisites are met, and the file needs to be replaced, do it try: salt.utils.files.copyfile(sfn, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) try: differences = get_diff( real_name, tmp, show_filenames=False, show_changes=show_changes, template=True) except CommandExecutionError as exc: ret.setdefault('warnings', []).append( 'Failed to detect changes to file: {0}'.format(exc.strerror) ) differences = '' if differences: ret['changes']['diff'] = differences # Pre requisites are met, the file needs to be replaced, do it try: salt.utils.files.copyfile(tmp, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(tmp) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) __clean_tmp(tmp) # Check for changing symlink to regular file here if os.path.islink(name) and not follow_symlinks: if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret try: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) ret['changes']['diff'] = \ 'Replace symbolic link with regular file' if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, follow_symlinks, seuser=seuser, serole=serole, setype=setype, serange=serange) if ret['changes']: ret['comment'] = 'File {0} updated'.format( salt.utils.data.decode(name) ) elif not ret['changes'] and ret['result']: ret['comment'] = 'File {0} is in the correct state'.format( salt.utils.data.decode(name) ) if sfn: __clean_tmp(sfn) return ret else: # target file does not exist contain_dir = os.path.dirname(name) def _set_mode_and_make_dirs(name, dir_mode, mode, user, group): # check for existence of windows drive letter if salt.utils.platform.is_windows(): drive, _ = os.path.splitdrive(name) if drive and not os.path.exists(drive): __clean_tmp(sfn) return _error(ret, '{0} drive not present'.format(drive)) if dir_mode is None and mode is not None: # Add execute bit to each nonzero digit in the mode, if # dir_mode was not specified. Otherwise, any # directories created with makedirs_() below can't be # listed via a shell. mode_list = [x for x in six.text_type(mode)][-3:] for idx in range(len(mode_list)): if mode_list[idx] != '0': mode_list[idx] = six.text_type(int(mode_list[idx]) | 1) dir_mode = ''.join(mode_list) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 makedirs_( path=name, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: makedirs_(name, user=user, group=group, mode=dir_mode) if source: # Apply the new file if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # It is a new file, set the diff accordingly ret['changes']['diff'] = 'New file' if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') else: # source != True if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') # Create the file, user rw-only if mode will be set to prevent # a small security race problem before the permissions are set with salt.utils.files.set_umask(0o077 if mode else None): # Create a new file when test is False and source is None if contents is None: if not __opts__['test']: if touch(name): ret['changes']['new'] = 'file {0} created'.format(name) ret['comment'] = 'Empty file' else: return _error( ret, 'Empty file {0} not created'.format(name) ) else: if not __opts__['test']: if touch(name): ret['changes']['diff'] = 'New file' else: return _error( ret, 'File {0} not created'.format(name) ) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) # Copy into place salt.utils.files.copyfile(tmp, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(tmp) # Now copy the file contents if there is a source file elif sfn: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(sfn) # This is a new file, if no mode specified, use the umask to figure # out what mode to use for the new file. if mode is None and not salt.utils.platform.is_windows(): # Get current umask mask = salt.utils.files.get_umask() # Calculate the mode value that results from the umask mode = oct((0o777 ^ mask) & 0o666) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, seuser=seuser, serole=serole, setype=setype, serange=serange) if not ret['comment']: ret['comment'] = 'File ' + name + ' updated' if __opts__['test']: ret['comment'] = 'File ' + name + ' not updated' elif not ret['changes'] and ret['result']: ret['comment'] = 'File ' + name + ' is in the correct state' if sfn: __clean_tmp(sfn) return ret def mkdir(dir_path, user=None, group=None, mode=None): ''' Ensure that a directory is available. CLI Example: .. code-block:: bash salt '*' file.mkdir /opt/jetty/context ''' dir_path = os.path.expanduser(dir_path) directory = os.path.normpath(dir_path) if not os.path.isdir(directory): # If a caller such as managed() is invoked with makedirs=True, make # sure that any created dirs are created with the same user and group # to follow the principal of least surprise method. makedirs_perms(directory, user, group, mode) return True def makedirs_(path, user=None, group=None, mode=None): ''' Ensure that the directory containing this path is available. .. note:: The path must end with a trailing slash otherwise the directory/directories will be created up to the parent directory. For example if path is ``/opt/code``, then it would be treated as ``/opt/`` but if the path ends with a trailing slash like ``/opt/code/``, then it would be treated as ``/opt/code/``. CLI Example: .. code-block:: bash salt '*' file.makedirs /opt/code/ ''' path = os.path.expanduser(path) if mode: mode = salt.utils.files.normalize_mode(mode) # walk up the directory structure until we find the first existing # directory dirname = os.path.normpath(os.path.dirname(path)) if os.path.isdir(dirname): # There's nothing for us to do msg = 'Directory \'{0}\' already exists'.format(dirname) log.debug(msg) return msg if os.path.exists(dirname): msg = 'The path \'{0}\' already exists and is not a directory'.format( dirname ) log.debug(msg) return msg directories_to_create = [] while True: if os.path.isdir(dirname): break directories_to_create.append(dirname) current_dirname = dirname dirname = os.path.dirname(dirname) if current_dirname == dirname: raise SaltInvocationError( 'Recursive creation for path \'{0}\' would result in an ' 'infinite loop. Please use an absolute path.'.format(dirname) ) # create parent directories from the topmost to the most deeply nested one directories_to_create.reverse() for directory_to_create in directories_to_create: # all directories have the user, group and mode set!! log.debug('Creating directory: %s', directory_to_create) mkdir(directory_to_create, user=user, group=group, mode=mode) def makedirs_perms(name, user=None, group=None, mode='0755'): ''' Taken and modified from os.makedirs to set user, group and mode for each directory created. CLI Example: .. code-block:: bash salt '*' file.makedirs_perms /opt/code ''' name = os.path.expanduser(name) path = os.path head, tail = path.split(name) if not tail: head, tail = path.split(head) if head and tail and not path.exists(head): try: makedirs_perms(head, user, group, mode) except OSError as exc: # be happy if someone already created the path if exc.errno != errno.EEXIST: raise if tail == os.curdir: # xxx/newdir/. exists if xxx/newdir exists return os.mkdir(name) check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) def get_devmm(name): ''' Get major/minor info from a device CLI Example: .. code-block:: bash salt '*' file.get_devmm /dev/chr ''' name = os.path.expanduser(name) if is_chrdev(name) or is_blkdev(name): stat_structure = os.stat(name) return ( os.major(stat_structure.st_rdev), os.minor(stat_structure.st_rdev)) else: return (0, 0) def is_chrdev(name): ''' Check if a file exists and is a character device. CLI Example: .. code-block:: bash salt '*' file.is_chrdev /dev/chr ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the character device does not exist in the first place return False else: raise return stat.S_ISCHR(stat_structure.st_mode) def mknod_chrdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a character device. CLI Example: .. code-block:: bash salt '*' file.mknod_chrdev /dev/chr 180 31 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating character device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFCHR, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created character device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_blkdev(name): ''' Check if a file exists and is a block device. CLI Example: .. code-block:: bash salt '*' file.is_blkdev /dev/blk ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the block device does not exist in the first place return False else: raise return stat.S_ISBLK(stat_structure.st_mode) def mknod_blkdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a block device. CLI Example: .. code-block:: bash salt '*' file.mknod_blkdev /dev/blk 8 999 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating block device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFBLK, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created block device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_fifo(name): ''' Check if a file exists and is a FIFO. CLI Example: .. code-block:: bash salt '*' file.is_fifo /dev/fifo ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the fifo does not exist in the first place return False else: raise return stat.S_ISFIFO(stat_structure.st_mode) def mknod_fifo(name, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a FIFO pipe. CLI Example: .. code-block:: bash salt '*' file.mknod_fifo /dev/fifo ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating FIFO name: %s', name) try: if __opts__['test']: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = None else: if os.mkfifo(name, int(six.text_type(mode).lstrip('0Oo'), 8)) is None: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created fifo check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def mknod(name, ntype, major=0, minor=0, user=None, group=None, mode='0600'): ''' .. versionadded:: 0.17.0 Create a block device, character device, or fifo pipe. Identical to the gnu mknod. CLI Examples: .. code-block:: bash salt '*' file.mknod /dev/chr c 180 31 salt '*' file.mknod /dev/blk b 8 999 salt '*' file.nknod /dev/fifo p ''' ret = False makedirs_(name, user, group) if ntype == 'c': ret = mknod_chrdev(name, major, minor, user, group, mode) elif ntype == 'b': ret = mknod_blkdev(name, major, minor, user, group, mode) elif ntype == 'p': ret = mknod_fifo(name, user, group, mode) else: raise SaltInvocationError( 'Node type unavailable: \'{0}\'. Available node types are ' 'character (\'c\'), block (\'b\'), and pipe (\'p\').'.format(ntype) ) return ret def list_backups(path, limit=None): ''' .. versionadded:: 0.17.0 Lists the previous versions of a file backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups /foo/bar/baz.txt ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows src_dir = parent_dir.replace(':', '_') else: src_dir = parent_dir[1:] # Figure out full path of location of backup file in minion cache bkdir = os.path.join(bkroot, src_dir) if not os.path.isdir(bkdir): return {} files = {} for fname in [x for x in os.listdir(bkdir) if os.path.isfile(os.path.join(bkdir, x))]: if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows strpfmt = '{0}_%a_%b_%d_%H-%M-%S_%f_%Y'.format(basename) else: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(fname, strpfmt) except ValueError: # File didn't match the strp format string, so it's not a backup # for this file. Move on to the next one. continue if salt.utils.platform.is_windows(): str_format = '%a %b %d %Y %H-%M-%S.%f' else: str_format = '%a %b %d %Y %H:%M:%S.%f' files.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime(str_format) location = os.path.join(bkdir, fname) files[timestamp]['Size'] = os.stat(location).st_size files[timestamp]['Location'] = location return dict(list(zip( list(range(len(files))), [files[x] for x in sorted(files, reverse=True)[:limit]] ))) list_backup = salt.utils.functools.alias_function(list_backups, 'list_backup') def list_backups_dir(path, limit=None): ''' Lists the previous versions of a directory backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The directory on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups_dir /foo/bar/baz/ ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups_dir: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) # Figure out full path of location of backup folder in minion cache bkdir = os.path.join(bkroot, parent_dir[1:]) if not os.path.isdir(bkdir): return {} files = {} f = dict([(i, len(list(n))) for i, n in itertools.groupby([x.split("_")[0] for x in sorted(os.listdir(bkdir))])]) ff = os.listdir(bkdir) for i, n in six.iteritems(f): ssfile = {} for x in sorted(ff): basename = x.split('_')[0] if i == basename: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(x, strpfmt) except ValueError: # Folder didn't match the strp format string, so it's not a backup # for this folder. Move on to the next one. continue ssfile.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime('%a %b %d %Y %H:%M:%S.%f') location = os.path.join(bkdir, x) ssfile[timestamp]['Size'] = os.stat(location).st_size ssfile[timestamp]['Location'] = location sfiles = dict(list(zip(list(range(n)), [ssfile[x] for x in sorted(ssfile, reverse=True)[:limit]]))) sefiles = {i: sfiles} files.update(sefiles) return files def restore_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Restore a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to restore, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.restore_backup /foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) # Note: This only supports minion backups, so this function will need to be # modified if/when master backups are implemented. ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret salt.utils.files.backup_minion(path, _get_bkroot()) try: shutil.copyfile(backup['Location'], path) except IOError as exc: ret['comment'] = \ 'Unable to restore {0} to {1}: ' \ '{2}'.format(backup['Location'], path, exc) return ret else: ret['result'] = True ret['comment'] = 'Successfully restored {0} to ' \ '{1}'.format(backup['Location'], path) # Try to set proper ownership if not salt.utils.platform.is_windows(): try: fstat = os.stat(path) except (OSError, IOError): ret['comment'] += ', but was unable to set ownership' else: os.chown(path, fstat.st_uid, fstat.st_gid) return ret def delete_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Delete a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to delete, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.delete_backup /var/cache/salt/minion/file_backup/home/foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret try: os.remove(backup['Location']) except IOError as exc: ret['comment'] = 'Unable to remove {0}: {1}'.format(backup['Location'], exc) else: ret['result'] = True ret['comment'] = 'Successfully removed {0}'.format(backup['Location']) return ret remove_backup = salt.utils.functools.alias_function(delete_backup, 'remove_backup') def grep(path, pattern, *opts): ''' Grep for a string in the specified file .. note:: This function's return value is slated for refinement in future versions of Salt path Path to the file to be searched .. note:: Globbing is supported (i.e. ``/var/log/foo/*.log``, but if globbing is being used then the path should be quoted to keep the shell from attempting to expand the glob expression. pattern Pattern to match. For example: ``test``, or ``a[0-5]`` opts Additional command-line flags to pass to the grep command. For example: ``-v``, or ``-i -B2`` .. note:: The options should come after a double-dash (as shown in the examples below) to keep Salt's own argument parser from interpreting them. CLI Example: .. code-block:: bash salt '*' file.grep /etc/passwd nobody salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i -B2 salt '*' file.grep "/etc/sysconfig/network-scripts/*" ipaddr -- -i -l ''' path = os.path.expanduser(path) # Backup the path in case the glob returns nothing _path = path path = glob.glob(path) # If the list is empty no files exist # so we revert back to the original path # so the result is an error. if not path: path = _path split_opts = [] for opt in opts: try: split = salt.utils.args.shlex_split(opt) except AttributeError: split = salt.utils.args.shlex_split(six.text_type(opt)) if len(split) > 1: raise SaltInvocationError( 'Passing multiple command line arguments in a single string ' 'is not supported, please pass the following arguments ' 'separately: {0}'.format(opt) ) split_opts.extend(split) if isinstance(path, list): cmd = ['grep'] + split_opts + [pattern] + path else: cmd = ['grep'] + split_opts + [pattern, path] try: ret = __salt__['cmd.run_all'](cmd, python_shell=False) except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return ret def open_files(by_pid=False): ''' Return a list of all physical open files on the system. CLI Examples: .. code-block:: bash salt '*' file.open_files salt '*' file.open_files by_pid=True ''' # First we collect valid PIDs pids = {} procfs = os.listdir('/proc/') for pfile in procfs: try: pids[int(pfile)] = [] except ValueError: # Not a valid PID, move on pass # Then we look at the open files for each PID files = {} for pid in pids: ppath = '/proc/{0}'.format(pid) try: tids = os.listdir('{0}/task'.format(ppath)) except OSError: continue # Collect the names of all of the file descriptors fd_ = [] #try: # fd_.append(os.path.realpath('{0}/task/{1}exe'.format(ppath, tid))) #except Exception: # pass for fpath in os.listdir('{0}/fd'.format(ppath)): fd_.append('{0}/fd/{1}'.format(ppath, fpath)) for tid in tids: try: fd_.append( os.path.realpath('{0}/task/{1}/exe'.format(ppath, tid)) ) except OSError: continue for tpath in os.listdir('{0}/task/{1}/fd'.format(ppath, tid)): fd_.append('{0}/task/{1}/fd/{2}'.format(ppath, tid, tpath)) fd_ = sorted(set(fd_)) # Loop through file descriptors and return useful data for each file for fdpath in fd_: # Sometimes PIDs and TIDs disappear before we can query them try: name = os.path.realpath(fdpath) # Running stat on the file cuts out all of the sockets and # deleted files from the list os.stat(name) except OSError: continue if name not in files: files[name] = [pid] else: # We still want to know which PIDs are using each file files[name].append(pid) files[name] = sorted(set(files[name])) pids[pid].append(name) pids[pid] = sorted(set(pids[pid])) if by_pid: return pids return files def pardir(): ''' Return the relative parent directory path symbol for underlying OS .. versionadded:: 2014.7.0 This can be useful when constructing Salt Formulas. .. code-block:: jinja {% set pardir = salt['file.pardir']() %} {% set final_path = salt['file.join']('subdir', pardir, 'confdir') %} CLI Example: .. code-block:: bash salt '*' file.pardir ''' return os.path.pardir def normpath(path): ''' Returns Normalize path, eliminating double slashes, etc. .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.normpath'](tpldir + '/../vars.jinja') import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.normpath 'a/b/c/..' ''' return os.path.normpath(path) def basename(path): ''' Returns the final component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- set filename = salt['file.basename'](source_file) %} CLI Example: .. code-block:: bash salt '*' file.basename 'test/test.config' ''' return os.path.basename(path) def dirname(path): ''' Returns the directory component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.dirname'](tpldir) + '/vars.jinja' import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.dirname 'test/path/filename.config' ''' return os.path.dirname(path) def join(*args): ''' Return a normalized file system path for the underlying OS .. versionadded:: 2014.7.0 This can be useful at the CLI but is frequently useful when scripting combining path variables: .. code-block:: jinja {% set www_root = '/var' %} {% set app_dir = 'myapp' %} myapp_config: file: - managed - name: {{ salt['file.join'](www_root, app_dir, 'config.yaml') }} CLI Example: .. code-block:: bash salt '*' file.join '/' 'usr' 'local' 'bin' ''' return os.path.join(*args) def move(src, dst): ''' Move a file or directory CLI Example: .. code-block:: bash salt '*' file.move /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('Source path must be absolute.') if not os.path.isabs(dst): raise SaltInvocationError('Destination path must be absolute.') ret = { 'result': True, 'comment': "'{0}' moved to '{1}'".format(src, dst), } try: shutil.move(src, dst) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move '{0}' to '{1}': {2}".format(src, dst, exc) ) return ret def diskusage(path): ''' Recursively calculate disk usage of path and return it in bytes CLI Example: .. code-block:: bash salt '*' file.diskusage /path/to/check ''' total_size = 0 seen = set() if os.path.isfile(path): stat_structure = os.stat(path) ret = stat_structure.st_size return ret for dirpath, dirnames, filenames in salt.utils.path.os_walk(path): for f in filenames: fp = os.path.join(dirpath, f) try: stat_structure = os.stat(fp) except OSError: continue if stat_structure.st_ino in seen: continue seen.add(stat_structure.st_ino) total_size += stat_structure.st_size ret = total_size return ret
saltstack/salt
salt/modules/file.py
_binary_replace
python
def _binary_replace(old, new): ''' This function does NOT do any diffing, it just checks the old and new files to see if either is binary, and provides an appropriate string noting the difference between the two files. If neither file is binary, an empty string is returned. This function should only be run AFTER it has been determined that the files differ. ''' old_isbin = not __utils__['files.is_text'](old) new_isbin = not __utils__['files.is_text'](new) if any((old_isbin, new_isbin)): if all((old_isbin, new_isbin)): return 'Replace binary file' elif old_isbin: return 'Replace binary file with text file' elif new_isbin: return 'Replace text file with binary file' return ''
This function does NOT do any diffing, it just checks the old and new files to see if either is binary, and provides an appropriate string noting the difference between the two files. If neither file is binary, an empty string is returned. This function should only be run AFTER it has been determined that the files differ.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L112-L131
null
# -*- coding: utf-8 -*- ''' Manage information about regular files, directories, and special files on the minion, set/read user, group, mode, and data ''' # TODO: We should add the capability to do u+r type operations here # some time in the future from __future__ import absolute_import, print_function, unicode_literals # Import python libs import datetime import errno import fnmatch import io import itertools import logging import operator import os import re import shutil import stat import string import sys import tempfile import time import glob import hashlib import mmap from collections import Iterable, Mapping from functools import reduce # pylint: disable=redefined-builtin # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range, zip from salt.ext.six.moves.urllib.parse import urlparse as _urlparse # pylint: enable=import-error,no-name-in-module,redefined-builtin try: import grp import pwd except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.atomicfile import salt.utils.data import salt.utils.dictupdate import salt.utils.filebuffer import salt.utils.files import salt.utils.find import salt.utils.functools import salt.utils.hashutils import salt.utils.itertools import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.templates import salt.utils.url import salt.utils.user from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError, get_error_message as _get_error_message from salt.utils.files import HASHES, HASHES_REVMAP log = logging.getLogger(__name__) __func_alias__ = { 'makedirs_': 'makedirs' } def __virtual__(): ''' Only work on POSIX-like systems ''' # win_file takes care of windows if salt.utils.platform.is_windows(): return ( False, 'The file execution module cannot be loaded: only available on ' 'non-Windows systems - use win_file instead.' ) return True def __clean_tmp(sfn): ''' Clean out a template temp file ''' if sfn.startswith(os.path.join(tempfile.gettempdir(), salt.utils.files.TEMPFILE_PREFIX)): # Don't remove if it exists in file_roots (any saltenv) all_roots = itertools.chain.from_iterable( six.itervalues(__opts__['file_roots'])) in_roots = any(sfn.startswith(root) for root in all_roots) # Only clean up files that exist if os.path.exists(sfn) and not in_roots: os.remove(sfn) def _error(ret, err_msg): ''' Common function for setting error information for return dicts ''' ret['result'] = False ret['comment'] = err_msg return ret def _get_bkroot(): ''' Get the location of the backup dir in the minion cache ''' # Get the cachedir from the minion config return os.path.join(__salt__['config.get']('cachedir'), 'file_backup') def _splitlines_preserving_trailing_newline(str): ''' Returns a list of the lines in the string, breaking at line boundaries and preserving a trailing newline (if present). Essentially, this works like ``str.striplines(False)`` but preserves an empty line at the end. This is equivalent to the following code: .. code-block:: python lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') ''' lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') return lines def gid_to_group(gid): ''' Convert the group id to the group name on this system gid gid to convert to a group name CLI Example: .. code-block:: bash salt '*' file.gid_to_group 0 ''' try: gid = int(gid) except ValueError: # This is not an integer, maybe it's already the group name? gid = group_to_gid(gid) if gid == '': # Don't even bother to feed it to grp return '' try: return grp.getgrgid(gid).gr_name except (KeyError, NameError): # If group is not present, fall back to the gid. return gid def group_to_gid(group): ''' Convert the group to the gid on this system group group to convert to its gid CLI Example: .. code-block:: bash salt '*' file.group_to_gid root ''' if group is None: return '' try: if isinstance(group, int): return group return grp.getgrnam(group).gr_gid except KeyError: return '' def get_gid(path, follow_symlinks=True): ''' Return the id of the group that owns a given file path file or directory of which to get the gid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_gid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('gid', -1) def get_group(path, follow_symlinks=True): ''' Return the group that owns a given file path file or directory of which to get the group follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_group /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('group', False) def uid_to_user(uid): ''' Convert a uid to a user name uid uid to convert to a username CLI Example: .. code-block:: bash salt '*' file.uid_to_user 0 ''' try: return pwd.getpwuid(uid).pw_name except (KeyError, NameError): # If user is not present, fall back to the uid. return uid def user_to_uid(user): ''' Convert user name to a uid user user name to convert to its uid CLI Example: .. code-block:: bash salt '*' file.user_to_uid root ''' if user is None: user = salt.utils.user.get_user() try: if isinstance(user, int): return user return pwd.getpwnam(user).pw_uid except KeyError: return '' def get_uid(path, follow_symlinks=True): ''' Return the id of the user that owns a given file path file or directory of which to get the uid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_uid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('uid', -1) def get_user(path, follow_symlinks=True): ''' Return the user that owns a given file path file or directory of which to get the user follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_user /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('user', False) def get_mode(path, follow_symlinks=True): ''' Return the mode of a file path file or directory of which to get the mode follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_mode /etc/passwd .. versionchanged:: 2014.1.0 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('mode', '') def set_mode(path, mode): ''' Set the mode of a file path file or directory of which to set the mode mode mode to set the path to CLI Example: .. code-block:: bash salt '*' file.set_mode /etc/passwd 0644 ''' path = os.path.expanduser(path) mode = six.text_type(mode).lstrip('0Oo') if not mode: mode = '0' if not os.path.exists(path): raise CommandExecutionError('{0}: File not found'.format(path)) try: os.chmod(path, int(mode, 8)) except Exception: return 'Invalid Mode ' + mode return get_mode(path) def lchown(path, user, group): ''' Chown a file, pass the file the desired user and group without following symlinks. path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 return os.lchown(path, uid, gid) def chown(path, user, group): ''' Chown a file, pass the file the desired user and group path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 if not os.path.exists(path): try: # Broken symlinks will return false, but still need to be chowned return os.lchown(path, uid, gid) except OSError: pass err += 'File not found' if err: return err return os.chown(path, uid, gid) def chgrp(path, group): ''' Change the group of a file path path to the file or directory group group owner CLI Example: .. code-block:: bash salt '*' file.chgrp /etc/passwd root ''' path = os.path.expanduser(path) user = get_user(path) return chown(path, user, group) def _cmp_attrs(path, attrs): ''' .. versionadded:: 2018.3.0 Compare attributes of a given file to given attributes. Returns a pair (list) where first item are attributes to add and second item are to be removed. Please take into account when using this function that some minions will not have lsattr installed. path path to file to compare attributes with. attrs string of attributes to compare against a given file ''' diff = [None, None] # lsattr for AIX is not the same thing as lsattr for linux. if salt.utils.platform.is_aix(): return None try: lattrs = lsattr(path).get(path, '') except AttributeError: # lsattr not installed return None old = [chr for chr in lattrs if chr not in attrs] if old: diff[1] = ''.join(old) new = [chr for chr in attrs if chr not in lattrs] if new: diff[0] = ''.join(new) return diff def lsattr(path): ''' .. versionadded:: 2018.3.0 .. versionchanged:: 2018.3.1 If ``lsattr`` is not installed on the system, ``None`` is returned. .. versionchanged:: 2018.3.4 If on ``AIX``, ``None`` is returned even if in filesystem as lsattr on ``AIX`` is not the same thing as the linux version. Obtain the modifiable attributes of the given file. If path is to a directory, an empty list is returned. path path to file to obtain attributes of. File/directory must exist. CLI Example: .. code-block:: bash salt '*' file.lsattr foo1.txt ''' if not salt.utils.path.which('lsattr') or salt.utils.platform.is_aix(): return None if not os.path.exists(path): raise SaltInvocationError("File or directory does not exist: " + path) cmd = ['lsattr', path] result = __salt__['cmd.run'](cmd, ignore_retcode=True, python_shell=False) results = {} for line in result.splitlines(): if not line.startswith('lsattr: '): vals = line.split(None, 1) results[vals[1]] = re.findall(r"[aAcCdDeijPsStTu]", vals[0]) return results def chattr(*files, **kwargs): ''' .. versionadded:: 2018.3.0 Change the attributes of files. This function accepts one or more files and the following options: operator Can be wither ``add`` or ``remove``. Determines whether attributes should be added or removed from files attributes One or more of the following characters: ``aAcCdDeijPsStTu``, representing attributes to add to/remove from files version a version number to assign to the file(s) flags One or more of the following characters: ``RVf``, representing flags to assign to chattr (recurse, verbose, suppress most errors) CLI Example: .. code-block:: bash salt '*' file.chattr foo1.txt foo2.txt operator=add attributes=ai salt '*' file.chattr foo3.txt operator=remove attributes=i version=2 ''' operator = kwargs.pop('operator', None) attributes = kwargs.pop('attributes', None) flags = kwargs.pop('flags', None) version = kwargs.pop('version', None) if (operator is None) or (operator not in ('add', 'remove')): raise SaltInvocationError( "Need an operator: 'add' or 'remove' to modify attributes.") if attributes is None: raise SaltInvocationError("Need attributes: [aAcCdDeijPsStTu]") cmd = ['chattr'] if operator == "add": attrs = '+{0}'.format(attributes) elif operator == "remove": attrs = '-{0}'.format(attributes) cmd.append(attrs) if flags is not None: cmd.append('-{0}'.format(flags)) if version is not None: cmd.extend(['-v', version]) cmd.extend(files) result = __salt__['cmd.run'](cmd, python_shell=False) if bool(result): raise CommandExecutionError( "chattr failed to run, possibly due to bad parameters.") return True def get_sum(path, form='sha256'): ''' Return the checksum for the given file. The following checksum algorithms are supported: * md5 * sha1 * sha224 * sha256 **(default)** * sha384 * sha512 path path to the file or directory form desired sum format CLI Example: .. code-block:: bash salt '*' file.get_sum /etc/passwd sha512 ''' path = os.path.expanduser(path) if not os.path.isfile(path): return 'File not found' return salt.utils.hashutils.get_hash(path, form, 4096) def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` path path to the file or directory form desired sum format chunk_size amount to sum at once CLI Example: .. code-block:: bash salt '*' file.get_hash /etc/shadow ''' return salt.utils.hashutils.get_hash(os.path.expanduser(path), form, chunk_size) def get_source_sum(file_name='', source='', source_hash=None, source_hash_name=None, saltenv='base'): ''' .. versionadded:: 2016.11.0 Used by :py:func:`file.get_managed <salt.modules.file.get_managed>` to obtain the hash and hash type from the parameters specified below. file_name Optional file name being managed, for matching with :py:func:`file.extract_hash <salt.modules.file.extract_hash>`. source Source file, as used in :py:mod:`file <salt.states.file>` and other states. If ``source_hash`` refers to a file containing hashes, then this filename will be used to match a filename in that file. If the ``source_hash`` is a hash expression, then this argument will be ignored. source_hash Hash file/expression, as used in :py:mod:`file <salt.states.file>` and other states. If this value refers to a remote URL or absolute path to a local file, it will be cached and :py:func:`file.extract_hash <salt.modules.file.extract_hash>` will be used to obtain a hash from it. source_hash_name Specific file name to look for when ``source_hash`` refers to a remote file, used to disambiguate ambiguous matches. saltenv : base Salt fileserver environment from which to retrieve the source_hash. This value will only be used when ``source_hash`` refers to a file on the Salt fileserver (i.e. one beginning with ``salt://``). CLI Example: .. code-block:: bash salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=499ae16dcae71eeb7c3a30c75ea7a1a6 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 source_hash_name=./dir2/foo.tar.gz ''' def _invalid_source_hash_format(): ''' DRY helper for reporting invalid source_hash input ''' raise CommandExecutionError( 'Source hash {0} format is invalid. The supported formats are: ' '1) a hash, 2) an expression in the format <hash_type>=<hash>, or ' '3) either a path to a local file containing hashes, or a URI of ' 'a remote hash file. Supported protocols for remote hash files ' 'are: {1}. The hash may also not be of a valid length, the ' 'following are supported hash types and lengths: {2}.'.format( source_hash, ', '.join(salt.utils.files.VALID_PROTOS), ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) hash_fn = None if os.path.isabs(source_hash): hash_fn = source_hash else: try: proto = _urlparse(source_hash).scheme if proto in salt.utils.files.VALID_PROTOS: hash_fn = __salt__['cp.cache_file'](source_hash, saltenv) if not hash_fn: raise CommandExecutionError( 'Source hash file {0} not found'.format(source_hash) ) else: if proto != '': # Some unsupported protocol (e.g. foo://) is being used. # We'll get into this else block if a hash expression # (like md5=<md5 checksum here>), but in those cases, the # protocol will be an empty string, in which case we avoid # this error condition. _invalid_source_hash_format() except (AttributeError, TypeError): _invalid_source_hash_format() if hash_fn is not None: ret = extract_hash(hash_fn, '', file_name, source, source_hash_name) if ret is None: _invalid_source_hash_format() ret['hsum'] = ret['hsum'].lower() return ret else: # The source_hash is a hash expression ret = {} try: ret['hash_type'], ret['hsum'] = \ [x.strip() for x in source_hash.split('=', 1)] except AttributeError: _invalid_source_hash_format() except ValueError: # No hash type, try to figure out by hash length if not re.match('^[{0}]+$'.format(string.hexdigits), source_hash): _invalid_source_hash_format() ret['hsum'] = source_hash source_hash_len = len(source_hash) if source_hash_len in HASHES_REVMAP: ret['hash_type'] = HASHES_REVMAP[source_hash_len] else: _invalid_source_hash_format() if ret['hash_type'] not in HASHES: raise CommandExecutionError( 'Invalid hash type \'{0}\'. Supported hash types are: {1}. ' 'Either remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to a supported type.' .format(ret['hash_type'], ', '.join(HASHES), ret['hsum']) ) else: hsum_len = len(ret['hsum']) if hsum_len not in HASHES_REVMAP: _invalid_source_hash_format() elif hsum_len != HASHES[ret['hash_type']]: raise CommandExecutionError( 'Invalid length ({0}) for hash type \'{1}\'. Either ' 'remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to \'{3}\''.format( hsum_len, ret['hash_type'], ret['hsum'], HASHES_REVMAP[hsum_len], ) ) ret['hsum'] = ret['hsum'].lower() return ret def check_hash(path, file_hash): ''' Check if a file matches the given hash string Returns ``True`` if the hash matches, otherwise ``False``. path Path to a file local to the minion. hash The hash to check against the file specified in the ``path`` argument. .. versionchanged:: 2016.11.4 For this and newer versions the hash can be specified without an accompanying hash type (e.g. ``e138491e9d5b97023cea823fe17bac22``), but for earlier releases it is necessary to also specify the hash type in the format ``<hash_type>=<hash_value>`` (e.g. ``md5=e138491e9d5b97023cea823fe17bac22``). CLI Example: .. code-block:: bash salt '*' file.check_hash /etc/fstab e138491e9d5b97023cea823fe17bac22 salt '*' file.check_hash /etc/fstab md5=e138491e9d5b97023cea823fe17bac22 ''' path = os.path.expanduser(path) if not isinstance(file_hash, six.string_types): raise SaltInvocationError('hash must be a string') for sep in (':', '='): if sep in file_hash: hash_type, hash_value = file_hash.split(sep, 1) break else: hash_value = file_hash hash_len = len(file_hash) hash_type = HASHES_REVMAP.get(hash_len) if hash_type is None: raise SaltInvocationError( 'Hash {0} (length: {1}) could not be matched to a supported ' 'hash type. The supported hash types and lengths are: ' '{2}'.format( file_hash, hash_len, ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) return get_hash(path, hash_type) == hash_value def find(path, *args, **kwargs): ''' Approximate the Unix ``find(1)`` command and return a list of paths that meet the specified criteria. The options include match criteria: .. code-block:: text name = path-glob # case sensitive iname = path-glob # case insensitive regex = path-regex # case sensitive iregex = path-regex # case insensitive type = file-types # match any listed type user = users # match any listed user group = groups # match any listed group size = [+-]number[size-unit] # default unit = byte mtime = interval # modified since date grep = regex # search file contents and/or actions: .. code-block:: text delete [= file-types] # default type = 'f' exec = command [arg ...] # where {} is replaced by pathname print [= print-opts] and/or depth criteria: .. code-block:: text maxdepth = maximum depth to transverse in path mindepth = minimum depth to transverse before checking files or directories The default action is ``print=path`` ``path-glob``: .. code-block:: text * = match zero or more chars ? = match any char [abc] = match a, b, or c [!abc] or [^abc] = match anything except a, b, and c [x-y] = match chars x through y [!x-y] or [^x-y] = match anything except chars x through y {a,b,c} = match a or b or c ``path-regex``: a Python Regex (regular expression) pattern to match pathnames ``file-types``: a string of one or more of the following: .. code-block:: text a: all file types b: block device c: character device d: directory p: FIFO (named pipe) f: plain file l: symlink s: socket ``users``: a space and/or comma separated list of user names and/or uids ``groups``: a space and/or comma separated list of group names and/or gids ``size-unit``: .. code-block:: text b: bytes k: kilobytes m: megabytes g: gigabytes t: terabytes interval: .. code-block:: text [<num>w] [<num>d] [<num>h] [<num>m] [<num>s] where: w: week d: day h: hour m: minute s: second print-opts: a comma and/or space separated list of one or more of the following: .. code-block:: text group: group name md5: MD5 digest of file contents mode: file permissions (as integer) mtime: last modification time (as time_t) name: file basename path: file absolute path size: file size in bytes type: file type user: user name CLI Examples: .. code-block:: bash salt '*' file.find / type=f name=\\*.bak size=+10m salt '*' file.find /var mtime=+30d size=+10m print=path,size,mtime salt '*' file.find /var/log name=\\*.[0-9] mtime=+30d size=+10m delete ''' if 'delete' in args: kwargs['delete'] = 'f' elif 'print' in args: kwargs['print'] = 'path' try: finder = salt.utils.find.Finder(kwargs) except ValueError as ex: return 'error: {0}'.format(ex) ret = [item for i in [finder.find(p) for p in glob.glob(os.path.expanduser(path))] for item in i] ret.sort() return ret def _sed_esc(string, escape_all=False): ''' Escape single quotes and forward slashes ''' special_chars = "^.[$()|*+?{" string = string.replace("'", "'\"'\"'").replace("/", "\\/") if escape_all is True: for char in special_chars: string = string.replace(char, "\\" + char) return string def sed(path, before, after, limit='', backup='.bak', options='-r -e', flags='g', escape_all=False, negate_match=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup options : ``-r -e`` Options to pass to sed flags : ``g`` Flags to modify the sed search; e.g., ``i`` for case-insensitive pattern matching negate_match : False Negate the search command (``!``) .. versionadded:: 0.17.0 Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # path = os.path.expanduser(path) if not os.path.exists(path): return False # Mandate that before and after are strings before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.append('-i{0}'.format(backup) if backup else '-i') cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}{negate_match}s/{before}/{after}/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', negate_match='!' if negate_match else '', before=before, after=after, flags=flags ) ) cmd.append(path) return __salt__['cmd.run_all'](cmd, python_shell=False) def sed_contains(path, text, limit='', flags='g'): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the file at ``path`` contains ``text``. Utilizes sed to perform the search (line-wise search). Note: the ``p`` flag will be added to any flags you pass in. CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' # Largely inspired by Fabric's contrib.files.contains() path = os.path.expanduser(path) if not os.path.exists(path): return False before = _sed_esc(six.text_type(text), False) limit = _sed_esc(six.text_type(limit), False) options = '-n -r -e' if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}s/{before}/$/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', before=before, flags='p{0}'.format(flags) ) ) cmd.append(path) result = __salt__['cmd.run'](cmd, python_shell=False) return bool(result) def psed(path, before, after, limit='', backup='.bak', flags='gMS', escape_all=False, multi=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file (pure Python version) Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup flags : ``gMS`` Flags to modify the search. Valid values are: - ``g``: Replace all occurrences of the pattern, not just the first. - ``I``: Ignore case. - ``L``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\s`` and ``\\S`` dependent on the locale. - ``M``: Treat multiple lines as a single line. - ``S``: Make `.` match all characters, including newlines. - ``U``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\d``, ``\\D``, ``\\s`` and ``\\S`` dependent on Unicode. - ``X``: Verbose (whitespace is ignored). multi: ``False`` If True, treat the entire file as a single line Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # # Mandate that before and after are strings path = os.path.expanduser(path) multi = bool(multi) before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) # The pattern to replace with does not need to be escaped!!! # after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) shutil.copy2(path, '{0}{1}'.format(path, backup)) with salt.utils.files.fopen(path, 'w') as ofile: with salt.utils.files.fopen('{0}{1}'.format(path, backup), 'r') as ifile: if multi is True: for line in ifile.readline(): ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(line), before, after, limit, flags ) ) ) else: ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(ifile.read()), before, after, limit, flags ) ) ) RE_FLAG_TABLE = {'I': re.I, 'L': re.L, 'M': re.M, 'S': re.S, 'U': re.U, 'X': re.X} def _psed(text, before, after, limit, flags): ''' Does the actual work for file.psed, so that single lines can be passed in ''' atext = text if limit: limit = re.compile(limit) comps = text.split(limit) atext = ''.join(comps[1:]) count = 1 if 'g' in flags: count = 0 flags = flags.replace('g', '') aflags = 0 for flag in flags: aflags |= RE_FLAG_TABLE[flag] before = re.compile(before, flags=aflags) text = re.sub(before, after, atext, count=count) return text def uncomment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Uncomment specified commented lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be uncommented. This regex should not include the comment character. A leading ``^`` character will be stripped for convenience (for easily switching between comment() and uncomment()). char : ``#`` The character to remove in order to uncomment a line backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup CLI Example: .. code-block:: bash salt '*' file.uncomment /etc/hosts.deny 'ALL: PARANOID' ''' return comment_line(path=path, regex=regex, char=char, cmnt=False, backup=backup) def comment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Comment out specified lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be commented; this pattern will be wrapped in parenthesis and will move any preceding/trailing ``^`` or ``$`` characters outside the parenthesis (e.g., the pattern ``^foo$`` will be rewritten as ``^(foo)$``) char : ``#`` The character to be inserted at the beginning of a line in order to comment it out backup : ``.bak`` The file will be backed up before edit with this file extension .. warning:: This backup will be overwritten each time ``sed`` / ``comment`` / ``uncomment`` is called. Meaning the backup will only be useful after the first invocation. CLI Example: .. code-block:: bash salt '*' file.comment /etc/modules pcspkr ''' return comment_line(path=path, regex=regex, char=char, cmnt=True, backup=backup) def comment_line(path, regex, char='#', cmnt=True, backup='.bak'): r''' Comment or Uncomment a line in a text file. :param path: string The full path to the text file. :param regex: string A regex expression that begins with ``^`` that will find the line you wish to comment. Can be as simple as ``^color =`` :param char: string The character used to comment a line in the type of file you're referencing. Default is ``#`` :param cmnt: boolean True to comment the line. False to uncomment the line. Default is True. :param backup: string The file extension to give the backup file. Default is ``.bak`` Set to False/None to not keep a backup. :return: boolean Returns True if successful, False if not CLI Example: The following example will comment out the ``pcspkr`` line in the ``/etc/modules`` file using the default ``#`` character and create a backup file named ``modules.bak`` .. code-block:: bash salt '*' file.comment_line '/etc/modules' '^pcspkr' CLI Example: The following example will uncomment the ``log_level`` setting in ``minion`` config file if it is set to either ``warning``, ``info``, or ``debug`` using the ``#`` character and create a backup file named ``minion.bk`` .. code-block:: bash salt '*' file.comment_line 'C:\salt\conf\minion' '^log_level: (warning|info|debug)' '#' False '.bk' ''' # Get the regex for comment or uncomment if cmnt: regex = '{0}({1}){2}'.format( '^' if regex.startswith('^') else '', regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') else: regex = r'^{0}\s*({1}){2}'.format( char, regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') # Load the real path to the file path = os.path.realpath(os.path.expanduser(path)) # Make sure the file exists if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) # Make sure it is a text file if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}'.format(path)) # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes found = False # Dictionaries for comparing changes orig_file = [] new_file = [] # Buffer size for fopen bufsize = os.path.getsize(path) try: # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: # Is it in this line line = salt.utils.stringutils.to_unicode(line) if re.match(regex, line): # Load lines into dictionaries, set found to True orig_file.append(line) if cmnt: new_file.append('{0}{1}'.format(char, line)) else: new_file.append(line.lstrip(char)) found = True except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) # We've searched the whole file. If we didn't find anything, return False if not found: return False if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Create a copy to read from and to use as a backup later try: temp_file = _mkstemp_copy(path=path, preserve_inode=False) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) try: # Open the file in write mode mode = 'wb' if six.PY2 and salt.utils.platform.is_windows() else 'w' with salt.utils.files.fopen(path, mode=mode, buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: line = salt.utils.stringutils.to_unicode(line) try: # Is it in this line if re.match(regex, line): # Write the new line if cmnt: wline = '{0}{1}'.format(char, line) else: wline = line.lstrip(char) else: # Write the existing line (no change) wline = line wline = salt.utils.stringutils.to_bytes(wline) \ if six.PY2 and salt.utils.platform.is_windows() \ else salt.utils.stringutils.to_str(wline) w_file.write(wline) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if backup: # Move the backup file to the original directory backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: os.remove(temp_file) if not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) # Return a diff using the two dictionaries return __utils__['stringutils.get_diff'](orig_file, new_file) def _get_flags(flags): ''' Return an integer appropriate for use as a flag for the re module from a list of human-readable strings .. code-block:: python >>> _get_flags(['MULTILINE', 'IGNORECASE']) 10 >>> _get_flags('MULTILINE') 8 >>> _get_flags(2) 2 ''' if isinstance(flags, six.string_types): flags = [flags] if isinstance(flags, Iterable) and not isinstance(flags, Mapping): _flags_acc = [] for flag in flags: _flag = getattr(re, six.text_type(flag).upper()) if not isinstance(_flag, six.integer_types): raise SaltInvocationError( 'Invalid re flag given: {0}'.format(flag) ) _flags_acc.append(_flag) return reduce(operator.__or__, _flags_acc) elif isinstance(flags, six.integer_types): return flags else: raise SaltInvocationError( 'Invalid re flags: "{0}", must be given either as a single flag ' 'string, a list of strings, or as an integer'.format(flags) ) def _add_flags(flags, new_flags): ''' Combine ``flags`` and ``new_flags`` ''' flags = _get_flags(flags) new_flags = _get_flags(new_flags) return flags | new_flags def _mkstemp_copy(path, preserve_inode=True): ''' Create a temp file and move/copy the contents of ``path`` to the temp file. Return the path to the temp file. path The full path to the file whose contents will be moved/copied to a temp file. Whether it's moved or copied depends on the value of ``preserve_inode``. preserve_inode Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). Default is ``True``. ''' temp_file = None # Create the temp file try: temp_file = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to create temp file. " "Exception: {0}".format(exc) ) # use `copy` to preserve the inode of the # original file, and thus preserve hardlinks # to the inode. otherwise, use `move` to # preserve prior behavior, which results in # writing the file to a new inode. if preserve_inode: try: shutil.copy2(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to copy file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: try: shutil.move(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) return temp_file def _starts_till(src, probe, strip_comments=True): ''' Returns True if src and probe at least matches at the beginning till some point. ''' def _strip_comments(txt): ''' Strip possible comments. Usually comments are one or two symbols at the beginning of the line, separated with space ''' buff = txt.split(" ", 1) return len(buff) == 2 and len(buff[0]) < 2 and buff[1] or txt def _to_words(txt): ''' Split by words ''' return txt and [w for w in txt.strip().split(" ") if w.strip()] or txt no_match = -1 equal = 0 if not src or not probe: return no_match src = src.rstrip('\n\r') probe = probe.rstrip('\n\r') if src == probe: return equal src = _to_words(strip_comments and _strip_comments(src) or src) probe = _to_words(strip_comments and _strip_comments(probe) or probe) a_buff, b_buff = len(src) < len(probe) and (src, probe) or (probe, src) b_buff = ' '.join(b_buff) for idx in range(len(a_buff)): prb = ' '.join(a_buff[:-(idx + 1)]) if prb and b_buff.startswith(prb): return idx return no_match def _regex_to_static(src, regex): ''' Expand regular expression to static match. ''' if not src or not regex: return None try: compiled = re.compile(regex, re.DOTALL) src = [line for line in src if compiled.search(line) or line.count(regex)] except Exception as ex: raise CommandExecutionError("{0}: '{1}'".format(_get_error_message(ex), regex)) return src and src or [] def _assert_occurrence(probe, target, amount=1): ''' Raise an exception, if there are different amount of specified occurrences in src. ''' occ = len(probe) if occ > amount: msg = 'more than' elif occ < amount: msg = 'less than' elif not occ: msg = 'no' else: msg = None if msg: raise CommandExecutionError('Found {0} expected occurrences in "{1}" expression'.format(msg, target)) return occ def _set_line_indent(src, line, indent): ''' Indent the line with the source line. ''' if not indent: return line idt = [] for c in src: if c not in ['\t', ' ']: break idt.append(c) return ''.join(idt) + line.lstrip() def _get_eol(line): match = re.search('((?<!\r)\n|\r(?!\n)|\r\n)$', line) return match and match.group() or '' def _set_line_eol(src, line): ''' Add line ending ''' line_ending = _get_eol(src) or os.linesep return line.rstrip() + line_ending def _insert_line_before(idx, body, content, indent): if not idx or (idx and _starts_till(body[idx - 1], content) < 0): cnd = _set_line_indent(body[idx], content, indent) body.insert(idx, cnd) return body def _insert_line_after(idx, body, content, indent): # No duplicates or append, if "after" is the last line next_line = idx + 1 < len(body) and body[idx + 1] or None if next_line is None or _starts_till(next_line, content) < 0: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) return body def line(path, content=None, match=None, mode=None, location=None, before=None, after=None, show_changes=True, backup=False, quiet=False, indent=True): ''' .. versionadded:: 2015.8.0 Edit a line in the configuration file. The ``path`` and ``content`` arguments are required, as well as passing in one of the ``mode`` options. path Filesystem path to the file to be edited. content Content of the line. Allowed to be empty if mode=delete. match Match the target line for an action by a fragment of a string or regular expression. If neither ``before`` nor ``after`` are provided, and ``match`` is also ``None``, match becomes the ``content`` value. mode Defines how to edit a line. One of the following options is required: - ensure If line does not exist, it will be added. This is based on the ``content`` argument. - replace If line already exists, it will be replaced. - delete Delete the line, once found. - insert Insert a line. .. note:: If ``mode=insert`` is used, at least one of the following options must also be defined: ``location``, ``before``, or ``after``. If ``location`` is used, it takes precedence over the other two options. location Defines where to place content in the line. Note this option is only used when ``mode=insert`` is specified. If a location is passed in, it takes precedence over both the ``before`` and ``after`` kwargs. Valid locations are: - start Place the content at the beginning of the file. - end Place the content at the end of the file. before Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. after Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. show_changes Output a unified diff of the old file and the new file. If ``False`` return a boolean if any changes were made. Default is ``True`` .. note:: Using this option will store two copies of the file in-memory (the original version and the edited version) in order to generate the diff. backup Create a backup of the original file with the extension: "Year-Month-Day-Hour-Minutes-Seconds". quiet Do not raise any exceptions. E.g. ignore the fact that the file that is tried to be edited does not exist and nothing really happened. indent Keep indentation with the previous line. This option is not considered when the ``delete`` mode is specified. CLI Example: .. code-block:: bash salt '*' file.line /etc/nsswitch.conf "networks:\tfiles dns" after="hosts:.*?" mode='ensure' .. note:: If an equal sign (``=``) appears in an argument to a Salt command, it is interpreted as a keyword argument in the format of ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.line /path/to/file content="CREATEMAIL_SPOOL=no" match="CREATE_MAIL_SPOOL=yes" mode="replace" ''' path = os.path.realpath(os.path.expanduser(path)) if not os.path.isfile(path): if not quiet: raise CommandExecutionError('File "{0}" does not exists or is not a file.'.format(path)) return False # No changes had happened mode = mode and mode.lower() or mode if mode not in ['insert', 'ensure', 'delete', 'replace']: if mode is None: raise CommandExecutionError('Mode was not defined. How to process the file?') else: raise CommandExecutionError('Unknown mode: "{0}"'.format(mode)) # We've set the content to be empty in the function params but we want to make sure # it gets passed when needed. Feature #37092 empty_content_modes = ['delete'] if mode not in empty_content_modes and content is None: raise CommandExecutionError('Content can only be empty if mode is "{0}"'.format(', '.join(empty_content_modes))) del empty_content_modes # Before/after has privilege. If nothing defined, match is used by content. if before is None and after is None and not match: match = content with salt.utils.files.fopen(path, mode='r') as fp_: body = salt.utils.data.decode_list(fp_.readlines()) body_before = hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() # Add empty line at the end if last line ends with eol. # Allows simpler code if body and _get_eol(body[-1]): body.append('') after = _regex_to_static(body, after) before = _regex_to_static(body, before) match = _regex_to_static(body, match) if os.stat(path).st_size == 0 and mode in ('delete', 'replace'): log.warning('Cannot find text to %s. File \'%s\' is empty.', mode, path) body = [] elif mode == 'delete' and match: body = [line for line in body if line != match[0]] elif mode == 'replace' and match: idx = body.index(match[0]) file_line = body.pop(idx) body.insert(idx, _set_line_indent(file_line, content, indent)) elif mode == 'insert': if not location and not before and not after: raise CommandExecutionError('On insert must be defined either "location" or "before/after" conditions.') if not location: if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') out = [] in_range = False for line in body: if line == after[0]: in_range = True elif line == before[0] and in_range: cnd = _set_line_indent(line, content, indent) out.append(cnd) out.append(line) body = out if before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif after and not before: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: if location == 'start': if body: body.insert(0, _set_line_eol(body[0], content)) else: body.append(content + os.linesep) elif location == 'end': body.append(_set_line_indent(body[-1], content, indent) if body else content) elif mode == 'ensure': if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') is_there = bool([l for l in body if l.count(content)]) if not is_there: idx = body.index(after[0]) if idx < (len(body) - 1) and body[idx + 1] == before[0]: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) else: raise CommandExecutionError('Found more than one line between ' 'boundaries "before" and "after".') elif before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif not before and after: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: raise CommandExecutionError("Wrong conditions? " "Unable to ensure line without knowing " "where to put it before and/or after.") if body: for idx, line in enumerate(body): if not _get_eol(line) and idx+1 < len(body): prev = idx and idx-1 or 1 body[idx] = _set_line_eol(body[prev], line) # We do not need empty line at the end anymore if '' == body[-1]: body.pop() changed = body_before != hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() if backup and changed and __opts__['test'] is False: try: temp_file = _mkstemp_copy(path=path, preserve_inode=True) shutil.move(temp_file, '{0}.{1}'.format(path, time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime()))) except (OSError, IOError) as exc: raise CommandExecutionError("Unable to create the backup file of {0}. Exception: {1}".format(path, exc)) changes_diff = None if changed: if show_changes: with salt.utils.files.fopen(path, 'r') as fp_: path_content = salt.utils.data.decode_list(fp_.read().splitlines(True)) changes_diff = __utils__['stringutils.get_diff'](path_content, body) if __opts__['test'] is False: fh_ = None try: # Make sure we match the file mode from salt.utils.files.fopen if six.PY2 and salt.utils.platform.is_windows(): mode = 'wb' body = salt.utils.data.encode_list(body) else: mode = 'w' body = salt.utils.data.decode_list(body, to_str=True) fh_ = salt.utils.atomicfile.atomic_open(path, mode) fh_.writelines(body) finally: if fh_: fh_.close() return show_changes and changes_diff or changed def replace(path, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, backup='.bak', dry_run=False, search_only=False, show_changes=True, ignore_if_missing=False, preserve_inode=True, backslash_literal=False, ): ''' .. versionadded:: 0.17.0 Replace occurrences of a pattern in a file. If ``show_changes`` is ``True``, then a diff of what changed will be returned, otherwise a ``True`` will be returned when changes are made, and ``False`` when no changes are made. This is a pure Python implementation that wraps Python's :py:func:`~re.sub`. path Filesystem path to the file to be edited. If a symlink is specified, it will be resolved to its target. pattern A regular expression, to be matched using Python's :py:func:`~re.search`. repl The replacement text count : 0 Maximum number of pattern occurrences to be replaced. If count is a positive integer ``n``, only ``n`` occurrences will be replaced, otherwise all occurrences will be replaced. flags (list or int) A list of flags defined in the ``re`` module documentation from the Python standard library. Each list item should be a string that will correlate to the human-friendly flag name. E.g., ``['IGNORECASE', 'MULTILINE']``. Optionally, ``flags`` may be an int, with a value corresponding to the XOR (``|``) of all the desired flags. Defaults to 8 (which supports 'MULTILINE'). bufsize (int or str) How much of the file to buffer into memory at once. The default value ``1`` processes one line at a time. The special value ``file`` may be specified which will read the entire file into memory before processing. append_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True``, and pattern is not found, then the content will be appended to the file. prepend_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True`` and pattern is not found, then the content will be prepended to the file. not_found_content .. versionadded:: 2014.7.0 Content to use for append/prepend if not found. If None (default), uses ``repl``. Useful when ``repl`` uses references to group in pattern. backup : .bak The file extension to use for a backup of the file before editing. Set to ``False`` to skip making a backup. dry_run : False If set to ``True``, no changes will be made to the file, the function will just return the changes that would have been made (or a ``True``/``False`` value if ``show_changes`` is set to ``False``). search_only : False If set to true, this no changes will be performed on the file, and this function will simply return ``True`` if the pattern was matched, and ``False`` if not. show_changes : True If ``True``, return a diff of changes made. Otherwise, return ``True`` if changes were made, and ``False`` if not. .. note:: Using this option will store two copies of the file in memory (the original version and the edited version) in order to generate the diff. This may not normally be a concern, but could impact performance if used with large files. ignore_if_missing : False .. versionadded:: 2015.8.0 If set to ``True``, this function will simply return ``False`` if the file doesn't exist. Otherwise, an error will be thrown. preserve_inode : True .. versionadded:: 2015.8.0 Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). backslash_literal : False .. versionadded:: 2016.11.7 Interpret backslashes as literal backslashes for the repl and not escape characters. This will help when using append/prepend so that the backslashes are not interpreted for the repl on the second run of the state. If an equal sign (``=``) appears in an argument to a Salt command it is interpreted as a keyword argument in the format ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.replace /path/to/file pattern='=' repl=':' salt '*' file.replace /path/to/file pattern="bind-address\\s*=" repl='bind-address:' CLI Examples: .. code-block:: bash salt '*' file.replace /etc/httpd/httpd.conf pattern='LogLevel warn' repl='LogLevel info' salt '*' file.replace /some/file pattern='before' repl='after' flags='[MULTILINE, IGNORECASE]' ''' symlink = False if is_link(path): symlink = True target_path = os.readlink(path) given_path = os.path.expanduser(path) path = os.path.realpath(os.path.expanduser(path)) if not os.path.exists(path): if ignore_if_missing: return False else: raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if search_only and (append_if_not_found or prepend_if_not_found): raise SaltInvocationError( 'search_only cannot be used with append/prepend_if_not_found' ) if append_if_not_found and prepend_if_not_found: raise SaltInvocationError( 'Only one of append and prepend_if_not_found is permitted' ) flags_num = _get_flags(flags) cpattern = re.compile(salt.utils.stringutils.to_bytes(pattern), flags_num) filesize = os.path.getsize(path) if bufsize == 'file': bufsize = filesize # Search the file; track if any changes have been made for the return val has_changes = False orig_file = [] # used for show_changes and change detection new_file = [] # used for show_changes and change detection if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Avoid TypeErrors by forcing repl to be bytearray related to mmap # Replacement text may contains integer: 123 for example repl = salt.utils.stringutils.to_bytes(six.text_type(repl)) if not_found_content: not_found_content = salt.utils.stringutils.to_bytes(not_found_content) found = False temp_file = None content = salt.utils.stringutils.to_unicode(not_found_content) \ if not_found_content and (prepend_if_not_found or append_if_not_found) \ else salt.utils.stringutils.to_unicode(repl) try: # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes r_data = None # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: try: # mmap throws a ValueError if the file is empty. r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) except (ValueError, mmap.error): # size of file in /proc is 0, but contains data r_data = salt.utils.stringutils.to_bytes("".join(r_file)) if search_only: # Just search; bail as early as a match is found if re.search(cpattern, r_data): return True # `with` block handles file closure else: return False else: result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) # found anything? (even if no change) if nrepl > 0: found = True # Identity check the potential change has_changes = True if pattern != repl else has_changes if prepend_if_not_found or append_if_not_found: # Search for content, to avoid pre/appending the # content if it was pre/appended in a previous run. if re.search(salt.utils.stringutils.to_bytes('^{0}($|(?=\r\n))'.format(re.escape(content))), r_data, flags=flags_num): # Content was found, so set found. found = True orig_file = r_data.read(filesize).splitlines(True) \ if isinstance(r_data, mmap.mmap) \ else r_data.splitlines(True) new_file = result.splitlines(True) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() if has_changes and not dry_run: # Write the replacement text in this block. try: # Create a copy to read from and to use as a backup later temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) r_data = None try: # Open the file in write mode with salt.utils.files.fopen(path, mode='w', buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='r', buffering=bufsize) as r_file: r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) try: w_file.write(salt.utils.stringutils.to_str(result)) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if not found and (append_if_not_found or prepend_if_not_found): if not_found_content is None: not_found_content = repl if prepend_if_not_found: new_file.insert(0, not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) else: # append_if_not_found # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(salt.utils.stringutils.to_bytes(os.linesep)): new_file[-1] += salt.utils.stringutils.to_bytes(os.linesep) new_file.append(not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) has_changes = True if not dry_run: try: # Create a copy to read from and for later use as a backup temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line)) finally: fh_.close() if backup and has_changes and not dry_run: # keep the backup only if it was requested # and only if there were any changes backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) if symlink: symlink_backup = '{0}{1}'.format(given_path, backup) target_backup = '{0}{1}'.format(target_path, backup) # Always clobber any existing symlink backup # to match the behaviour of the 'backup' option try: os.symlink(target_backup, symlink_backup) except OSError: os.remove(symlink_backup) os.symlink(target_backup, symlink_backup) except Exception: raise CommandExecutionError( "Unable create backup symlink '{0}'. " "Target was '{1}'. " "Exception: {2}".format(symlink_backup, target_backup, exc) ) elif temp_file: try: os.remove(temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to delete temp file '{0}'. " "Exception: {1}".format(temp_file, exc) ) if not dry_run and not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) differences = __utils__['stringutils.get_diff'](orig_file, new_file) if show_changes: return differences # We may have found a regex line match but don't need to change the line # (for situations where the pattern also matches the repl). Revert the # has_changes flag to False if the final result is unchanged. if not differences: has_changes = False return has_changes def blockreplace(path, marker_start='#-- start managed zone --', marker_end='#-- end managed zone --', content='', append_if_not_found=False, prepend_if_not_found=False, backup='.bak', dry_run=False, show_changes=True, append_newline=False, insert_before_match=None, insert_after_match=None): ''' .. versionadded:: 2014.1.0 Replace content of a text block in a file, delimited by line markers A block of content delimited by comments can help you manage several lines entries without worrying about old entries removal. .. note:: This function will store two copies of the file in-memory (the original version and the edited version) in order to detect changes and only edit the targeted file if necessary. path Filesystem path to the file to be edited marker_start The line content identifying a line as the start of the content block. Note that the whole line containing this marker will be considered, so whitespace or extra content before or after the marker is included in final output marker_end The line content identifying the end of the content block. As of versions 2017.7.5 and 2018.3.1, everything up to the text matching the marker will be replaced, so it's important to ensure that your marker includes the beginning of the text you wish to replace. content The content to be used between the two lines identified by marker_start and marker_stop. append_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be appended to the file. prepend_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be prepended to the file. insert_before_match If markers are not found, this parameter can be set to a regex which will insert the block before the first found occurrence in the file. .. versionadded:: Neon insert_after_match If markers are not found, this parameter can be set to a regex which will insert the block after the first found occurrence in the file. .. versionadded:: Neon backup The file extension to use for a backup of the file if any edit is made. Set to ``False`` to skip making a backup. dry_run : False If ``True``, do not make any edits to the file and simply return the changes that *would* be made. show_changes : True Controls how changes are presented. If ``True``, this function will return a unified diff of the changes made. If False, then it will return a boolean (``True`` if any changes were made, otherwise ``False``). append_newline : False Controls whether or not a newline is appended to the content block. If the value of this argument is ``True`` then a newline will be added to the content block. If it is ``False``, then a newline will *not* be added to the content block. If it is ``None`` then a newline will only be added to the content block if it does not already end in a newline. .. versionadded:: 2016.3.4 .. versionchanged:: 2017.7.5,2018.3.1 New behavior added when value is ``None``. .. versionchanged:: 2019.2.0 The default value of this argument will change to ``None`` to match the behavior of the :py:func:`file.blockreplace state <salt.states.file.blockreplace>` CLI Example: .. code-block:: bash salt '*' file.blockreplace /etc/hosts '#-- start managed zone foobar : DO NOT EDIT --' \\ '#-- end managed zone foobar --' $'10.0.1.1 foo.foobar\\n10.0.1.2 bar.foobar' True ''' exclusive_params = [append_if_not_found, prepend_if_not_found, bool(insert_before_match), bool(insert_after_match)] if sum(exclusive_params) > 1: raise SaltInvocationError( 'Only one of append_if_not_found, prepend_if_not_found,' ' insert_before_match, and insert_after_match is permitted' ) path = os.path.expanduser(path) if not os.path.exists(path): raise SaltInvocationError('File not found: {0}'.format(path)) try: file_encoding = __utils__['files.get_encoding'](path) except CommandExecutionError: file_encoding = None if __utils__['files.is_binary'](path): if not file_encoding: raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if insert_before_match or insert_after_match: if insert_before_match: if not isinstance(insert_before_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_before_match parameter.' ) elif insert_after_match: if not isinstance(insert_after_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_after_match parameter.' ) if append_newline is None and not content.endswith((os.linesep, '\n')): append_newline = True # Split the content into a list of lines, removing newline characters. To # ensure that we handle both Windows and POSIX newlines, first split on # Windows newlines, and then split on POSIX newlines. split_content = [] for win_line in content.split('\r\n'): for content_line in win_line.split('\n'): split_content.append(content_line) line_count = len(split_content) has_changes = False orig_file = [] new_file = [] in_block = False block_found = False linesep = None def _add_content(linesep, lines=None, include_marker_start=True, end_line=None): if lines is None: lines = [] include_marker_start = True if end_line is None: end_line = marker_end end_line = end_line.rstrip('\r\n') + linesep if include_marker_start: lines.append(marker_start + linesep) if split_content: for index, content_line in enumerate(split_content, 1): if index != line_count: lines.append(content_line + linesep) else: # We're on the last line of the content block if append_newline: lines.append(content_line + linesep) lines.append(end_line) else: lines.append(content_line + end_line) else: lines.append(end_line) return lines # We do not use in-place editing to avoid file attrs modifications when # no changes are required and to avoid any file access on a partially # written file. try: fi_file = io.open(path, mode='r', encoding=file_encoding, newline='') for line in fi_file: write_line_to_new_file = True if linesep is None: # Auto-detect line separator if line.endswith('\r\n'): linesep = '\r\n' elif line.endswith('\n'): linesep = '\n' else: # No newline(s) in file, fall back to system's linesep linesep = os.linesep if marker_start in line: # We've entered the content block in_block = True else: if in_block: # We're not going to write the lines from the old file to # the new file until we have exited the block. write_line_to_new_file = False marker_end_pos = line.find(marker_end) if marker_end_pos != -1: # End of block detected in_block = False # We've found and exited the block block_found = True _add_content(linesep, lines=new_file, include_marker_start=False, end_line=line[marker_end_pos:]) # Save the line from the original file orig_file.append(line) if write_line_to_new_file: new_file.append(line) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read from {0}: {1}'.format(path, exc) ) finally: if linesep is None: # If the file was empty, we will not have set linesep yet. Assume # the system's line separator. This is needed for when we # prepend/append later on. linesep = os.linesep try: fi_file.close() except Exception: pass if in_block: # unterminated block => bad, always fail raise CommandExecutionError( 'Unterminated marked block. End of file reached before marker_end.' ) if not block_found: if prepend_if_not_found: # add the markers and content at the beginning of file prepended_content = _add_content(linesep) prepended_content.extend(new_file) new_file = prepended_content block_found = True elif append_if_not_found: # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(linesep): new_file[-1] += linesep # add the markers and content at the end of file _add_content(linesep, lines=new_file) block_found = True elif insert_before_match or insert_after_match: match_regex = insert_before_match or insert_after_match match_idx = [i for i, item in enumerate(orig_file) if re.search(match_regex, item)] if match_idx: match_idx = match_idx[0] for line in _add_content(linesep): if insert_after_match: match_idx += 1 new_file.insert(match_idx, line) if insert_before_match: match_idx += 1 block_found = True if not block_found: raise CommandExecutionError( 'Cannot edit marked block. Markers were not found in file.' ) diff = __utils__['stringutils.get_diff'](orig_file, new_file) has_changes = diff is not '' if has_changes and not dry_run: # changes detected # backup file attrs perms = {} perms['user'] = get_user(path) perms['group'] = get_group(path) perms['mode'] = salt.utils.files.normalize_mode(get_mode(path)) # backup old content if backup is not False: backup_path = '{0}{1}'.format(path, backup) shutil.copy2(path, backup_path) # copy2 does not preserve ownership check_perms(backup_path, None, perms['user'], perms['group'], perms['mode']) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line, encoding=file_encoding)) finally: fh_.close() # this may have overwritten file attrs check_perms(path, None, perms['user'], perms['group'], perms['mode']) if show_changes: return diff return has_changes def search(path, pattern, flags=8, bufsize=1, ignore_if_missing=False, multiline=False ): ''' .. versionadded:: 0.17.0 Search for occurrences of a pattern in a file Except for multiline, params are identical to :py:func:`~salt.modules.file.replace`. multiline If true, inserts 'MULTILINE' into ``flags`` and sets ``bufsize`` to 'file'. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' file.search /etc/crontab 'mymaintenance.sh' ''' if multiline: flags = _add_flags(flags, 'MULTILINE') bufsize = 'file' # This function wraps file.replace on purpose in order to enforce # consistent usage, compatible regex's, expected behavior, *and* bugs. :) # Any enhancements or fixes to one should affect the other. return replace(path, pattern, '', flags=flags, bufsize=bufsize, dry_run=True, search_only=True, show_changes=False, ignore_if_missing=ignore_if_missing) def patch(originalfile, patchfile, options='', dry_run=False): ''' .. versionadded:: 0.10.4 Apply a patch to a file or directory. Equivalent to: .. code-block:: bash patch <options> -i <patchfile> <originalfile> Or, when a directory is patched: .. code-block:: bash patch <options> -i <patchfile> -d <originalfile> -p0 originalfile The full path to the file or directory to be patched patchfile A patch file to apply to ``originalfile`` options Options to pass to patch. CLI Example: .. code-block:: bash salt '*' file.patch /opt/file.txt /tmp/file.txt.patch ''' patchpath = salt.utils.path.which('patch') if not patchpath: raise CommandExecutionError( 'patch executable not found. Is the distribution\'s patch ' 'package installed?' ) cmd = [patchpath] cmd.extend(salt.utils.args.shlex_split(options)) if dry_run: if __grains__['kernel'] in ('FreeBSD', 'OpenBSD'): cmd.append('-C') else: cmd.append('--dry-run') # this argument prevents interactive prompts when the patch fails to apply. # the exit code will still be greater than 0 if that is the case. if '-N' not in cmd and '--forward' not in cmd: cmd.append('--forward') has_rejectfile_option = False for option in cmd: if option == '-r' or option.startswith('-r ') \ or option.startswith('--reject-file'): has_rejectfile_option = True break # by default, patch will write rejected patch files to <filename>.rej. # this option prevents that. if not has_rejectfile_option: cmd.append('--reject-file=-') cmd.extend(['-i', patchfile]) if os.path.isdir(originalfile): cmd.extend(['-d', originalfile]) has_strip_option = False for option in cmd: if option.startswith('-p') or option.startswith('--strip='): has_strip_option = True break if not has_strip_option: cmd.append('--strip=0') else: cmd.append(originalfile) return __salt__['cmd.run_all'](cmd, python_shell=False) def contains(path, text): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the file at ``path`` contains ``text`` CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False stripped_text = six.text_type(text).strip() try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if stripped_text in chunk: return True return False except (IOError, OSError): return False def contains_regex(path, regex, lchar=''): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the given regular expression matches on any line in the text of a given file. If the lchar argument (leading char) is specified, it will strip `lchar` from the left side of each line before trying to match CLI Example: .. code-block:: bash salt '*' file.contains_regex /etc/crontab ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.files.fopen(path, 'r') as target: for line in target: line = salt.utils.stringutils.to_unicode(line) if lchar: line = line.lstrip(lchar) if re.search(regex, line): return True return False except (IOError, OSError): return False def contains_glob(path, glob_expr): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the given glob matches a string in the named file CLI Example: .. code-block:: bash salt '*' file.contains_glob /etc/foobar '*cheese*' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if fnmatch.fnmatch(chunk, glob_expr): return True return False except (IOError, OSError): return False def append(path, *args, **kwargs): ''' .. versionadded:: 0.9.5 Append text to the end of a file path path to file `*args` strings to append to file CLI Example: .. code-block:: bash salt '*' file.append /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.append /etc/motd args='cheese=spam' salt '*' file.append /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) # Largely inspired by Fabric's contrib.files.append() if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] # Make sure we have a newline at the end of the file. Do this in binary # mode so SEEK_END with nonzero offset will work. with salt.utils.files.fopen(path, 'rb+') as ofile: linesep = salt.utils.stringutils.to_bytes(os.linesep) try: ofile.seek(-len(linesep), os.SEEK_END) except IOError as exc: if exc.errno in (errno.EINVAL, errno.ESPIPE): # Empty file, simply append lines at the beginning of the file pass else: raise else: if ofile.read(len(linesep)) != linesep: ofile.seek(0, os.SEEK_END) ofile.write(linesep) # Append lines in text mode with salt.utils.files.fopen(path, 'a') as ofile: for new_line in args: ofile.write( salt.utils.stringutils.to_str( '{0}{1}'.format(new_line, os.linesep) ) ) return 'Wrote {0} lines to "{1}"'.format(len(args), path) def prepend(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Prepend text to the beginning of a file path path to file `*args` strings to prepend to the file CLI Example: .. code-block:: bash salt '*' file.prepend /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.prepend /etc/motd args='cheese=spam' salt '*' file.prepend /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] try: with salt.utils.files.fopen(path) as fhr: contents = [salt.utils.stringutils.to_unicode(line) for line in fhr.readlines()] except IOError: contents = [] preface = [] for line in args: preface.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, 'w') as ofile: contents = preface + contents ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Prepended {0} lines to "{1}"'.format(len(args), path) def write(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Write text to a file, overwriting any existing contents. path path to file `*args` strings to write to the file CLI Example: .. code-block:: bash salt '*' file.write /etc/motd \\ "With all thine offerings thou shalt offer salt." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.write /etc/motd args='cheese=spam' salt '*' file.write /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] contents = [] for line in args: contents.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, "w") as ofile: ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Wrote {0} lines to "{1}"'.format(len(contents), path) def touch(name, atime=None, mtime=None): ''' .. versionadded:: 0.9.5 Just like the ``touch`` command, create a file if it doesn't exist or simply update the atime and mtime if it already does. atime: Access time in Unix epoch time. Set it to 0 to set atime of the file with Unix date of birth. If this parameter isn't set, atime will be set with current time. mtime: Last modification in Unix epoch time. Set it to 0 to set mtime of the file with Unix date of birth. If this parameter isn't set, mtime will be set with current time. CLI Example: .. code-block:: bash salt '*' file.touch /var/log/emptyfile ''' name = os.path.expanduser(name) if atime and atime.isdigit(): atime = int(atime) if mtime and mtime.isdigit(): mtime = int(mtime) try: if not os.path.exists(name): with salt.utils.files.fopen(name, 'a'): pass if atime is None and mtime is None: times = None elif mtime is None and atime is not None: times = (atime, time.time()) elif atime is None and mtime is not None: times = (time.time(), mtime) else: times = (atime, mtime) os.utime(name, times) except TypeError: raise SaltInvocationError('atime and mtime must be integers') except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return os.path.exists(name) def tail(path, lines): ''' .. versionadded:: Neon Read the last n lines from a file path path to file lines number of lines to read CLI Example: .. code-block:: bash salt '*' file.tail /path/to/file 10 ''' path = os.path.expanduser(path) lines_found = [] buffer_size = 4098 if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot tail a binary file: {0}'.format(path)) try: lines = int(lines) except ValueError: raise SaltInvocationError('file.tail: \'lines\' value must be an integer') try: with salt.utils.fopen(path) as tail_fh: blk_cnt = 1 size = os.stat(path).st_size if size > buffer_size: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size), os.linesep) for i in range(lines): while len(data) == 1 and ((blk_cnt * buffer_size) < size): blk_cnt += 1 line = data[0] try: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size) + line, os.linesep) except IOError: tail_fh.seek(0) data = string.split(tail_fh.read(size - (buffer_size * (blk_cnt - 1))) + line, os.linesep) line = data[-1] data.pop() lines_found.append(line) return lines_found[-lines:] except (OSError, IOError): raise CommandExecutionError('Could not tail \'{0}\''.format(path)) def seek_read(path, size, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and read it path path to file seek amount to read at once offset offset to start into the file CLI Example: .. code-block:: bash salt '*' file.seek_read /path/to/file 4096 0 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_RDONLY) try: os.lseek(seek_fh, int(offset), 0) data = os.read(seek_fh, int(size)) finally: os.close(seek_fh) return data def seek_write(path, data, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and write to it path path to file data data to write to file offset position in file to start writing CLI Example: .. code-block:: bash salt '*' file.seek_write /path/to/file 'some data' 4096 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_WRONLY) try: os.lseek(seek_fh, int(offset), 0) ret = os.write(seek_fh, data) os.fsync(seek_fh) finally: os.close(seek_fh) return ret def truncate(path, length): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and delete everything after that point path path to file length offset into file to truncate CLI Example: .. code-block:: bash salt '*' file.truncate /path/to/file 512 ''' path = os.path.expanduser(path) with salt.utils.files.fopen(path, 'rb+') as seek_fh: seek_fh.truncate(int(length)) def link(src, path): ''' .. versionadded:: 2014.1.0 Create a hard link to a file CLI Example: .. code-block:: bash salt '*' file.link /path/to/file /path/to/link ''' src = os.path.expanduser(src) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.link(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def is_link(path): ''' Check if the path is a symbolic link CLI Example: .. code-block:: bash salt '*' file.is_link /path/to/link ''' # This function exists because os.path.islink does not support Windows, # therefore a custom function will need to be called. This function # therefore helps API consistency by providing a single function to call for # both operating systems. return os.path.islink(os.path.expanduser(path)) def symlink(src, path): ''' Create a symbolic link (symlink, soft link) to a file CLI Example: .. code-block:: bash salt '*' file.symlink /path/to/file /path/to/link ''' path = os.path.expanduser(path) try: if os.path.normpath(os.readlink(path)) == os.path.normpath(src): log.debug('link already in correct state: %s -> %s', path, src) return True except OSError: pass if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: os.symlink(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def rename(src, dst): ''' Rename a file or directory CLI Example: .. code-block:: bash salt '*' file.rename /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.rename(src, dst) return True except OSError: raise CommandExecutionError( 'Could not rename \'{0}\' to \'{1}\''.format(src, dst) ) return False def copy(src, dst, recurse=False, remove_existing=False): ''' Copy a file or directory from source to dst In order to copy a directory, the recurse flag is required, and will by default overwrite files in the destination with the same path, and retain all other existing files. (similar to cp -r on unix) remove_existing will remove all files in the target directory, and then copy files from the source. .. note:: The copy function accepts paths that are local to the Salt minion. This function does not support salt://, http://, or the other additional file paths that are supported by :mod:`states.file.managed <salt.states.file.managed>` and :mod:`states.file.recurse <salt.states.file.recurse>`. CLI Example: .. code-block:: bash salt '*' file.copy /path/to/src /path/to/dst salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True remove_existing=True ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') if not os.path.exists(src): raise CommandExecutionError('No such file or directory \'{0}\''.format(src)) if not salt.utils.platform.is_windows(): pre_user = get_user(src) pre_group = get_group(src) pre_mode = salt.utils.files.normalize_mode(get_mode(src)) try: if (os.path.exists(dst) and os.path.isdir(dst)) or os.path.isdir(src): if not recurse: raise SaltInvocationError( "Cannot copy overwriting a directory without recurse flag set to true!") if remove_existing: if os.path.exists(dst): shutil.rmtree(dst) shutil.copytree(src, dst) else: salt.utils.files.recursive_copy(src, dst) else: shutil.copyfile(src, dst) except OSError: raise CommandExecutionError( 'Could not copy \'{0}\' to \'{1}\''.format(src, dst) ) if not salt.utils.platform.is_windows(): check_perms(dst, None, pre_user, pre_group, pre_mode) return True def lstat(path): ''' .. versionadded:: 2014.1.0 Returns the lstat attributes for the given file or dir. Does not support symbolic links. CLI Example: .. code-block:: bash salt '*' file.lstat /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to file must be absolute.') try: lst = os.lstat(path) return dict((key, getattr(lst, key)) for key in ('st_atime', 'st_ctime', 'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid')) except Exception: return {} def access(path, mode): ''' .. versionadded:: 2014.1.0 Test whether the Salt process has the specified access to the file. One of the following modes must be specified: .. code-block::text f: Test the existence of the path r: Test the readability of the path w: Test the writability of the path x: Test whether the path can be executed CLI Example: .. code-block:: bash salt '*' file.access /path/to/file f salt '*' file.access /path/to/file x ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') modes = {'f': os.F_OK, 'r': os.R_OK, 'w': os.W_OK, 'x': os.X_OK} if mode in modes: return os.access(path, modes[mode]) elif mode in six.itervalues(modes): return os.access(path, mode) else: raise SaltInvocationError('Invalid mode specified.') def read(path, binary=False): ''' .. versionadded:: 2017.7.0 Return the content of the file. CLI Example: .. code-block:: bash salt '*' file.read /path/to/file ''' access_mode = 'r' if binary is True: access_mode += 'b' with salt.utils.files.fopen(path, access_mode) as file_obj: return salt.utils.stringutils.to_unicode(file_obj.read()) def readlink(path, canonicalize=False): ''' .. versionadded:: 2014.1.0 Return the path that a symlink points to If canonicalize is set to True, then it return the final target CLI Example: .. code-block:: bash salt '*' file.readlink /path/to/link ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') if not os.path.islink(path): raise SaltInvocationError('A valid link was not specified.') if canonicalize: return os.path.realpath(path) else: return os.readlink(path) def readdir(path): ''' .. versionadded:: 2014.1.0 Return a list containing the contents of a directory CLI Example: .. code-block:: bash salt '*' file.readdir /path/to/dir/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Dir path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') dirents = ['.', '..'] dirents.extend(os.listdir(path)) return dirents def statvfs(path): ''' .. versionadded:: 2014.1.0 Perform a statvfs call against the filesystem that the file resides on CLI Example: .. code-block:: bash salt '*' file.statvfs /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: stv = os.statvfs(path) return dict((key, getattr(stv, key)) for key in ('f_bavail', 'f_bfree', 'f_blocks', 'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag', 'f_frsize', 'f_namemax')) except (OSError, IOError): raise CommandExecutionError('Could not statvfs \'{0}\''.format(path)) return False def stats(path, hash_type=None, follow_symlinks=True): ''' Return a dict containing the stats for a given file CLI Example: .. code-block:: bash salt '*' file.stats /etc/passwd ''' path = os.path.expanduser(path) ret = {} if not os.path.exists(path): try: # Broken symlinks will return False for os.path.exists(), but still # have a uid and gid pstat = os.lstat(path) except OSError: # Not a broken symlink, just a nonexistent path # NOTE: The file.directory state checks the content of the error # message in this exception. Any changes made to the message for this # exception will reflect the file.directory state as well, and will # likely require changes there. raise CommandExecutionError('Path not found: {0}'.format(path)) else: if follow_symlinks: pstat = os.stat(path) else: pstat = os.lstat(path) ret['inode'] = pstat.st_ino ret['uid'] = pstat.st_uid ret['gid'] = pstat.st_gid ret['group'] = gid_to_group(pstat.st_gid) ret['user'] = uid_to_user(pstat.st_uid) ret['atime'] = pstat.st_atime ret['mtime'] = pstat.st_mtime ret['ctime'] = pstat.st_ctime ret['size'] = pstat.st_size ret['mode'] = six.text_type(oct(stat.S_IMODE(pstat.st_mode))) if hash_type: ret['sum'] = get_hash(path, hash_type) ret['type'] = 'file' if stat.S_ISDIR(pstat.st_mode): ret['type'] = 'dir' if stat.S_ISCHR(pstat.st_mode): ret['type'] = 'char' if stat.S_ISBLK(pstat.st_mode): ret['type'] = 'block' if stat.S_ISREG(pstat.st_mode): ret['type'] = 'file' if stat.S_ISLNK(pstat.st_mode): ret['type'] = 'link' if stat.S_ISFIFO(pstat.st_mode): ret['type'] = 'pipe' if stat.S_ISSOCK(pstat.st_mode): ret['type'] = 'socket' ret['target'] = os.path.realpath(path) return ret def rmdir(path): ''' .. versionadded:: 2014.1.0 Remove the specified directory. Fails if a directory is not empty. CLI Example: .. code-block:: bash salt '*' file.rmdir /tmp/foo/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') try: os.rmdir(path) return True except OSError as exc: return exc.strerror def remove(path, **kwargs): ''' Remove the named file. If a directory is supplied, it will be recursively deleted. CLI Example: .. code-block:: bash salt '*' file.remove /tmp/foo ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute: {0}'.format(path)) try: if os.path.isfile(path) or os.path.islink(path): os.remove(path) return True elif os.path.isdir(path): shutil.rmtree(path) return True except (OSError, IOError) as exc: raise CommandExecutionError( 'Could not remove \'{0}\': {1}'.format(path, exc) ) return False def directory_exists(path): ''' Tests to see if path is a valid directory. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.directory_exists /etc ''' return os.path.isdir(os.path.expanduser(path)) def file_exists(path): ''' Tests to see if path is a valid file. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.file_exists /etc/passwd ''' return os.path.isfile(os.path.expanduser(path)) def path_exists_glob(path): ''' Tests to see if path after expansion is a valid path (file or directory). Expansion allows usage of ? * and character ranges []. Tilde expansion is not supported. Returns True/False. .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' file.path_exists_glob /etc/pam*/pass* ''' return True if glob.glob(os.path.expanduser(path)) else False def restorecon(path, recursive=False): ''' Reset the SELinux context on a given path CLI Example: .. code-block:: bash salt '*' file.restorecon /home/user/.ssh/authorized_keys ''' if recursive: cmd = ['restorecon', '-FR', path] else: cmd = ['restorecon', '-F', path] return not __salt__['cmd.retcode'](cmd, python_shell=False) def get_selinux_context(path): ''' Get an SELinux context from a given path CLI Example: .. code-block:: bash salt '*' file.get_selinux_context /etc/hosts ''' out = __salt__['cmd.run'](['ls', '-Z', path], python_shell=False) try: ret = re.search(r'\w+:\w+:\w+:\w+', out).group(0) except AttributeError: ret = ( 'No selinux context information is available for {0}'.format(path) ) return ret def set_selinux_context(path, user=None, role=None, type=None, # pylint: disable=W0622 range=None, # pylint: disable=W0622 persist=False): ''' .. versionchanged:: Neon Added persist option Set a specific SELinux label on a given path CLI Example: .. code-block:: bash salt '*' file.set_selinux_context path <user> <role> <type> <range> salt '*' file.set_selinux_context /etc/yum.repos.d/epel.repo system_u object_r system_conf_t s0 ''' if not any((user, role, type, range)): return False if persist: fcontext_result = __salt__['selinux.fcontext_add_policy'](path, sel_type=type, sel_user=user, sel_level=range) if fcontext_result.get('retcode', None) is not 0: # Problem setting fcontext policy raise CommandExecutionError( 'Problem setting fcontext: {0}'.format(fcontext_result) ) cmd = ['chcon'] if user: cmd.extend(['-u', user]) if role: cmd.extend(['-r', role]) if type: cmd.extend(['-t', type]) if range: cmd.extend(['-l', range]) cmd.append(path) ret = not __salt__['cmd.retcode'](cmd, python_shell=False) if ret: return get_selinux_context(path) else: return ret def source_list(source, source_hash, saltenv): ''' Check the source list and return the source to use CLI Example: .. code-block:: bash salt '*' file.source_list salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' base ''' contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv) if contextkey in __context__: return __context__[contextkey] # get the master file list if isinstance(source, list): mfiles = [(f, saltenv) for f in __salt__['cp.list_master'](saltenv)] mdirs = [(d, saltenv) for d in __salt__['cp.list_master_dirs'](saltenv)] for single in source: if isinstance(single, dict): single = next(iter(single)) path, senv = salt.utils.url.parse(single) if senv: mfiles += [(f, senv) for f in __salt__['cp.list_master'](senv)] mdirs += [(d, senv) for d in __salt__['cp.list_master_dirs'](senv)] ret = None for single in source: if isinstance(single, dict): # check the proto, if it is http or ftp then download the file # to check, if it is salt then check the master list # if it is a local file, check if the file exists if len(single) != 1: continue single_src = next(iter(single)) single_hash = single[single_src] if single[single_src] else source_hash urlparsed_single_src = _urlparse(single_src) # Fix this for Windows if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_single_src.scheme.lower() in string.ascii_lowercase: urlparsed_single_src = _urlparse('file://' + single_src) proto = urlparsed_single_src.scheme if proto == 'salt': path, senv = salt.utils.url.parse(single_src) if not senv: senv = saltenv if (path, saltenv) in mfiles or (path, saltenv) in mdirs: ret = (single_src, single_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single_src, single_hash) break elif proto == 'file' and ( os.path.exists(urlparsed_single_src.netloc) or os.path.exists(urlparsed_single_src.path) or os.path.exists(os.path.join( urlparsed_single_src.netloc, urlparsed_single_src.path))): ret = (single_src, single_hash) break elif single_src.startswith(os.sep) and os.path.exists(single_src): ret = (single_src, single_hash) break elif isinstance(single, six.string_types): path, senv = salt.utils.url.parse(single) if not senv: senv = saltenv if (path, senv) in mfiles or (path, senv) in mdirs: ret = (single, source_hash) break urlparsed_src = _urlparse(single) if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_src.scheme.lower() in string.ascii_lowercase: urlparsed_src = _urlparse('file://' + single) proto = urlparsed_src.scheme if proto == 'file' and ( os.path.exists(urlparsed_src.netloc) or os.path.exists(urlparsed_src.path) or os.path.exists(os.path.join( urlparsed_src.netloc, urlparsed_src.path))): ret = (single, source_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single, source_hash) break elif single.startswith(os.sep) and os.path.exists(single): ret = (single, source_hash) break if ret is None: # None of the list items matched raise CommandExecutionError( 'none of the specified sources were found' ) else: ret = (source, source_hash) __context__[contextkey] = ret return ret def apply_template_on_contents( contents, template, context, defaults, saltenv): ''' Return the contents after applying the templating engine contents template string template template format context Overrides default context variables passed to the template. defaults Default context passed to the template. CLI Example: .. code-block:: bash salt '*' file.apply_template_on_contents \\ contents='This is a {{ template }} string.' \\ template=jinja \\ "context={}" "defaults={'template': 'cool'}" \\ saltenv=base ''' if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) # Apply templating contents = salt.utils.templates.TEMPLATE_REGISTRY[template]( contents, from_str=True, to_str=True, context=context_dict, saltenv=saltenv, grains=__opts__['grains'], pillar=__pillar__, salt=__salt__, opts=__opts__)['data'] if six.PY2: contents = contents.encode('utf-8') elif six.PY3 and isinstance(contents, bytes): # bytes -> str contents = contents.decode('utf-8') else: ret = {} ret['result'] = False ret['comment'] = ('Specified template format {0} is not supported' ).format(template) return ret return contents def get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify=False, **kwargs): ''' Return the managed file data for file.managed name location where the file lives on the server template template format source managed source file source_hash hash of the source file source_hash_name When ``source_hash`` refers to a remote file, this specifies the filename to look for in that file. .. versionadded:: 2016.3.5 user Owner of file group Group owner of file mode Permissions of file attrs Attributes of file .. versionadded:: 2018.3.0 context Variables to add to the template context defaults Default values of for context_dict skip_verify If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' file.get_managed /etc/httpd/conf.d/httpd.conf jinja salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' None root root '755' base None None ''' # Copy the file to the minion and templatize it sfn = '' source_sum = {} def _get_local_file_source_sum(path): ''' DRY helper for getting the source_sum value from a locally cached path. ''' return {'hsum': get_hash(path, form='sha256'), 'hash_type': 'sha256'} # If we have a source defined, let's figure out what the hash is if source: urlparsed_source = _urlparse(source) if urlparsed_source.scheme in salt.utils.files.VALID_PROTOS: parsed_scheme = urlparsed_source.scheme else: parsed_scheme = '' parsed_path = os.path.join( urlparsed_source.netloc, urlparsed_source.path).rstrip(os.sep) unix_local_source = parsed_scheme in ('file', '') if parsed_scheme == '': parsed_path = sfn = source if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg elif parsed_scheme == 'file': sfn = parsed_path if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg if parsed_scheme and parsed_scheme.lower() in string.ascii_lowercase: parsed_path = ':'.join([parsed_scheme, parsed_path]) parsed_scheme = 'file' if parsed_scheme == 'salt': source_sum = __salt__['cp.hash_file'](source, saltenv) if not source_sum: return '', {}, 'Source file {0} not found in saltenv \'{1}\''.format(source, saltenv) elif not source_hash and unix_local_source: source_sum = _get_local_file_source_sum(parsed_path) elif not source_hash and source.startswith(os.sep): # This should happen on Windows source_sum = _get_local_file_source_sum(source) else: if not skip_verify: if source_hash: try: source_sum = get_source_sum(name, source, source_hash, source_hash_name, saltenv) except CommandExecutionError as exc: return '', {}, exc.strerror else: msg = ( 'Unable to verify upstream hash of source file {0}, ' 'please set source_hash or set skip_verify to True' .format(salt.utils.url.redact_http_basic_auth(source)) ) return '', {}, msg if source and (template or parsed_scheme in salt.utils.files.REMOTE_PROTOS): # Check if we have the template or remote file cached cache_refetch = False cached_dest = __salt__['cp.is_cached'](source, saltenv) if cached_dest and (source_hash or skip_verify): htype = source_sum.get('hash_type', 'sha256') cached_sum = get_hash(cached_dest, form=htype) if skip_verify: # prev: if skip_verify or cached_sum == source_sum['hsum']: # but `cached_sum == source_sum['hsum']` is elliptical as prev if sfn = cached_dest source_sum = {'hsum': cached_sum, 'hash_type': htype} elif cached_sum != source_sum.get('hsum', __opts__['hash_type']): cache_refetch = True else: sfn = cached_dest # If we didn't have the template or remote file, or the file has been # updated and the cache has to be refreshed, download the file. if not sfn or cache_refetch: try: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum.get('hsum')) except Exception as exc: # A 404 or other error code may raise an exception, catch it # and return a comment that will fail the calling state. _source = salt.utils.url.redact_http_basic_auth(source) return '', {}, 'Failed to cache {0}: {1}'.format(_source, exc) # If cache failed, sfn will be False, so do a truth check on sfn first # as invoking os.path.exists() on a bool raises a TypeError. if not sfn or not os.path.exists(sfn): _source = salt.utils.url.redact_http_basic_auth(source) return sfn, {}, 'Source file \'{0}\' not found'.format(_source) if sfn == name: raise SaltInvocationError( 'Source file cannot be the same as destination' ) if template: if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, name=name, source=source, user=user, group=group, mode=mode, attrs=attrs, saltenv=saltenv, context=context_dict, salt=__salt__, pillar=__pillar__, grains=__opts__['grains'], opts=__opts__, **kwargs) else: return sfn, {}, ('Specified template format {0} is not supported' ).format(template) if data['result']: sfn = data['data'] hsum = get_hash(sfn, form='sha256') source_sum = {'hash_type': 'sha256', 'hsum': hsum} else: __clean_tmp(sfn) return sfn, {}, data['data'] return sfn, source_sum, '' def extract_hash(hash_fn, hash_type='sha256', file_name='', source='', source_hash_name=None): ''' .. versionchanged:: 2016.3.5 Prior to this version, only the ``file_name`` argument was considered for filename matches in the hash file. This would be problematic for cases in which the user was relying on a remote checksum file that they do not control, and they wished to use a different name for that file on the minion from the filename on the remote server (and in the checksum file). For example, managing ``/tmp/myfile.tar.gz`` when the remote file was at ``https://mydomain.tld/different_name.tar.gz``. The :py:func:`file.managed <salt.states.file.managed>` state now also passes this function the source URI as well as the ``source_hash_name`` (if specified). In cases where ``source_hash_name`` is specified, it takes precedence over both the ``file_name`` and ``source``. When it is not specified, ``file_name`` takes precedence over ``source``. This allows for better capability for matching hashes. .. versionchanged:: 2016.11.0 File name and source URI matches are no longer disregarded when ``source_hash_name`` is specified. They will be used as fallback matches if there is no match to the ``source_hash_name`` value. This routine is called from the :mod:`file.managed <salt.states.file.managed>` state to pull a hash from a remote file. Regular expressions are used line by line on the ``source_hash`` file, to find a potential candidate of the indicated hash type. This avoids many problems of arbitrary file layout rules. It specifically permits pulling hash codes from debian ``*.dsc`` files. If no exact match of a hash and filename are found, then the first hash found (if any) will be returned. If no hashes at all are found, then ``None`` will be returned. For example: .. code-block:: yaml openerp_7.0-latest-1.tar.gz: file.managed: - name: /tmp/openerp_7.0-20121227-075624-1_all.deb - source: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.tar.gz - source_hash: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.dsc CLI Example: .. code-block:: bash salt '*' file.extract_hash /path/to/hash/file sha512 /etc/foo ''' hash_len = HASHES.get(hash_type) if hash_len is None: if hash_type: log.warning( 'file.extract_hash: Unsupported hash_type \'%s\', falling ' 'back to matching any supported hash_type', hash_type ) hash_type = '' hash_len_expr = '{0},{1}'.format(min(HASHES_REVMAP), max(HASHES_REVMAP)) else: hash_len_expr = six.text_type(hash_len) filename_separators = string.whitespace + r'\/' if source_hash_name: if not isinstance(source_hash_name, six.string_types): source_hash_name = six.text_type(source_hash_name) source_hash_name_idx = (len(source_hash_name) + 1) * -1 log.debug( 'file.extract_hash: Extracting %s hash for file matching ' 'source_hash_name \'%s\'', 'any supported' if not hash_type else hash_type, source_hash_name ) if file_name: if not isinstance(file_name, six.string_types): file_name = six.text_type(file_name) file_name_basename = os.path.basename(file_name) file_name_idx = (len(file_name_basename) + 1) * -1 if source: if not isinstance(source, six.string_types): source = six.text_type(source) urlparsed_source = _urlparse(source) source_basename = os.path.basename( urlparsed_source.path or urlparsed_source.netloc ) source_idx = (len(source_basename) + 1) * -1 basename_searches = [x for x in (file_name, source) if x] if basename_searches: log.debug( 'file.extract_hash: %s %s hash for file matching%s: %s', 'If no source_hash_name match found, will extract' if source_hash_name else 'Extracting', 'any supported' if not hash_type else hash_type, '' if len(basename_searches) == 1 else ' either of the following', ', '.join(basename_searches) ) partial = None found = {} with salt.utils.files.fopen(hash_fn, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line.strip()) hash_re = r'(?i)(?<![a-z0-9])([a-f0-9]{' + hash_len_expr + '})(?![a-z0-9])' hash_match = re.search(hash_re, line) matched = None if hash_match: matched_hsum = hash_match.group(1) if matched_hsum is not None: matched_type = HASHES_REVMAP.get(len(matched_hsum)) if matched_type is None: # There was a match, but it's not of the correct length # to match one of the supported hash types. matched = None else: matched = {'hsum': matched_hsum, 'hash_type': matched_type} if matched is None: log.debug( 'file.extract_hash: In line \'%s\', no %shash found', line, '' if not hash_type else hash_type + ' ' ) continue if partial is None: partial = matched def _add_to_matches(found, line, match_type, value, matched): log.debug( 'file.extract_hash: Line \'%s\' matches %s \'%s\'', line, match_type, value ) found.setdefault(match_type, []).append(matched) hash_matched = False if source_hash_name: if line.endswith(source_hash_name): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[source_hash_name_idx] in string.whitespace: _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source_hash_name) + r'\s+', line): _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True if file_name: if line.endswith(file_name_basename): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[file_name_idx] in filename_separators: _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(file_name) + r'\s+', line): _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True if source: if line.endswith(source_basename): # Same as above, we can't just do an rsplit here. try: if line[source_idx] in filename_separators: _add_to_matches(found, line, 'source', source, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source) + r'\s+', line): _add_to_matches(found, line, 'source', source, matched) hash_matched = True if not hash_matched: log.debug( 'file.extract_hash: Line \'%s\' contains %s hash ' '\'%s\', but line did not meet the search criteria', line, matched['hash_type'], matched['hsum'] ) for found_type, found_str in (('source_hash_name', source_hash_name), ('file_name', file_name), ('source', source)): if found_type in found: if len(found[found_type]) > 1: log.debug( 'file.extract_hash: Multiple %s matches for %s: %s', found_type, found_str, ', '.join( ['{0} ({1})'.format(x['hsum'], x['hash_type']) for x in found[found_type]] ) ) ret = found[found_type][0] log.debug( 'file.extract_hash: Returning %s hash \'%s\' as a match of %s', ret['hash_type'], ret['hsum'], found_str ) return ret if partial: log.debug( 'file.extract_hash: Returning the partially identified %s hash ' '\'%s\'', partial['hash_type'], partial['hsum'] ) return partial log.debug('file.extract_hash: No matches, returning None') return None def check_perms(name, ret, user, group, mode, attrs=None, follow_symlinks=False, seuser=None, serole=None, setype=None, serange=None): ''' .. versionchanged:: Neon Added selinux options Check the permissions on files, modify attributes and chown if needed. File attributes are only verified if lsattr(1) is installed. CLI Example: .. code-block:: bash salt '*' file.check_perms /etc/sudoers '{}' root root 400 ai .. versionchanged:: 2014.1.3 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': [], 'result': True} orig_comment = '' else: orig_comment = ret['comment'] ret['comment'] = [] # Check permissions perms = {} cur = stats(name, follow_symlinks=follow_symlinks) perms['luser'] = cur['user'] perms['lgroup'] = cur['group'] perms['lmode'] = salt.utils.files.normalize_mode(cur['mode']) is_dir = os.path.isdir(name) is_link = os.path.islink(name) if attrs is not None \ and not salt.utils.platform.is_windows() \ and not is_dir and not is_link: try: lattrs = lsattr(name) except SaltInvocationError: lattrs = None if lattrs is not None: # List attributes on file perms['lattrs'] = ''.join(lattrs.get(name, '')) # Remove attributes on file so changes can be enforced. if perms['lattrs']: chattr(name, operator='remove', attributes=perms['lattrs']) # user/group changes if needed, then check if it worked if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid(perms['luser']) ) or ( not salt.utils.platform.is_windows() and user != perms['luser'] ): perms['cuser'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid(perms['lgroup']) ) or ( not salt.utils.platform.is_windows() and group != perms['lgroup'] ): perms['cgroup'] = group if 'cuser' in perms or 'cgroup' in perms: if not __opts__['test']: if os.path.islink(name) and not follow_symlinks: chown_func = lchown else: chown_func = chown if user is None: user = perms['luser'] if group is None: group = perms['lgroup'] try: chown_func(name, user, group) # Python os.chown() does reset the suid and sgid, # that's why setting the right mode again is needed here. set_mode(name, mode) except OSError: ret['result'] = False if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid( get_user(name, follow_symlinks=follow_symlinks)) and user != '' ) or ( not salt.utils.platform.is_windows() and user != get_user(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['user'] = user else: ret['result'] = False ret['comment'].append('Failed to change user to {0}' .format(user)) elif 'cuser' in perms and user != '': ret['changes']['user'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid( get_group(name, follow_symlinks=follow_symlinks)) and user != '') or ( not salt.utils.platform.is_windows() and group != get_group(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['group'] = group else: ret['result'] = False ret['comment'].append('Failed to change group to {0}' .format(group)) elif 'cgroup' in perms and user != '': ret['changes']['group'] = group if not salt.utils.platform.is_windows() and not is_dir: # Replace attributes on file if it had been removed if perms.get('lattrs', ''): chattr(name, operator='add', attributes=perms['lattrs']) # Mode changes if needed if mode is not None: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: mode = salt.utils.files.normalize_mode(mode) if mode != perms['lmode']: if __opts__['test'] is True: ret['changes']['mode'] = mode else: set_mode(name, mode) if mode != salt.utils.files.normalize_mode(get_mode(name)): ret['result'] = False ret['comment'].append( 'Failed to change mode to {0}'.format(mode) ) else: ret['changes']['mode'] = mode # Modify attributes of file if needed if attrs is not None and not is_dir: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if diff_attrs[0] is not None or diff_attrs[1] is not None: if __opts__['test'] is True: ret['changes']['attrs'] = attrs else: if diff_attrs[0] is not None: chattr(name, operator="add", attributes=diff_attrs[0]) if diff_attrs[1] is not None: chattr(name, operator="remove", attributes=diff_attrs[1]) cmp_attrs = _cmp_attrs(name, attrs) if cmp_attrs[0] is not None or cmp_attrs[1] is not None: ret['result'] = False ret['comment'].append( 'Failed to change attributes to {0}'.format(attrs) ) else: ret['changes']['attrs'] = attrs # Set selinux attributes if needed if salt.utils.platform.is_linux() and (seuser or serole or setype or serange): selinux_error = False try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError: log.error('Unable to get current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to get selinux attributes' ) selinux_error = True if not selinux_error: requested_seuser = None requested_serole = None requested_setype = None requested_serange = None # Only set new selinux variables if updates are needed if seuser and seuser != current_seuser: requested_seuser = seuser if serole and serole != current_serole: requested_serole = serole if setype and setype != current_setype: requested_setype = setype if serange and serange != current_serange: requested_serange = serange if requested_seuser or requested_serole or requested_setype or requested_serange: # selinux updates needed, prep changes output selinux_change_new = '' selinux_change_orig = '' if requested_seuser: selinux_change_new += "User: {0} ".format(requested_seuser) selinux_change_orig += "User: {0} ".format(current_seuser) if requested_serole: selinux_change_new += "Role: {0} ".format(requested_serole) selinux_change_orig += "Role: {0} ".format(current_serole) if requested_setype: selinux_change_new += "Type: {0} ".format(requested_setype) selinux_change_orig += "Type: {0} ".format(current_setype) if requested_serange: selinux_change_new += "Range: {0} ".format(requested_serange) selinux_change_orig += "Range: {0} ".format(current_serange) if __opts__['test']: ret['comment'] = 'File {0} selinux context to be updated'.format(name) ret['result'] = None ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} else: try: # set_selinux_context requires type to be set on any other change if (requested_seuser or requested_serole or requested_serange) and not requested_setype: requested_setype = current_setype result = set_selinux_context(name, user=requested_seuser, role=requested_serole, type=requested_setype, range=requested_serange, persist=True) log.debug('selinux set result: %s', result) current_seuser, current_serole, current_setype, current_serange = result.split(':') except ValueError: log.error('Unable to set current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to set selinux attributes' ) selinux_error = True if not selinux_error: ret['comment'].append('The file {0} is set to be changed'.format(name)) if requested_seuser: if current_seuser != requested_seuser: ret['comment'].append("Unable to update seuser context") ret['result'] = False if requested_serole: if current_serole != requested_serole: ret['comment'].append("Unable to update serole context") ret['result'] = False if requested_setype: if current_setype != requested_setype: ret['comment'].append("Unable to update setype context") ret['result'] = False if requested_serange: if current_serange != requested_serange: ret['comment'].append("Unable to update serange context") ret['result'] = False ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} # Only combine the comment list into a string # after all comments are added above if isinstance(orig_comment, six.string_types): if orig_comment: ret['comment'].insert(0, orig_comment) ret['comment'] = '; '.join(ret['comment']) # Set result to None at the very end of the function, # after all changes have been recorded above if __opts__['test'] is True and ret['changes']: ret['result'] = None return ret, perms def check_managed( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Check to see what changes need to be made for a file CLI Example: .. code-block:: bash salt '*' file.check_managed /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) if comments: __clean_tmp(sfn) return False, comments changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) # Ignore permission for files written temporary directories # Files in any path will still be set correctly using get_managed() if name.startswith(tempfile.gettempdir()): for key in ['user', 'group', 'mode']: changes.pop(key, None) __clean_tmp(sfn) if changes: log.info(changes) comments = ['The following values are set to be changed:\n'] comments.extend('{0}: {1}\n'.format(key, val) for key, val in six.iteritems(changes)) return None, ''.join(comments) return True, 'The file {0} is in the correct state'.format(name) def check_managed_changes( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, keep_mode=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Return a dictionary of what changes need to be made for a file .. versionchanged:: Neon selinux attributes added CLI Example: .. code-block:: bash salt '*' file.check_managed_changes /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if comments: __clean_tmp(sfn) raise CommandExecutionError(comments) if sfn and source and keep_mode: if _urlparse(source).scheme in ('salt', 'file') \ or source.startswith('/'): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) __clean_tmp(sfn) return changes def check_file_meta( name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents=None, seuser=None, serole=None, setype=None, serange=None): ''' Check for the changes in the file metadata. CLI Example: .. code-block:: bash salt '*' file.check_file_meta /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' base .. note:: Supported hash types include sha512, sha384, sha256, sha224, sha1, and md5. name Path to file destination sfn Template-processed source file contents source URL to file source source_sum File checksum information as a dictionary .. code-block:: yaml {hash_type: md5, hsum: <md5sum>} user Destination file user owner group Destination file group owner mode Destination file permissions mode attrs Destination file attributes .. versionadded:: 2018.3.0 saltenv Salt environment used to resolve source files contents File contents seuser selinux user attribute .. versionadded:: Neon serole selinux role attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon ''' changes = {} if not source_sum: source_sum = dict() try: lstats = stats(name, hash_type=source_sum.get('hash_type', None), follow_symlinks=False) except CommandExecutionError: lstats = {} if not lstats: changes['newfile'] = name return changes if 'hsum' in source_sum: if source_sum['hsum'] != lstats['sum']: if not sfn and source: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum['hsum']) if sfn: try: changes['diff'] = get_diff( name, sfn, template=True, show_filenames=False) except CommandExecutionError as exc: changes['diff'] = exc.strerror else: changes['sum'] = 'Checksum differs' if contents is not None: # Write a tempfile with the static contents tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'w') as tmp_: tmp_.write(salt.utils.stringutils.to_str(contents)) # Compare the static contents with the named file try: differences = get_diff(name, tmp, show_filenames=False) except CommandExecutionError as exc: log.error('Failed to diff files: %s', exc) differences = exc.strerror __clean_tmp(tmp) if differences: if __salt__['config.option']('obfuscate_templates'): changes['diff'] = '<Obfuscated Template>' else: changes['diff'] = differences if not salt.utils.platform.is_windows(): # Check owner if (user is not None and user != lstats['user'] and user != lstats['uid']): changes['user'] = user # Check group if (group is not None and group != lstats['group'] and group != lstats['gid']): changes['group'] = group # Normalize the file mode smode = salt.utils.files.normalize_mode(lstats['mode']) mode = salt.utils.files.normalize_mode(mode) if mode is not None and mode != smode: changes['mode'] = mode if attrs: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if attrs is not None \ and (diff_attrs[0] is not None or diff_attrs[1] is not None): changes['attrs'] = attrs # Check selinux if seuser or serole or setype or serange: try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError as exc: log.error('Unable to get current selinux attributes') changes['selinux'] = exc.strerror if seuser and seuser != current_seuser: changes['selinux'] = {"user": seuser} if serole and serole != current_serole: changes['selinux'] = {"role": serole} if setype and setype != current_setype: changes['selinux'] = {"type": setype} if serange and serange != current_serange: changes['selinux'] = {"range": serange} return changes def get_diff(file1, file2, saltenv='base', show_filenames=True, show_changes=True, template=False, source_hash_file1=None, source_hash_file2=None): ''' Return unified diff of two files file1 The first file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, thuis had to be a file local to the minion. file2 The second file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, this had to be a file on the salt fileserver (i.e. ``salt://somefile.txt``) show_filenames : True Set to ``False`` to hide the filenames in the top two lines of the diff. show_changes : True If set to ``False``, and there are differences, then instead of a diff a simple message stating that show_changes is set to ``False`` will be returned. template : False Set to ``True`` if two templates are being compared. This is not useful except for within states, with the ``obfuscate_templates`` option set to ``True``. .. versionadded:: 2018.3.0 source_hash_file1 If ``file1`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 source_hash_file2 If ``file2`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 CLI Examples: .. code-block:: bash salt '*' file.get_diff /home/fred/.vimrc salt://users/fred/.vimrc salt '*' file.get_diff /tmp/foo.txt /tmp/bar.txt ''' files = (file1, file2) source_hashes = (source_hash_file1, source_hash_file2) paths = [] errors = [] for filename, source_hash in zip(files, source_hashes): try: # Local file paths will just return the same path back when passed # to cp.cache_file. cached_path = __salt__['cp.cache_file'](filename, saltenv, source_hash=source_hash) if cached_path is False: errors.append( 'File {0} not found'.format( salt.utils.stringutils.to_unicode(filename) ) ) continue paths.append(cached_path) except MinionError as exc: errors.append(salt.utils.stringutils.to_unicode(exc.__str__())) continue if errors: raise CommandExecutionError( 'Failed to cache one or more files', info=errors ) args = [] for filename in paths: try: with salt.utils.files.fopen(filename, 'rb') as fp_: args.append(fp_.readlines()) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read {0}: {1}'.format( salt.utils.stringutils.to_unicode(filename), exc.strerror ) ) if args[0] != args[1]: if template and __salt__['config.option']('obfuscate_templates'): ret = '<Obfuscated Template>' elif not show_changes: ret = '<show_changes=False>' else: bdiff = _binary_replace(*paths) # pylint: disable=no-value-for-parameter if bdiff: ret = bdiff else: if show_filenames: args.extend(paths) ret = __utils__['stringutils.get_diff'](*args) return ret return '' def manage_file(name, sfn, ret, source, source_sum, user, group, mode, attrs, saltenv, backup, makedirs=False, template=None, # pylint: disable=W0613 show_changes=True, contents=None, dir_mode=None, follow_symlinks=True, skip_verify=False, keep_mode=False, encoding=None, encoding_errors='strict', seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Checks the destination against what was retrieved with get_managed and makes the appropriate modifications (if necessary). name location to place the file sfn location of cached file on the minion This is the path to the file stored on the minion. This file is placed on the minion using cp.cache_file. If the hash sum of that file matches the source_sum, we do not transfer the file to the minion again. This file is then grabbed and if it has template set, it renders the file to be placed into the correct place on the system using salt.files.utils.copyfile() ret The initial state return data structure. Pass in ``None`` to use the default structure. source file reference on the master source_sum sum hash for source user user owner group group owner backup backup_mode attrs attributes to be set on file: '' means remove all of them .. versionadded:: 2018.3.0 makedirs make directories if they do not exist template format of templating show_changes Include diff in state return contents: contents to be placed in the file dir_mode mode for directories created with makedirs skip_verify : False If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 keep_mode : False If ``True``, and the ``source`` is a file from the Salt fileserver (or a local file on the minion), the mode of the destination file will be set to the mode of the source file. .. note:: keep_mode does not work with salt-ssh. As a consequence of how the files are transferred to the minion, and the inability to connect back to the master with salt-ssh, salt is unable to stat the file as it exists on the fileserver and thus cannot mirror the mode on the salt-ssh minion encoding If specified, then the specified encoding will be used. Otherwise, the file will be encoded using the system locale (usually UTF-8). See https://docs.python.org/3/library/codecs.html#standard-encodings for the list of available encodings. .. versionadded:: 2017.7.0 encoding_errors : 'strict' Default is ```'strict'```. See https://docs.python.org/2/library/codecs.html#codec-base-classes for the error handling schemes. .. versionadded:: 2017.7.0 seuser selinux user attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon CLI Example: .. code-block:: bash salt '*' file.manage_file /etc/httpd/conf.d/httpd.conf '' '{}' salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' '' base '' .. versionchanged:: 2014.7.0 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if source: if not sfn: # File is not present, cache it sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) htype = source_sum.get('hash_type', __opts__['hash_type']) # Recalculate source sum now that file has been cached source_sum = { 'hash_type': htype, 'hsum': get_hash(sfn, form=htype) } if keep_mode: if _urlparse(source).scheme in ('salt', 'file', ''): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) # Check changes if the target file exists if os.path.isfile(name) or os.path.islink(name): if os.path.islink(name) and follow_symlinks: real_name = os.path.realpath(name) else: real_name = name # Only test the checksums on files with managed contents if source and not (not follow_symlinks and os.path.islink(real_name)): name_sum = get_hash(real_name, source_sum.get('hash_type', __opts__['hash_type'])) else: name_sum = None # Check if file needs to be replaced if source and (name_sum is None or source_sum.get('hsum', __opts__['hash_type']) != name_sum): if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server or local # source, and we are not skipping checksum verification, then # verify that it matches the specified checksum. if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3}). If the \'source_hash\' value ' 'refers to a remote file with multiple possible ' 'matches, then it may be necessary to set ' '\'source_hash_name\'.'.format( source_sum['hash_type'], source, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # Print a diff equivalent to diff -u old new if __salt__['config.option']('obfuscate_templates'): ret['changes']['diff'] = '<Obfuscated Template>' elif not show_changes: ret['changes']['diff'] = '<show_changes=False>' else: try: ret['changes']['diff'] = get_diff( real_name, sfn, show_filenames=False) except CommandExecutionError as exc: ret['changes']['diff'] = exc.strerror # Pre requisites are met, and the file needs to be replaced, do it try: salt.utils.files.copyfile(sfn, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) try: differences = get_diff( real_name, tmp, show_filenames=False, show_changes=show_changes, template=True) except CommandExecutionError as exc: ret.setdefault('warnings', []).append( 'Failed to detect changes to file: {0}'.format(exc.strerror) ) differences = '' if differences: ret['changes']['diff'] = differences # Pre requisites are met, the file needs to be replaced, do it try: salt.utils.files.copyfile(tmp, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(tmp) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) __clean_tmp(tmp) # Check for changing symlink to regular file here if os.path.islink(name) and not follow_symlinks: if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret try: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) ret['changes']['diff'] = \ 'Replace symbolic link with regular file' if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, follow_symlinks, seuser=seuser, serole=serole, setype=setype, serange=serange) if ret['changes']: ret['comment'] = 'File {0} updated'.format( salt.utils.data.decode(name) ) elif not ret['changes'] and ret['result']: ret['comment'] = 'File {0} is in the correct state'.format( salt.utils.data.decode(name) ) if sfn: __clean_tmp(sfn) return ret else: # target file does not exist contain_dir = os.path.dirname(name) def _set_mode_and_make_dirs(name, dir_mode, mode, user, group): # check for existence of windows drive letter if salt.utils.platform.is_windows(): drive, _ = os.path.splitdrive(name) if drive and not os.path.exists(drive): __clean_tmp(sfn) return _error(ret, '{0} drive not present'.format(drive)) if dir_mode is None and mode is not None: # Add execute bit to each nonzero digit in the mode, if # dir_mode was not specified. Otherwise, any # directories created with makedirs_() below can't be # listed via a shell. mode_list = [x for x in six.text_type(mode)][-3:] for idx in range(len(mode_list)): if mode_list[idx] != '0': mode_list[idx] = six.text_type(int(mode_list[idx]) | 1) dir_mode = ''.join(mode_list) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 makedirs_( path=name, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: makedirs_(name, user=user, group=group, mode=dir_mode) if source: # Apply the new file if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # It is a new file, set the diff accordingly ret['changes']['diff'] = 'New file' if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') else: # source != True if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') # Create the file, user rw-only if mode will be set to prevent # a small security race problem before the permissions are set with salt.utils.files.set_umask(0o077 if mode else None): # Create a new file when test is False and source is None if contents is None: if not __opts__['test']: if touch(name): ret['changes']['new'] = 'file {0} created'.format(name) ret['comment'] = 'Empty file' else: return _error( ret, 'Empty file {0} not created'.format(name) ) else: if not __opts__['test']: if touch(name): ret['changes']['diff'] = 'New file' else: return _error( ret, 'File {0} not created'.format(name) ) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) # Copy into place salt.utils.files.copyfile(tmp, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(tmp) # Now copy the file contents if there is a source file elif sfn: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(sfn) # This is a new file, if no mode specified, use the umask to figure # out what mode to use for the new file. if mode is None and not salt.utils.platform.is_windows(): # Get current umask mask = salt.utils.files.get_umask() # Calculate the mode value that results from the umask mode = oct((0o777 ^ mask) & 0o666) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, seuser=seuser, serole=serole, setype=setype, serange=serange) if not ret['comment']: ret['comment'] = 'File ' + name + ' updated' if __opts__['test']: ret['comment'] = 'File ' + name + ' not updated' elif not ret['changes'] and ret['result']: ret['comment'] = 'File ' + name + ' is in the correct state' if sfn: __clean_tmp(sfn) return ret def mkdir(dir_path, user=None, group=None, mode=None): ''' Ensure that a directory is available. CLI Example: .. code-block:: bash salt '*' file.mkdir /opt/jetty/context ''' dir_path = os.path.expanduser(dir_path) directory = os.path.normpath(dir_path) if not os.path.isdir(directory): # If a caller such as managed() is invoked with makedirs=True, make # sure that any created dirs are created with the same user and group # to follow the principal of least surprise method. makedirs_perms(directory, user, group, mode) return True def makedirs_(path, user=None, group=None, mode=None): ''' Ensure that the directory containing this path is available. .. note:: The path must end with a trailing slash otherwise the directory/directories will be created up to the parent directory. For example if path is ``/opt/code``, then it would be treated as ``/opt/`` but if the path ends with a trailing slash like ``/opt/code/``, then it would be treated as ``/opt/code/``. CLI Example: .. code-block:: bash salt '*' file.makedirs /opt/code/ ''' path = os.path.expanduser(path) if mode: mode = salt.utils.files.normalize_mode(mode) # walk up the directory structure until we find the first existing # directory dirname = os.path.normpath(os.path.dirname(path)) if os.path.isdir(dirname): # There's nothing for us to do msg = 'Directory \'{0}\' already exists'.format(dirname) log.debug(msg) return msg if os.path.exists(dirname): msg = 'The path \'{0}\' already exists and is not a directory'.format( dirname ) log.debug(msg) return msg directories_to_create = [] while True: if os.path.isdir(dirname): break directories_to_create.append(dirname) current_dirname = dirname dirname = os.path.dirname(dirname) if current_dirname == dirname: raise SaltInvocationError( 'Recursive creation for path \'{0}\' would result in an ' 'infinite loop. Please use an absolute path.'.format(dirname) ) # create parent directories from the topmost to the most deeply nested one directories_to_create.reverse() for directory_to_create in directories_to_create: # all directories have the user, group and mode set!! log.debug('Creating directory: %s', directory_to_create) mkdir(directory_to_create, user=user, group=group, mode=mode) def makedirs_perms(name, user=None, group=None, mode='0755'): ''' Taken and modified from os.makedirs to set user, group and mode for each directory created. CLI Example: .. code-block:: bash salt '*' file.makedirs_perms /opt/code ''' name = os.path.expanduser(name) path = os.path head, tail = path.split(name) if not tail: head, tail = path.split(head) if head and tail and not path.exists(head): try: makedirs_perms(head, user, group, mode) except OSError as exc: # be happy if someone already created the path if exc.errno != errno.EEXIST: raise if tail == os.curdir: # xxx/newdir/. exists if xxx/newdir exists return os.mkdir(name) check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) def get_devmm(name): ''' Get major/minor info from a device CLI Example: .. code-block:: bash salt '*' file.get_devmm /dev/chr ''' name = os.path.expanduser(name) if is_chrdev(name) or is_blkdev(name): stat_structure = os.stat(name) return ( os.major(stat_structure.st_rdev), os.minor(stat_structure.st_rdev)) else: return (0, 0) def is_chrdev(name): ''' Check if a file exists and is a character device. CLI Example: .. code-block:: bash salt '*' file.is_chrdev /dev/chr ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the character device does not exist in the first place return False else: raise return stat.S_ISCHR(stat_structure.st_mode) def mknod_chrdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a character device. CLI Example: .. code-block:: bash salt '*' file.mknod_chrdev /dev/chr 180 31 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating character device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFCHR, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created character device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_blkdev(name): ''' Check if a file exists and is a block device. CLI Example: .. code-block:: bash salt '*' file.is_blkdev /dev/blk ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the block device does not exist in the first place return False else: raise return stat.S_ISBLK(stat_structure.st_mode) def mknod_blkdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a block device. CLI Example: .. code-block:: bash salt '*' file.mknod_blkdev /dev/blk 8 999 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating block device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFBLK, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created block device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_fifo(name): ''' Check if a file exists and is a FIFO. CLI Example: .. code-block:: bash salt '*' file.is_fifo /dev/fifo ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the fifo does not exist in the first place return False else: raise return stat.S_ISFIFO(stat_structure.st_mode) def mknod_fifo(name, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a FIFO pipe. CLI Example: .. code-block:: bash salt '*' file.mknod_fifo /dev/fifo ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating FIFO name: %s', name) try: if __opts__['test']: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = None else: if os.mkfifo(name, int(six.text_type(mode).lstrip('0Oo'), 8)) is None: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created fifo check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def mknod(name, ntype, major=0, minor=0, user=None, group=None, mode='0600'): ''' .. versionadded:: 0.17.0 Create a block device, character device, or fifo pipe. Identical to the gnu mknod. CLI Examples: .. code-block:: bash salt '*' file.mknod /dev/chr c 180 31 salt '*' file.mknod /dev/blk b 8 999 salt '*' file.nknod /dev/fifo p ''' ret = False makedirs_(name, user, group) if ntype == 'c': ret = mknod_chrdev(name, major, minor, user, group, mode) elif ntype == 'b': ret = mknod_blkdev(name, major, minor, user, group, mode) elif ntype == 'p': ret = mknod_fifo(name, user, group, mode) else: raise SaltInvocationError( 'Node type unavailable: \'{0}\'. Available node types are ' 'character (\'c\'), block (\'b\'), and pipe (\'p\').'.format(ntype) ) return ret def list_backups(path, limit=None): ''' .. versionadded:: 0.17.0 Lists the previous versions of a file backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups /foo/bar/baz.txt ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows src_dir = parent_dir.replace(':', '_') else: src_dir = parent_dir[1:] # Figure out full path of location of backup file in minion cache bkdir = os.path.join(bkroot, src_dir) if not os.path.isdir(bkdir): return {} files = {} for fname in [x for x in os.listdir(bkdir) if os.path.isfile(os.path.join(bkdir, x))]: if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows strpfmt = '{0}_%a_%b_%d_%H-%M-%S_%f_%Y'.format(basename) else: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(fname, strpfmt) except ValueError: # File didn't match the strp format string, so it's not a backup # for this file. Move on to the next one. continue if salt.utils.platform.is_windows(): str_format = '%a %b %d %Y %H-%M-%S.%f' else: str_format = '%a %b %d %Y %H:%M:%S.%f' files.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime(str_format) location = os.path.join(bkdir, fname) files[timestamp]['Size'] = os.stat(location).st_size files[timestamp]['Location'] = location return dict(list(zip( list(range(len(files))), [files[x] for x in sorted(files, reverse=True)[:limit]] ))) list_backup = salt.utils.functools.alias_function(list_backups, 'list_backup') def list_backups_dir(path, limit=None): ''' Lists the previous versions of a directory backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The directory on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups_dir /foo/bar/baz/ ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups_dir: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) # Figure out full path of location of backup folder in minion cache bkdir = os.path.join(bkroot, parent_dir[1:]) if not os.path.isdir(bkdir): return {} files = {} f = dict([(i, len(list(n))) for i, n in itertools.groupby([x.split("_")[0] for x in sorted(os.listdir(bkdir))])]) ff = os.listdir(bkdir) for i, n in six.iteritems(f): ssfile = {} for x in sorted(ff): basename = x.split('_')[0] if i == basename: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(x, strpfmt) except ValueError: # Folder didn't match the strp format string, so it's not a backup # for this folder. Move on to the next one. continue ssfile.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime('%a %b %d %Y %H:%M:%S.%f') location = os.path.join(bkdir, x) ssfile[timestamp]['Size'] = os.stat(location).st_size ssfile[timestamp]['Location'] = location sfiles = dict(list(zip(list(range(n)), [ssfile[x] for x in sorted(ssfile, reverse=True)[:limit]]))) sefiles = {i: sfiles} files.update(sefiles) return files def restore_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Restore a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to restore, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.restore_backup /foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) # Note: This only supports minion backups, so this function will need to be # modified if/when master backups are implemented. ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret salt.utils.files.backup_minion(path, _get_bkroot()) try: shutil.copyfile(backup['Location'], path) except IOError as exc: ret['comment'] = \ 'Unable to restore {0} to {1}: ' \ '{2}'.format(backup['Location'], path, exc) return ret else: ret['result'] = True ret['comment'] = 'Successfully restored {0} to ' \ '{1}'.format(backup['Location'], path) # Try to set proper ownership if not salt.utils.platform.is_windows(): try: fstat = os.stat(path) except (OSError, IOError): ret['comment'] += ', but was unable to set ownership' else: os.chown(path, fstat.st_uid, fstat.st_gid) return ret def delete_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Delete a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to delete, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.delete_backup /var/cache/salt/minion/file_backup/home/foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret try: os.remove(backup['Location']) except IOError as exc: ret['comment'] = 'Unable to remove {0}: {1}'.format(backup['Location'], exc) else: ret['result'] = True ret['comment'] = 'Successfully removed {0}'.format(backup['Location']) return ret remove_backup = salt.utils.functools.alias_function(delete_backup, 'remove_backup') def grep(path, pattern, *opts): ''' Grep for a string in the specified file .. note:: This function's return value is slated for refinement in future versions of Salt path Path to the file to be searched .. note:: Globbing is supported (i.e. ``/var/log/foo/*.log``, but if globbing is being used then the path should be quoted to keep the shell from attempting to expand the glob expression. pattern Pattern to match. For example: ``test``, or ``a[0-5]`` opts Additional command-line flags to pass to the grep command. For example: ``-v``, or ``-i -B2`` .. note:: The options should come after a double-dash (as shown in the examples below) to keep Salt's own argument parser from interpreting them. CLI Example: .. code-block:: bash salt '*' file.grep /etc/passwd nobody salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i -B2 salt '*' file.grep "/etc/sysconfig/network-scripts/*" ipaddr -- -i -l ''' path = os.path.expanduser(path) # Backup the path in case the glob returns nothing _path = path path = glob.glob(path) # If the list is empty no files exist # so we revert back to the original path # so the result is an error. if not path: path = _path split_opts = [] for opt in opts: try: split = salt.utils.args.shlex_split(opt) except AttributeError: split = salt.utils.args.shlex_split(six.text_type(opt)) if len(split) > 1: raise SaltInvocationError( 'Passing multiple command line arguments in a single string ' 'is not supported, please pass the following arguments ' 'separately: {0}'.format(opt) ) split_opts.extend(split) if isinstance(path, list): cmd = ['grep'] + split_opts + [pattern] + path else: cmd = ['grep'] + split_opts + [pattern, path] try: ret = __salt__['cmd.run_all'](cmd, python_shell=False) except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return ret def open_files(by_pid=False): ''' Return a list of all physical open files on the system. CLI Examples: .. code-block:: bash salt '*' file.open_files salt '*' file.open_files by_pid=True ''' # First we collect valid PIDs pids = {} procfs = os.listdir('/proc/') for pfile in procfs: try: pids[int(pfile)] = [] except ValueError: # Not a valid PID, move on pass # Then we look at the open files for each PID files = {} for pid in pids: ppath = '/proc/{0}'.format(pid) try: tids = os.listdir('{0}/task'.format(ppath)) except OSError: continue # Collect the names of all of the file descriptors fd_ = [] #try: # fd_.append(os.path.realpath('{0}/task/{1}exe'.format(ppath, tid))) #except Exception: # pass for fpath in os.listdir('{0}/fd'.format(ppath)): fd_.append('{0}/fd/{1}'.format(ppath, fpath)) for tid in tids: try: fd_.append( os.path.realpath('{0}/task/{1}/exe'.format(ppath, tid)) ) except OSError: continue for tpath in os.listdir('{0}/task/{1}/fd'.format(ppath, tid)): fd_.append('{0}/task/{1}/fd/{2}'.format(ppath, tid, tpath)) fd_ = sorted(set(fd_)) # Loop through file descriptors and return useful data for each file for fdpath in fd_: # Sometimes PIDs and TIDs disappear before we can query them try: name = os.path.realpath(fdpath) # Running stat on the file cuts out all of the sockets and # deleted files from the list os.stat(name) except OSError: continue if name not in files: files[name] = [pid] else: # We still want to know which PIDs are using each file files[name].append(pid) files[name] = sorted(set(files[name])) pids[pid].append(name) pids[pid] = sorted(set(pids[pid])) if by_pid: return pids return files def pardir(): ''' Return the relative parent directory path symbol for underlying OS .. versionadded:: 2014.7.0 This can be useful when constructing Salt Formulas. .. code-block:: jinja {% set pardir = salt['file.pardir']() %} {% set final_path = salt['file.join']('subdir', pardir, 'confdir') %} CLI Example: .. code-block:: bash salt '*' file.pardir ''' return os.path.pardir def normpath(path): ''' Returns Normalize path, eliminating double slashes, etc. .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.normpath'](tpldir + '/../vars.jinja') import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.normpath 'a/b/c/..' ''' return os.path.normpath(path) def basename(path): ''' Returns the final component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- set filename = salt['file.basename'](source_file) %} CLI Example: .. code-block:: bash salt '*' file.basename 'test/test.config' ''' return os.path.basename(path) def dirname(path): ''' Returns the directory component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.dirname'](tpldir) + '/vars.jinja' import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.dirname 'test/path/filename.config' ''' return os.path.dirname(path) def join(*args): ''' Return a normalized file system path for the underlying OS .. versionadded:: 2014.7.0 This can be useful at the CLI but is frequently useful when scripting combining path variables: .. code-block:: jinja {% set www_root = '/var' %} {% set app_dir = 'myapp' %} myapp_config: file: - managed - name: {{ salt['file.join'](www_root, app_dir, 'config.yaml') }} CLI Example: .. code-block:: bash salt '*' file.join '/' 'usr' 'local' 'bin' ''' return os.path.join(*args) def move(src, dst): ''' Move a file or directory CLI Example: .. code-block:: bash salt '*' file.move /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('Source path must be absolute.') if not os.path.isabs(dst): raise SaltInvocationError('Destination path must be absolute.') ret = { 'result': True, 'comment': "'{0}' moved to '{1}'".format(src, dst), } try: shutil.move(src, dst) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move '{0}' to '{1}': {2}".format(src, dst, exc) ) return ret def diskusage(path): ''' Recursively calculate disk usage of path and return it in bytes CLI Example: .. code-block:: bash salt '*' file.diskusage /path/to/check ''' total_size = 0 seen = set() if os.path.isfile(path): stat_structure = os.stat(path) ret = stat_structure.st_size return ret for dirpath, dirnames, filenames in salt.utils.path.os_walk(path): for f in filenames: fp = os.path.join(dirpath, f) try: stat_structure = os.stat(fp) except OSError: continue if stat_structure.st_ino in seen: continue seen.add(stat_structure.st_ino) total_size += stat_structure.st_size ret = total_size return ret
saltstack/salt
salt/modules/file.py
_splitlines_preserving_trailing_newline
python
def _splitlines_preserving_trailing_newline(str): ''' Returns a list of the lines in the string, breaking at line boundaries and preserving a trailing newline (if present). Essentially, this works like ``str.striplines(False)`` but preserves an empty line at the end. This is equivalent to the following code: .. code-block:: python lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') ''' lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') return lines
Returns a list of the lines in the string, breaking at line boundaries and preserving a trailing newline (if present). Essentially, this works like ``str.striplines(False)`` but preserves an empty line at the end. This is equivalent to the following code: .. code-block:: python lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('')
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L142-L159
null
# -*- coding: utf-8 -*- ''' Manage information about regular files, directories, and special files on the minion, set/read user, group, mode, and data ''' # TODO: We should add the capability to do u+r type operations here # some time in the future from __future__ import absolute_import, print_function, unicode_literals # Import python libs import datetime import errno import fnmatch import io import itertools import logging import operator import os import re import shutil import stat import string import sys import tempfile import time import glob import hashlib import mmap from collections import Iterable, Mapping from functools import reduce # pylint: disable=redefined-builtin # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range, zip from salt.ext.six.moves.urllib.parse import urlparse as _urlparse # pylint: enable=import-error,no-name-in-module,redefined-builtin try: import grp import pwd except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.atomicfile import salt.utils.data import salt.utils.dictupdate import salt.utils.filebuffer import salt.utils.files import salt.utils.find import salt.utils.functools import salt.utils.hashutils import salt.utils.itertools import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.templates import salt.utils.url import salt.utils.user from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError, get_error_message as _get_error_message from salt.utils.files import HASHES, HASHES_REVMAP log = logging.getLogger(__name__) __func_alias__ = { 'makedirs_': 'makedirs' } def __virtual__(): ''' Only work on POSIX-like systems ''' # win_file takes care of windows if salt.utils.platform.is_windows(): return ( False, 'The file execution module cannot be loaded: only available on ' 'non-Windows systems - use win_file instead.' ) return True def __clean_tmp(sfn): ''' Clean out a template temp file ''' if sfn.startswith(os.path.join(tempfile.gettempdir(), salt.utils.files.TEMPFILE_PREFIX)): # Don't remove if it exists in file_roots (any saltenv) all_roots = itertools.chain.from_iterable( six.itervalues(__opts__['file_roots'])) in_roots = any(sfn.startswith(root) for root in all_roots) # Only clean up files that exist if os.path.exists(sfn) and not in_roots: os.remove(sfn) def _error(ret, err_msg): ''' Common function for setting error information for return dicts ''' ret['result'] = False ret['comment'] = err_msg return ret def _binary_replace(old, new): ''' This function does NOT do any diffing, it just checks the old and new files to see if either is binary, and provides an appropriate string noting the difference between the two files. If neither file is binary, an empty string is returned. This function should only be run AFTER it has been determined that the files differ. ''' old_isbin = not __utils__['files.is_text'](old) new_isbin = not __utils__['files.is_text'](new) if any((old_isbin, new_isbin)): if all((old_isbin, new_isbin)): return 'Replace binary file' elif old_isbin: return 'Replace binary file with text file' elif new_isbin: return 'Replace text file with binary file' return '' def _get_bkroot(): ''' Get the location of the backup dir in the minion cache ''' # Get the cachedir from the minion config return os.path.join(__salt__['config.get']('cachedir'), 'file_backup') def gid_to_group(gid): ''' Convert the group id to the group name on this system gid gid to convert to a group name CLI Example: .. code-block:: bash salt '*' file.gid_to_group 0 ''' try: gid = int(gid) except ValueError: # This is not an integer, maybe it's already the group name? gid = group_to_gid(gid) if gid == '': # Don't even bother to feed it to grp return '' try: return grp.getgrgid(gid).gr_name except (KeyError, NameError): # If group is not present, fall back to the gid. return gid def group_to_gid(group): ''' Convert the group to the gid on this system group group to convert to its gid CLI Example: .. code-block:: bash salt '*' file.group_to_gid root ''' if group is None: return '' try: if isinstance(group, int): return group return grp.getgrnam(group).gr_gid except KeyError: return '' def get_gid(path, follow_symlinks=True): ''' Return the id of the group that owns a given file path file or directory of which to get the gid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_gid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('gid', -1) def get_group(path, follow_symlinks=True): ''' Return the group that owns a given file path file or directory of which to get the group follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_group /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('group', False) def uid_to_user(uid): ''' Convert a uid to a user name uid uid to convert to a username CLI Example: .. code-block:: bash salt '*' file.uid_to_user 0 ''' try: return pwd.getpwuid(uid).pw_name except (KeyError, NameError): # If user is not present, fall back to the uid. return uid def user_to_uid(user): ''' Convert user name to a uid user user name to convert to its uid CLI Example: .. code-block:: bash salt '*' file.user_to_uid root ''' if user is None: user = salt.utils.user.get_user() try: if isinstance(user, int): return user return pwd.getpwnam(user).pw_uid except KeyError: return '' def get_uid(path, follow_symlinks=True): ''' Return the id of the user that owns a given file path file or directory of which to get the uid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_uid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('uid', -1) def get_user(path, follow_symlinks=True): ''' Return the user that owns a given file path file or directory of which to get the user follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_user /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('user', False) def get_mode(path, follow_symlinks=True): ''' Return the mode of a file path file or directory of which to get the mode follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_mode /etc/passwd .. versionchanged:: 2014.1.0 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('mode', '') def set_mode(path, mode): ''' Set the mode of a file path file or directory of which to set the mode mode mode to set the path to CLI Example: .. code-block:: bash salt '*' file.set_mode /etc/passwd 0644 ''' path = os.path.expanduser(path) mode = six.text_type(mode).lstrip('0Oo') if not mode: mode = '0' if not os.path.exists(path): raise CommandExecutionError('{0}: File not found'.format(path)) try: os.chmod(path, int(mode, 8)) except Exception: return 'Invalid Mode ' + mode return get_mode(path) def lchown(path, user, group): ''' Chown a file, pass the file the desired user and group without following symlinks. path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 return os.lchown(path, uid, gid) def chown(path, user, group): ''' Chown a file, pass the file the desired user and group path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 if not os.path.exists(path): try: # Broken symlinks will return false, but still need to be chowned return os.lchown(path, uid, gid) except OSError: pass err += 'File not found' if err: return err return os.chown(path, uid, gid) def chgrp(path, group): ''' Change the group of a file path path to the file or directory group group owner CLI Example: .. code-block:: bash salt '*' file.chgrp /etc/passwd root ''' path = os.path.expanduser(path) user = get_user(path) return chown(path, user, group) def _cmp_attrs(path, attrs): ''' .. versionadded:: 2018.3.0 Compare attributes of a given file to given attributes. Returns a pair (list) where first item are attributes to add and second item are to be removed. Please take into account when using this function that some minions will not have lsattr installed. path path to file to compare attributes with. attrs string of attributes to compare against a given file ''' diff = [None, None] # lsattr for AIX is not the same thing as lsattr for linux. if salt.utils.platform.is_aix(): return None try: lattrs = lsattr(path).get(path, '') except AttributeError: # lsattr not installed return None old = [chr for chr in lattrs if chr not in attrs] if old: diff[1] = ''.join(old) new = [chr for chr in attrs if chr not in lattrs] if new: diff[0] = ''.join(new) return diff def lsattr(path): ''' .. versionadded:: 2018.3.0 .. versionchanged:: 2018.3.1 If ``lsattr`` is not installed on the system, ``None`` is returned. .. versionchanged:: 2018.3.4 If on ``AIX``, ``None`` is returned even if in filesystem as lsattr on ``AIX`` is not the same thing as the linux version. Obtain the modifiable attributes of the given file. If path is to a directory, an empty list is returned. path path to file to obtain attributes of. File/directory must exist. CLI Example: .. code-block:: bash salt '*' file.lsattr foo1.txt ''' if not salt.utils.path.which('lsattr') or salt.utils.platform.is_aix(): return None if not os.path.exists(path): raise SaltInvocationError("File or directory does not exist: " + path) cmd = ['lsattr', path] result = __salt__['cmd.run'](cmd, ignore_retcode=True, python_shell=False) results = {} for line in result.splitlines(): if not line.startswith('lsattr: '): vals = line.split(None, 1) results[vals[1]] = re.findall(r"[aAcCdDeijPsStTu]", vals[0]) return results def chattr(*files, **kwargs): ''' .. versionadded:: 2018.3.0 Change the attributes of files. This function accepts one or more files and the following options: operator Can be wither ``add`` or ``remove``. Determines whether attributes should be added or removed from files attributes One or more of the following characters: ``aAcCdDeijPsStTu``, representing attributes to add to/remove from files version a version number to assign to the file(s) flags One or more of the following characters: ``RVf``, representing flags to assign to chattr (recurse, verbose, suppress most errors) CLI Example: .. code-block:: bash salt '*' file.chattr foo1.txt foo2.txt operator=add attributes=ai salt '*' file.chattr foo3.txt operator=remove attributes=i version=2 ''' operator = kwargs.pop('operator', None) attributes = kwargs.pop('attributes', None) flags = kwargs.pop('flags', None) version = kwargs.pop('version', None) if (operator is None) or (operator not in ('add', 'remove')): raise SaltInvocationError( "Need an operator: 'add' or 'remove' to modify attributes.") if attributes is None: raise SaltInvocationError("Need attributes: [aAcCdDeijPsStTu]") cmd = ['chattr'] if operator == "add": attrs = '+{0}'.format(attributes) elif operator == "remove": attrs = '-{0}'.format(attributes) cmd.append(attrs) if flags is not None: cmd.append('-{0}'.format(flags)) if version is not None: cmd.extend(['-v', version]) cmd.extend(files) result = __salt__['cmd.run'](cmd, python_shell=False) if bool(result): raise CommandExecutionError( "chattr failed to run, possibly due to bad parameters.") return True def get_sum(path, form='sha256'): ''' Return the checksum for the given file. The following checksum algorithms are supported: * md5 * sha1 * sha224 * sha256 **(default)** * sha384 * sha512 path path to the file or directory form desired sum format CLI Example: .. code-block:: bash salt '*' file.get_sum /etc/passwd sha512 ''' path = os.path.expanduser(path) if not os.path.isfile(path): return 'File not found' return salt.utils.hashutils.get_hash(path, form, 4096) def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` path path to the file or directory form desired sum format chunk_size amount to sum at once CLI Example: .. code-block:: bash salt '*' file.get_hash /etc/shadow ''' return salt.utils.hashutils.get_hash(os.path.expanduser(path), form, chunk_size) def get_source_sum(file_name='', source='', source_hash=None, source_hash_name=None, saltenv='base'): ''' .. versionadded:: 2016.11.0 Used by :py:func:`file.get_managed <salt.modules.file.get_managed>` to obtain the hash and hash type from the parameters specified below. file_name Optional file name being managed, for matching with :py:func:`file.extract_hash <salt.modules.file.extract_hash>`. source Source file, as used in :py:mod:`file <salt.states.file>` and other states. If ``source_hash`` refers to a file containing hashes, then this filename will be used to match a filename in that file. If the ``source_hash`` is a hash expression, then this argument will be ignored. source_hash Hash file/expression, as used in :py:mod:`file <salt.states.file>` and other states. If this value refers to a remote URL or absolute path to a local file, it will be cached and :py:func:`file.extract_hash <salt.modules.file.extract_hash>` will be used to obtain a hash from it. source_hash_name Specific file name to look for when ``source_hash`` refers to a remote file, used to disambiguate ambiguous matches. saltenv : base Salt fileserver environment from which to retrieve the source_hash. This value will only be used when ``source_hash`` refers to a file on the Salt fileserver (i.e. one beginning with ``salt://``). CLI Example: .. code-block:: bash salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=499ae16dcae71eeb7c3a30c75ea7a1a6 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 source_hash_name=./dir2/foo.tar.gz ''' def _invalid_source_hash_format(): ''' DRY helper for reporting invalid source_hash input ''' raise CommandExecutionError( 'Source hash {0} format is invalid. The supported formats are: ' '1) a hash, 2) an expression in the format <hash_type>=<hash>, or ' '3) either a path to a local file containing hashes, or a URI of ' 'a remote hash file. Supported protocols for remote hash files ' 'are: {1}. The hash may also not be of a valid length, the ' 'following are supported hash types and lengths: {2}.'.format( source_hash, ', '.join(salt.utils.files.VALID_PROTOS), ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) hash_fn = None if os.path.isabs(source_hash): hash_fn = source_hash else: try: proto = _urlparse(source_hash).scheme if proto in salt.utils.files.VALID_PROTOS: hash_fn = __salt__['cp.cache_file'](source_hash, saltenv) if not hash_fn: raise CommandExecutionError( 'Source hash file {0} not found'.format(source_hash) ) else: if proto != '': # Some unsupported protocol (e.g. foo://) is being used. # We'll get into this else block if a hash expression # (like md5=<md5 checksum here>), but in those cases, the # protocol will be an empty string, in which case we avoid # this error condition. _invalid_source_hash_format() except (AttributeError, TypeError): _invalid_source_hash_format() if hash_fn is not None: ret = extract_hash(hash_fn, '', file_name, source, source_hash_name) if ret is None: _invalid_source_hash_format() ret['hsum'] = ret['hsum'].lower() return ret else: # The source_hash is a hash expression ret = {} try: ret['hash_type'], ret['hsum'] = \ [x.strip() for x in source_hash.split('=', 1)] except AttributeError: _invalid_source_hash_format() except ValueError: # No hash type, try to figure out by hash length if not re.match('^[{0}]+$'.format(string.hexdigits), source_hash): _invalid_source_hash_format() ret['hsum'] = source_hash source_hash_len = len(source_hash) if source_hash_len in HASHES_REVMAP: ret['hash_type'] = HASHES_REVMAP[source_hash_len] else: _invalid_source_hash_format() if ret['hash_type'] not in HASHES: raise CommandExecutionError( 'Invalid hash type \'{0}\'. Supported hash types are: {1}. ' 'Either remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to a supported type.' .format(ret['hash_type'], ', '.join(HASHES), ret['hsum']) ) else: hsum_len = len(ret['hsum']) if hsum_len not in HASHES_REVMAP: _invalid_source_hash_format() elif hsum_len != HASHES[ret['hash_type']]: raise CommandExecutionError( 'Invalid length ({0}) for hash type \'{1}\'. Either ' 'remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to \'{3}\''.format( hsum_len, ret['hash_type'], ret['hsum'], HASHES_REVMAP[hsum_len], ) ) ret['hsum'] = ret['hsum'].lower() return ret def check_hash(path, file_hash): ''' Check if a file matches the given hash string Returns ``True`` if the hash matches, otherwise ``False``. path Path to a file local to the minion. hash The hash to check against the file specified in the ``path`` argument. .. versionchanged:: 2016.11.4 For this and newer versions the hash can be specified without an accompanying hash type (e.g. ``e138491e9d5b97023cea823fe17bac22``), but for earlier releases it is necessary to also specify the hash type in the format ``<hash_type>=<hash_value>`` (e.g. ``md5=e138491e9d5b97023cea823fe17bac22``). CLI Example: .. code-block:: bash salt '*' file.check_hash /etc/fstab e138491e9d5b97023cea823fe17bac22 salt '*' file.check_hash /etc/fstab md5=e138491e9d5b97023cea823fe17bac22 ''' path = os.path.expanduser(path) if not isinstance(file_hash, six.string_types): raise SaltInvocationError('hash must be a string') for sep in (':', '='): if sep in file_hash: hash_type, hash_value = file_hash.split(sep, 1) break else: hash_value = file_hash hash_len = len(file_hash) hash_type = HASHES_REVMAP.get(hash_len) if hash_type is None: raise SaltInvocationError( 'Hash {0} (length: {1}) could not be matched to a supported ' 'hash type. The supported hash types and lengths are: ' '{2}'.format( file_hash, hash_len, ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) return get_hash(path, hash_type) == hash_value def find(path, *args, **kwargs): ''' Approximate the Unix ``find(1)`` command and return a list of paths that meet the specified criteria. The options include match criteria: .. code-block:: text name = path-glob # case sensitive iname = path-glob # case insensitive regex = path-regex # case sensitive iregex = path-regex # case insensitive type = file-types # match any listed type user = users # match any listed user group = groups # match any listed group size = [+-]number[size-unit] # default unit = byte mtime = interval # modified since date grep = regex # search file contents and/or actions: .. code-block:: text delete [= file-types] # default type = 'f' exec = command [arg ...] # where {} is replaced by pathname print [= print-opts] and/or depth criteria: .. code-block:: text maxdepth = maximum depth to transverse in path mindepth = minimum depth to transverse before checking files or directories The default action is ``print=path`` ``path-glob``: .. code-block:: text * = match zero or more chars ? = match any char [abc] = match a, b, or c [!abc] or [^abc] = match anything except a, b, and c [x-y] = match chars x through y [!x-y] or [^x-y] = match anything except chars x through y {a,b,c} = match a or b or c ``path-regex``: a Python Regex (regular expression) pattern to match pathnames ``file-types``: a string of one or more of the following: .. code-block:: text a: all file types b: block device c: character device d: directory p: FIFO (named pipe) f: plain file l: symlink s: socket ``users``: a space and/or comma separated list of user names and/or uids ``groups``: a space and/or comma separated list of group names and/or gids ``size-unit``: .. code-block:: text b: bytes k: kilobytes m: megabytes g: gigabytes t: terabytes interval: .. code-block:: text [<num>w] [<num>d] [<num>h] [<num>m] [<num>s] where: w: week d: day h: hour m: minute s: second print-opts: a comma and/or space separated list of one or more of the following: .. code-block:: text group: group name md5: MD5 digest of file contents mode: file permissions (as integer) mtime: last modification time (as time_t) name: file basename path: file absolute path size: file size in bytes type: file type user: user name CLI Examples: .. code-block:: bash salt '*' file.find / type=f name=\\*.bak size=+10m salt '*' file.find /var mtime=+30d size=+10m print=path,size,mtime salt '*' file.find /var/log name=\\*.[0-9] mtime=+30d size=+10m delete ''' if 'delete' in args: kwargs['delete'] = 'f' elif 'print' in args: kwargs['print'] = 'path' try: finder = salt.utils.find.Finder(kwargs) except ValueError as ex: return 'error: {0}'.format(ex) ret = [item for i in [finder.find(p) for p in glob.glob(os.path.expanduser(path))] for item in i] ret.sort() return ret def _sed_esc(string, escape_all=False): ''' Escape single quotes and forward slashes ''' special_chars = "^.[$()|*+?{" string = string.replace("'", "'\"'\"'").replace("/", "\\/") if escape_all is True: for char in special_chars: string = string.replace(char, "\\" + char) return string def sed(path, before, after, limit='', backup='.bak', options='-r -e', flags='g', escape_all=False, negate_match=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup options : ``-r -e`` Options to pass to sed flags : ``g`` Flags to modify the sed search; e.g., ``i`` for case-insensitive pattern matching negate_match : False Negate the search command (``!``) .. versionadded:: 0.17.0 Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # path = os.path.expanduser(path) if not os.path.exists(path): return False # Mandate that before and after are strings before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.append('-i{0}'.format(backup) if backup else '-i') cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}{negate_match}s/{before}/{after}/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', negate_match='!' if negate_match else '', before=before, after=after, flags=flags ) ) cmd.append(path) return __salt__['cmd.run_all'](cmd, python_shell=False) def sed_contains(path, text, limit='', flags='g'): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the file at ``path`` contains ``text``. Utilizes sed to perform the search (line-wise search). Note: the ``p`` flag will be added to any flags you pass in. CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' # Largely inspired by Fabric's contrib.files.contains() path = os.path.expanduser(path) if not os.path.exists(path): return False before = _sed_esc(six.text_type(text), False) limit = _sed_esc(six.text_type(limit), False) options = '-n -r -e' if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}s/{before}/$/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', before=before, flags='p{0}'.format(flags) ) ) cmd.append(path) result = __salt__['cmd.run'](cmd, python_shell=False) return bool(result) def psed(path, before, after, limit='', backup='.bak', flags='gMS', escape_all=False, multi=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file (pure Python version) Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup flags : ``gMS`` Flags to modify the search. Valid values are: - ``g``: Replace all occurrences of the pattern, not just the first. - ``I``: Ignore case. - ``L``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\s`` and ``\\S`` dependent on the locale. - ``M``: Treat multiple lines as a single line. - ``S``: Make `.` match all characters, including newlines. - ``U``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\d``, ``\\D``, ``\\s`` and ``\\S`` dependent on Unicode. - ``X``: Verbose (whitespace is ignored). multi: ``False`` If True, treat the entire file as a single line Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # # Mandate that before and after are strings path = os.path.expanduser(path) multi = bool(multi) before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) # The pattern to replace with does not need to be escaped!!! # after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) shutil.copy2(path, '{0}{1}'.format(path, backup)) with salt.utils.files.fopen(path, 'w') as ofile: with salt.utils.files.fopen('{0}{1}'.format(path, backup), 'r') as ifile: if multi is True: for line in ifile.readline(): ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(line), before, after, limit, flags ) ) ) else: ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(ifile.read()), before, after, limit, flags ) ) ) RE_FLAG_TABLE = {'I': re.I, 'L': re.L, 'M': re.M, 'S': re.S, 'U': re.U, 'X': re.X} def _psed(text, before, after, limit, flags): ''' Does the actual work for file.psed, so that single lines can be passed in ''' atext = text if limit: limit = re.compile(limit) comps = text.split(limit) atext = ''.join(comps[1:]) count = 1 if 'g' in flags: count = 0 flags = flags.replace('g', '') aflags = 0 for flag in flags: aflags |= RE_FLAG_TABLE[flag] before = re.compile(before, flags=aflags) text = re.sub(before, after, atext, count=count) return text def uncomment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Uncomment specified commented lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be uncommented. This regex should not include the comment character. A leading ``^`` character will be stripped for convenience (for easily switching between comment() and uncomment()). char : ``#`` The character to remove in order to uncomment a line backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup CLI Example: .. code-block:: bash salt '*' file.uncomment /etc/hosts.deny 'ALL: PARANOID' ''' return comment_line(path=path, regex=regex, char=char, cmnt=False, backup=backup) def comment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Comment out specified lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be commented; this pattern will be wrapped in parenthesis and will move any preceding/trailing ``^`` or ``$`` characters outside the parenthesis (e.g., the pattern ``^foo$`` will be rewritten as ``^(foo)$``) char : ``#`` The character to be inserted at the beginning of a line in order to comment it out backup : ``.bak`` The file will be backed up before edit with this file extension .. warning:: This backup will be overwritten each time ``sed`` / ``comment`` / ``uncomment`` is called. Meaning the backup will only be useful after the first invocation. CLI Example: .. code-block:: bash salt '*' file.comment /etc/modules pcspkr ''' return comment_line(path=path, regex=regex, char=char, cmnt=True, backup=backup) def comment_line(path, regex, char='#', cmnt=True, backup='.bak'): r''' Comment or Uncomment a line in a text file. :param path: string The full path to the text file. :param regex: string A regex expression that begins with ``^`` that will find the line you wish to comment. Can be as simple as ``^color =`` :param char: string The character used to comment a line in the type of file you're referencing. Default is ``#`` :param cmnt: boolean True to comment the line. False to uncomment the line. Default is True. :param backup: string The file extension to give the backup file. Default is ``.bak`` Set to False/None to not keep a backup. :return: boolean Returns True if successful, False if not CLI Example: The following example will comment out the ``pcspkr`` line in the ``/etc/modules`` file using the default ``#`` character and create a backup file named ``modules.bak`` .. code-block:: bash salt '*' file.comment_line '/etc/modules' '^pcspkr' CLI Example: The following example will uncomment the ``log_level`` setting in ``minion`` config file if it is set to either ``warning``, ``info``, or ``debug`` using the ``#`` character and create a backup file named ``minion.bk`` .. code-block:: bash salt '*' file.comment_line 'C:\salt\conf\minion' '^log_level: (warning|info|debug)' '#' False '.bk' ''' # Get the regex for comment or uncomment if cmnt: regex = '{0}({1}){2}'.format( '^' if regex.startswith('^') else '', regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') else: regex = r'^{0}\s*({1}){2}'.format( char, regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') # Load the real path to the file path = os.path.realpath(os.path.expanduser(path)) # Make sure the file exists if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) # Make sure it is a text file if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}'.format(path)) # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes found = False # Dictionaries for comparing changes orig_file = [] new_file = [] # Buffer size for fopen bufsize = os.path.getsize(path) try: # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: # Is it in this line line = salt.utils.stringutils.to_unicode(line) if re.match(regex, line): # Load lines into dictionaries, set found to True orig_file.append(line) if cmnt: new_file.append('{0}{1}'.format(char, line)) else: new_file.append(line.lstrip(char)) found = True except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) # We've searched the whole file. If we didn't find anything, return False if not found: return False if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Create a copy to read from and to use as a backup later try: temp_file = _mkstemp_copy(path=path, preserve_inode=False) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) try: # Open the file in write mode mode = 'wb' if six.PY2 and salt.utils.platform.is_windows() else 'w' with salt.utils.files.fopen(path, mode=mode, buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: line = salt.utils.stringutils.to_unicode(line) try: # Is it in this line if re.match(regex, line): # Write the new line if cmnt: wline = '{0}{1}'.format(char, line) else: wline = line.lstrip(char) else: # Write the existing line (no change) wline = line wline = salt.utils.stringutils.to_bytes(wline) \ if six.PY2 and salt.utils.platform.is_windows() \ else salt.utils.stringutils.to_str(wline) w_file.write(wline) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if backup: # Move the backup file to the original directory backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: os.remove(temp_file) if not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) # Return a diff using the two dictionaries return __utils__['stringutils.get_diff'](orig_file, new_file) def _get_flags(flags): ''' Return an integer appropriate for use as a flag for the re module from a list of human-readable strings .. code-block:: python >>> _get_flags(['MULTILINE', 'IGNORECASE']) 10 >>> _get_flags('MULTILINE') 8 >>> _get_flags(2) 2 ''' if isinstance(flags, six.string_types): flags = [flags] if isinstance(flags, Iterable) and not isinstance(flags, Mapping): _flags_acc = [] for flag in flags: _flag = getattr(re, six.text_type(flag).upper()) if not isinstance(_flag, six.integer_types): raise SaltInvocationError( 'Invalid re flag given: {0}'.format(flag) ) _flags_acc.append(_flag) return reduce(operator.__or__, _flags_acc) elif isinstance(flags, six.integer_types): return flags else: raise SaltInvocationError( 'Invalid re flags: "{0}", must be given either as a single flag ' 'string, a list of strings, or as an integer'.format(flags) ) def _add_flags(flags, new_flags): ''' Combine ``flags`` and ``new_flags`` ''' flags = _get_flags(flags) new_flags = _get_flags(new_flags) return flags | new_flags def _mkstemp_copy(path, preserve_inode=True): ''' Create a temp file and move/copy the contents of ``path`` to the temp file. Return the path to the temp file. path The full path to the file whose contents will be moved/copied to a temp file. Whether it's moved or copied depends on the value of ``preserve_inode``. preserve_inode Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). Default is ``True``. ''' temp_file = None # Create the temp file try: temp_file = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to create temp file. " "Exception: {0}".format(exc) ) # use `copy` to preserve the inode of the # original file, and thus preserve hardlinks # to the inode. otherwise, use `move` to # preserve prior behavior, which results in # writing the file to a new inode. if preserve_inode: try: shutil.copy2(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to copy file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: try: shutil.move(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) return temp_file def _starts_till(src, probe, strip_comments=True): ''' Returns True if src and probe at least matches at the beginning till some point. ''' def _strip_comments(txt): ''' Strip possible comments. Usually comments are one or two symbols at the beginning of the line, separated with space ''' buff = txt.split(" ", 1) return len(buff) == 2 and len(buff[0]) < 2 and buff[1] or txt def _to_words(txt): ''' Split by words ''' return txt and [w for w in txt.strip().split(" ") if w.strip()] or txt no_match = -1 equal = 0 if not src or not probe: return no_match src = src.rstrip('\n\r') probe = probe.rstrip('\n\r') if src == probe: return equal src = _to_words(strip_comments and _strip_comments(src) or src) probe = _to_words(strip_comments and _strip_comments(probe) or probe) a_buff, b_buff = len(src) < len(probe) and (src, probe) or (probe, src) b_buff = ' '.join(b_buff) for idx in range(len(a_buff)): prb = ' '.join(a_buff[:-(idx + 1)]) if prb and b_buff.startswith(prb): return idx return no_match def _regex_to_static(src, regex): ''' Expand regular expression to static match. ''' if not src or not regex: return None try: compiled = re.compile(regex, re.DOTALL) src = [line for line in src if compiled.search(line) or line.count(regex)] except Exception as ex: raise CommandExecutionError("{0}: '{1}'".format(_get_error_message(ex), regex)) return src and src or [] def _assert_occurrence(probe, target, amount=1): ''' Raise an exception, if there are different amount of specified occurrences in src. ''' occ = len(probe) if occ > amount: msg = 'more than' elif occ < amount: msg = 'less than' elif not occ: msg = 'no' else: msg = None if msg: raise CommandExecutionError('Found {0} expected occurrences in "{1}" expression'.format(msg, target)) return occ def _set_line_indent(src, line, indent): ''' Indent the line with the source line. ''' if not indent: return line idt = [] for c in src: if c not in ['\t', ' ']: break idt.append(c) return ''.join(idt) + line.lstrip() def _get_eol(line): match = re.search('((?<!\r)\n|\r(?!\n)|\r\n)$', line) return match and match.group() or '' def _set_line_eol(src, line): ''' Add line ending ''' line_ending = _get_eol(src) or os.linesep return line.rstrip() + line_ending def _insert_line_before(idx, body, content, indent): if not idx or (idx and _starts_till(body[idx - 1], content) < 0): cnd = _set_line_indent(body[idx], content, indent) body.insert(idx, cnd) return body def _insert_line_after(idx, body, content, indent): # No duplicates or append, if "after" is the last line next_line = idx + 1 < len(body) and body[idx + 1] or None if next_line is None or _starts_till(next_line, content) < 0: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) return body def line(path, content=None, match=None, mode=None, location=None, before=None, after=None, show_changes=True, backup=False, quiet=False, indent=True): ''' .. versionadded:: 2015.8.0 Edit a line in the configuration file. The ``path`` and ``content`` arguments are required, as well as passing in one of the ``mode`` options. path Filesystem path to the file to be edited. content Content of the line. Allowed to be empty if mode=delete. match Match the target line for an action by a fragment of a string or regular expression. If neither ``before`` nor ``after`` are provided, and ``match`` is also ``None``, match becomes the ``content`` value. mode Defines how to edit a line. One of the following options is required: - ensure If line does not exist, it will be added. This is based on the ``content`` argument. - replace If line already exists, it will be replaced. - delete Delete the line, once found. - insert Insert a line. .. note:: If ``mode=insert`` is used, at least one of the following options must also be defined: ``location``, ``before``, or ``after``. If ``location`` is used, it takes precedence over the other two options. location Defines where to place content in the line. Note this option is only used when ``mode=insert`` is specified. If a location is passed in, it takes precedence over both the ``before`` and ``after`` kwargs. Valid locations are: - start Place the content at the beginning of the file. - end Place the content at the end of the file. before Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. after Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. show_changes Output a unified diff of the old file and the new file. If ``False`` return a boolean if any changes were made. Default is ``True`` .. note:: Using this option will store two copies of the file in-memory (the original version and the edited version) in order to generate the diff. backup Create a backup of the original file with the extension: "Year-Month-Day-Hour-Minutes-Seconds". quiet Do not raise any exceptions. E.g. ignore the fact that the file that is tried to be edited does not exist and nothing really happened. indent Keep indentation with the previous line. This option is not considered when the ``delete`` mode is specified. CLI Example: .. code-block:: bash salt '*' file.line /etc/nsswitch.conf "networks:\tfiles dns" after="hosts:.*?" mode='ensure' .. note:: If an equal sign (``=``) appears in an argument to a Salt command, it is interpreted as a keyword argument in the format of ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.line /path/to/file content="CREATEMAIL_SPOOL=no" match="CREATE_MAIL_SPOOL=yes" mode="replace" ''' path = os.path.realpath(os.path.expanduser(path)) if not os.path.isfile(path): if not quiet: raise CommandExecutionError('File "{0}" does not exists or is not a file.'.format(path)) return False # No changes had happened mode = mode and mode.lower() or mode if mode not in ['insert', 'ensure', 'delete', 'replace']: if mode is None: raise CommandExecutionError('Mode was not defined. How to process the file?') else: raise CommandExecutionError('Unknown mode: "{0}"'.format(mode)) # We've set the content to be empty in the function params but we want to make sure # it gets passed when needed. Feature #37092 empty_content_modes = ['delete'] if mode not in empty_content_modes and content is None: raise CommandExecutionError('Content can only be empty if mode is "{0}"'.format(', '.join(empty_content_modes))) del empty_content_modes # Before/after has privilege. If nothing defined, match is used by content. if before is None and after is None and not match: match = content with salt.utils.files.fopen(path, mode='r') as fp_: body = salt.utils.data.decode_list(fp_.readlines()) body_before = hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() # Add empty line at the end if last line ends with eol. # Allows simpler code if body and _get_eol(body[-1]): body.append('') after = _regex_to_static(body, after) before = _regex_to_static(body, before) match = _regex_to_static(body, match) if os.stat(path).st_size == 0 and mode in ('delete', 'replace'): log.warning('Cannot find text to %s. File \'%s\' is empty.', mode, path) body = [] elif mode == 'delete' and match: body = [line for line in body if line != match[0]] elif mode == 'replace' and match: idx = body.index(match[0]) file_line = body.pop(idx) body.insert(idx, _set_line_indent(file_line, content, indent)) elif mode == 'insert': if not location and not before and not after: raise CommandExecutionError('On insert must be defined either "location" or "before/after" conditions.') if not location: if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') out = [] in_range = False for line in body: if line == after[0]: in_range = True elif line == before[0] and in_range: cnd = _set_line_indent(line, content, indent) out.append(cnd) out.append(line) body = out if before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif after and not before: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: if location == 'start': if body: body.insert(0, _set_line_eol(body[0], content)) else: body.append(content + os.linesep) elif location == 'end': body.append(_set_line_indent(body[-1], content, indent) if body else content) elif mode == 'ensure': if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') is_there = bool([l for l in body if l.count(content)]) if not is_there: idx = body.index(after[0]) if idx < (len(body) - 1) and body[idx + 1] == before[0]: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) else: raise CommandExecutionError('Found more than one line between ' 'boundaries "before" and "after".') elif before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif not before and after: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: raise CommandExecutionError("Wrong conditions? " "Unable to ensure line without knowing " "where to put it before and/or after.") if body: for idx, line in enumerate(body): if not _get_eol(line) and idx+1 < len(body): prev = idx and idx-1 or 1 body[idx] = _set_line_eol(body[prev], line) # We do not need empty line at the end anymore if '' == body[-1]: body.pop() changed = body_before != hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() if backup and changed and __opts__['test'] is False: try: temp_file = _mkstemp_copy(path=path, preserve_inode=True) shutil.move(temp_file, '{0}.{1}'.format(path, time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime()))) except (OSError, IOError) as exc: raise CommandExecutionError("Unable to create the backup file of {0}. Exception: {1}".format(path, exc)) changes_diff = None if changed: if show_changes: with salt.utils.files.fopen(path, 'r') as fp_: path_content = salt.utils.data.decode_list(fp_.read().splitlines(True)) changes_diff = __utils__['stringutils.get_diff'](path_content, body) if __opts__['test'] is False: fh_ = None try: # Make sure we match the file mode from salt.utils.files.fopen if six.PY2 and salt.utils.platform.is_windows(): mode = 'wb' body = salt.utils.data.encode_list(body) else: mode = 'w' body = salt.utils.data.decode_list(body, to_str=True) fh_ = salt.utils.atomicfile.atomic_open(path, mode) fh_.writelines(body) finally: if fh_: fh_.close() return show_changes and changes_diff or changed def replace(path, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, backup='.bak', dry_run=False, search_only=False, show_changes=True, ignore_if_missing=False, preserve_inode=True, backslash_literal=False, ): ''' .. versionadded:: 0.17.0 Replace occurrences of a pattern in a file. If ``show_changes`` is ``True``, then a diff of what changed will be returned, otherwise a ``True`` will be returned when changes are made, and ``False`` when no changes are made. This is a pure Python implementation that wraps Python's :py:func:`~re.sub`. path Filesystem path to the file to be edited. If a symlink is specified, it will be resolved to its target. pattern A regular expression, to be matched using Python's :py:func:`~re.search`. repl The replacement text count : 0 Maximum number of pattern occurrences to be replaced. If count is a positive integer ``n``, only ``n`` occurrences will be replaced, otherwise all occurrences will be replaced. flags (list or int) A list of flags defined in the ``re`` module documentation from the Python standard library. Each list item should be a string that will correlate to the human-friendly flag name. E.g., ``['IGNORECASE', 'MULTILINE']``. Optionally, ``flags`` may be an int, with a value corresponding to the XOR (``|``) of all the desired flags. Defaults to 8 (which supports 'MULTILINE'). bufsize (int or str) How much of the file to buffer into memory at once. The default value ``1`` processes one line at a time. The special value ``file`` may be specified which will read the entire file into memory before processing. append_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True``, and pattern is not found, then the content will be appended to the file. prepend_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True`` and pattern is not found, then the content will be prepended to the file. not_found_content .. versionadded:: 2014.7.0 Content to use for append/prepend if not found. If None (default), uses ``repl``. Useful when ``repl`` uses references to group in pattern. backup : .bak The file extension to use for a backup of the file before editing. Set to ``False`` to skip making a backup. dry_run : False If set to ``True``, no changes will be made to the file, the function will just return the changes that would have been made (or a ``True``/``False`` value if ``show_changes`` is set to ``False``). search_only : False If set to true, this no changes will be performed on the file, and this function will simply return ``True`` if the pattern was matched, and ``False`` if not. show_changes : True If ``True``, return a diff of changes made. Otherwise, return ``True`` if changes were made, and ``False`` if not. .. note:: Using this option will store two copies of the file in memory (the original version and the edited version) in order to generate the diff. This may not normally be a concern, but could impact performance if used with large files. ignore_if_missing : False .. versionadded:: 2015.8.0 If set to ``True``, this function will simply return ``False`` if the file doesn't exist. Otherwise, an error will be thrown. preserve_inode : True .. versionadded:: 2015.8.0 Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). backslash_literal : False .. versionadded:: 2016.11.7 Interpret backslashes as literal backslashes for the repl and not escape characters. This will help when using append/prepend so that the backslashes are not interpreted for the repl on the second run of the state. If an equal sign (``=``) appears in an argument to a Salt command it is interpreted as a keyword argument in the format ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.replace /path/to/file pattern='=' repl=':' salt '*' file.replace /path/to/file pattern="bind-address\\s*=" repl='bind-address:' CLI Examples: .. code-block:: bash salt '*' file.replace /etc/httpd/httpd.conf pattern='LogLevel warn' repl='LogLevel info' salt '*' file.replace /some/file pattern='before' repl='after' flags='[MULTILINE, IGNORECASE]' ''' symlink = False if is_link(path): symlink = True target_path = os.readlink(path) given_path = os.path.expanduser(path) path = os.path.realpath(os.path.expanduser(path)) if not os.path.exists(path): if ignore_if_missing: return False else: raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if search_only and (append_if_not_found or prepend_if_not_found): raise SaltInvocationError( 'search_only cannot be used with append/prepend_if_not_found' ) if append_if_not_found and prepend_if_not_found: raise SaltInvocationError( 'Only one of append and prepend_if_not_found is permitted' ) flags_num = _get_flags(flags) cpattern = re.compile(salt.utils.stringutils.to_bytes(pattern), flags_num) filesize = os.path.getsize(path) if bufsize == 'file': bufsize = filesize # Search the file; track if any changes have been made for the return val has_changes = False orig_file = [] # used for show_changes and change detection new_file = [] # used for show_changes and change detection if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Avoid TypeErrors by forcing repl to be bytearray related to mmap # Replacement text may contains integer: 123 for example repl = salt.utils.stringutils.to_bytes(six.text_type(repl)) if not_found_content: not_found_content = salt.utils.stringutils.to_bytes(not_found_content) found = False temp_file = None content = salt.utils.stringutils.to_unicode(not_found_content) \ if not_found_content and (prepend_if_not_found or append_if_not_found) \ else salt.utils.stringutils.to_unicode(repl) try: # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes r_data = None # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: try: # mmap throws a ValueError if the file is empty. r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) except (ValueError, mmap.error): # size of file in /proc is 0, but contains data r_data = salt.utils.stringutils.to_bytes("".join(r_file)) if search_only: # Just search; bail as early as a match is found if re.search(cpattern, r_data): return True # `with` block handles file closure else: return False else: result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) # found anything? (even if no change) if nrepl > 0: found = True # Identity check the potential change has_changes = True if pattern != repl else has_changes if prepend_if_not_found or append_if_not_found: # Search for content, to avoid pre/appending the # content if it was pre/appended in a previous run. if re.search(salt.utils.stringutils.to_bytes('^{0}($|(?=\r\n))'.format(re.escape(content))), r_data, flags=flags_num): # Content was found, so set found. found = True orig_file = r_data.read(filesize).splitlines(True) \ if isinstance(r_data, mmap.mmap) \ else r_data.splitlines(True) new_file = result.splitlines(True) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() if has_changes and not dry_run: # Write the replacement text in this block. try: # Create a copy to read from and to use as a backup later temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) r_data = None try: # Open the file in write mode with salt.utils.files.fopen(path, mode='w', buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='r', buffering=bufsize) as r_file: r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) try: w_file.write(salt.utils.stringutils.to_str(result)) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if not found and (append_if_not_found or prepend_if_not_found): if not_found_content is None: not_found_content = repl if prepend_if_not_found: new_file.insert(0, not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) else: # append_if_not_found # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(salt.utils.stringutils.to_bytes(os.linesep)): new_file[-1] += salt.utils.stringutils.to_bytes(os.linesep) new_file.append(not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) has_changes = True if not dry_run: try: # Create a copy to read from and for later use as a backup temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line)) finally: fh_.close() if backup and has_changes and not dry_run: # keep the backup only if it was requested # and only if there were any changes backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) if symlink: symlink_backup = '{0}{1}'.format(given_path, backup) target_backup = '{0}{1}'.format(target_path, backup) # Always clobber any existing symlink backup # to match the behaviour of the 'backup' option try: os.symlink(target_backup, symlink_backup) except OSError: os.remove(symlink_backup) os.symlink(target_backup, symlink_backup) except Exception: raise CommandExecutionError( "Unable create backup symlink '{0}'. " "Target was '{1}'. " "Exception: {2}".format(symlink_backup, target_backup, exc) ) elif temp_file: try: os.remove(temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to delete temp file '{0}'. " "Exception: {1}".format(temp_file, exc) ) if not dry_run and not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) differences = __utils__['stringutils.get_diff'](orig_file, new_file) if show_changes: return differences # We may have found a regex line match but don't need to change the line # (for situations where the pattern also matches the repl). Revert the # has_changes flag to False if the final result is unchanged. if not differences: has_changes = False return has_changes def blockreplace(path, marker_start='#-- start managed zone --', marker_end='#-- end managed zone --', content='', append_if_not_found=False, prepend_if_not_found=False, backup='.bak', dry_run=False, show_changes=True, append_newline=False, insert_before_match=None, insert_after_match=None): ''' .. versionadded:: 2014.1.0 Replace content of a text block in a file, delimited by line markers A block of content delimited by comments can help you manage several lines entries without worrying about old entries removal. .. note:: This function will store two copies of the file in-memory (the original version and the edited version) in order to detect changes and only edit the targeted file if necessary. path Filesystem path to the file to be edited marker_start The line content identifying a line as the start of the content block. Note that the whole line containing this marker will be considered, so whitespace or extra content before or after the marker is included in final output marker_end The line content identifying the end of the content block. As of versions 2017.7.5 and 2018.3.1, everything up to the text matching the marker will be replaced, so it's important to ensure that your marker includes the beginning of the text you wish to replace. content The content to be used between the two lines identified by marker_start and marker_stop. append_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be appended to the file. prepend_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be prepended to the file. insert_before_match If markers are not found, this parameter can be set to a regex which will insert the block before the first found occurrence in the file. .. versionadded:: Neon insert_after_match If markers are not found, this parameter can be set to a regex which will insert the block after the first found occurrence in the file. .. versionadded:: Neon backup The file extension to use for a backup of the file if any edit is made. Set to ``False`` to skip making a backup. dry_run : False If ``True``, do not make any edits to the file and simply return the changes that *would* be made. show_changes : True Controls how changes are presented. If ``True``, this function will return a unified diff of the changes made. If False, then it will return a boolean (``True`` if any changes were made, otherwise ``False``). append_newline : False Controls whether or not a newline is appended to the content block. If the value of this argument is ``True`` then a newline will be added to the content block. If it is ``False``, then a newline will *not* be added to the content block. If it is ``None`` then a newline will only be added to the content block if it does not already end in a newline. .. versionadded:: 2016.3.4 .. versionchanged:: 2017.7.5,2018.3.1 New behavior added when value is ``None``. .. versionchanged:: 2019.2.0 The default value of this argument will change to ``None`` to match the behavior of the :py:func:`file.blockreplace state <salt.states.file.blockreplace>` CLI Example: .. code-block:: bash salt '*' file.blockreplace /etc/hosts '#-- start managed zone foobar : DO NOT EDIT --' \\ '#-- end managed zone foobar --' $'10.0.1.1 foo.foobar\\n10.0.1.2 bar.foobar' True ''' exclusive_params = [append_if_not_found, prepend_if_not_found, bool(insert_before_match), bool(insert_after_match)] if sum(exclusive_params) > 1: raise SaltInvocationError( 'Only one of append_if_not_found, prepend_if_not_found,' ' insert_before_match, and insert_after_match is permitted' ) path = os.path.expanduser(path) if not os.path.exists(path): raise SaltInvocationError('File not found: {0}'.format(path)) try: file_encoding = __utils__['files.get_encoding'](path) except CommandExecutionError: file_encoding = None if __utils__['files.is_binary'](path): if not file_encoding: raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if insert_before_match or insert_after_match: if insert_before_match: if not isinstance(insert_before_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_before_match parameter.' ) elif insert_after_match: if not isinstance(insert_after_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_after_match parameter.' ) if append_newline is None and not content.endswith((os.linesep, '\n')): append_newline = True # Split the content into a list of lines, removing newline characters. To # ensure that we handle both Windows and POSIX newlines, first split on # Windows newlines, and then split on POSIX newlines. split_content = [] for win_line in content.split('\r\n'): for content_line in win_line.split('\n'): split_content.append(content_line) line_count = len(split_content) has_changes = False orig_file = [] new_file = [] in_block = False block_found = False linesep = None def _add_content(linesep, lines=None, include_marker_start=True, end_line=None): if lines is None: lines = [] include_marker_start = True if end_line is None: end_line = marker_end end_line = end_line.rstrip('\r\n') + linesep if include_marker_start: lines.append(marker_start + linesep) if split_content: for index, content_line in enumerate(split_content, 1): if index != line_count: lines.append(content_line + linesep) else: # We're on the last line of the content block if append_newline: lines.append(content_line + linesep) lines.append(end_line) else: lines.append(content_line + end_line) else: lines.append(end_line) return lines # We do not use in-place editing to avoid file attrs modifications when # no changes are required and to avoid any file access on a partially # written file. try: fi_file = io.open(path, mode='r', encoding=file_encoding, newline='') for line in fi_file: write_line_to_new_file = True if linesep is None: # Auto-detect line separator if line.endswith('\r\n'): linesep = '\r\n' elif line.endswith('\n'): linesep = '\n' else: # No newline(s) in file, fall back to system's linesep linesep = os.linesep if marker_start in line: # We've entered the content block in_block = True else: if in_block: # We're not going to write the lines from the old file to # the new file until we have exited the block. write_line_to_new_file = False marker_end_pos = line.find(marker_end) if marker_end_pos != -1: # End of block detected in_block = False # We've found and exited the block block_found = True _add_content(linesep, lines=new_file, include_marker_start=False, end_line=line[marker_end_pos:]) # Save the line from the original file orig_file.append(line) if write_line_to_new_file: new_file.append(line) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read from {0}: {1}'.format(path, exc) ) finally: if linesep is None: # If the file was empty, we will not have set linesep yet. Assume # the system's line separator. This is needed for when we # prepend/append later on. linesep = os.linesep try: fi_file.close() except Exception: pass if in_block: # unterminated block => bad, always fail raise CommandExecutionError( 'Unterminated marked block. End of file reached before marker_end.' ) if not block_found: if prepend_if_not_found: # add the markers and content at the beginning of file prepended_content = _add_content(linesep) prepended_content.extend(new_file) new_file = prepended_content block_found = True elif append_if_not_found: # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(linesep): new_file[-1] += linesep # add the markers and content at the end of file _add_content(linesep, lines=new_file) block_found = True elif insert_before_match or insert_after_match: match_regex = insert_before_match or insert_after_match match_idx = [i for i, item in enumerate(orig_file) if re.search(match_regex, item)] if match_idx: match_idx = match_idx[0] for line in _add_content(linesep): if insert_after_match: match_idx += 1 new_file.insert(match_idx, line) if insert_before_match: match_idx += 1 block_found = True if not block_found: raise CommandExecutionError( 'Cannot edit marked block. Markers were not found in file.' ) diff = __utils__['stringutils.get_diff'](orig_file, new_file) has_changes = diff is not '' if has_changes and not dry_run: # changes detected # backup file attrs perms = {} perms['user'] = get_user(path) perms['group'] = get_group(path) perms['mode'] = salt.utils.files.normalize_mode(get_mode(path)) # backup old content if backup is not False: backup_path = '{0}{1}'.format(path, backup) shutil.copy2(path, backup_path) # copy2 does not preserve ownership check_perms(backup_path, None, perms['user'], perms['group'], perms['mode']) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line, encoding=file_encoding)) finally: fh_.close() # this may have overwritten file attrs check_perms(path, None, perms['user'], perms['group'], perms['mode']) if show_changes: return diff return has_changes def search(path, pattern, flags=8, bufsize=1, ignore_if_missing=False, multiline=False ): ''' .. versionadded:: 0.17.0 Search for occurrences of a pattern in a file Except for multiline, params are identical to :py:func:`~salt.modules.file.replace`. multiline If true, inserts 'MULTILINE' into ``flags`` and sets ``bufsize`` to 'file'. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' file.search /etc/crontab 'mymaintenance.sh' ''' if multiline: flags = _add_flags(flags, 'MULTILINE') bufsize = 'file' # This function wraps file.replace on purpose in order to enforce # consistent usage, compatible regex's, expected behavior, *and* bugs. :) # Any enhancements or fixes to one should affect the other. return replace(path, pattern, '', flags=flags, bufsize=bufsize, dry_run=True, search_only=True, show_changes=False, ignore_if_missing=ignore_if_missing) def patch(originalfile, patchfile, options='', dry_run=False): ''' .. versionadded:: 0.10.4 Apply a patch to a file or directory. Equivalent to: .. code-block:: bash patch <options> -i <patchfile> <originalfile> Or, when a directory is patched: .. code-block:: bash patch <options> -i <patchfile> -d <originalfile> -p0 originalfile The full path to the file or directory to be patched patchfile A patch file to apply to ``originalfile`` options Options to pass to patch. CLI Example: .. code-block:: bash salt '*' file.patch /opt/file.txt /tmp/file.txt.patch ''' patchpath = salt.utils.path.which('patch') if not patchpath: raise CommandExecutionError( 'patch executable not found. Is the distribution\'s patch ' 'package installed?' ) cmd = [patchpath] cmd.extend(salt.utils.args.shlex_split(options)) if dry_run: if __grains__['kernel'] in ('FreeBSD', 'OpenBSD'): cmd.append('-C') else: cmd.append('--dry-run') # this argument prevents interactive prompts when the patch fails to apply. # the exit code will still be greater than 0 if that is the case. if '-N' not in cmd and '--forward' not in cmd: cmd.append('--forward') has_rejectfile_option = False for option in cmd: if option == '-r' or option.startswith('-r ') \ or option.startswith('--reject-file'): has_rejectfile_option = True break # by default, patch will write rejected patch files to <filename>.rej. # this option prevents that. if not has_rejectfile_option: cmd.append('--reject-file=-') cmd.extend(['-i', patchfile]) if os.path.isdir(originalfile): cmd.extend(['-d', originalfile]) has_strip_option = False for option in cmd: if option.startswith('-p') or option.startswith('--strip='): has_strip_option = True break if not has_strip_option: cmd.append('--strip=0') else: cmd.append(originalfile) return __salt__['cmd.run_all'](cmd, python_shell=False) def contains(path, text): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the file at ``path`` contains ``text`` CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False stripped_text = six.text_type(text).strip() try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if stripped_text in chunk: return True return False except (IOError, OSError): return False def contains_regex(path, regex, lchar=''): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the given regular expression matches on any line in the text of a given file. If the lchar argument (leading char) is specified, it will strip `lchar` from the left side of each line before trying to match CLI Example: .. code-block:: bash salt '*' file.contains_regex /etc/crontab ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.files.fopen(path, 'r') as target: for line in target: line = salt.utils.stringutils.to_unicode(line) if lchar: line = line.lstrip(lchar) if re.search(regex, line): return True return False except (IOError, OSError): return False def contains_glob(path, glob_expr): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the given glob matches a string in the named file CLI Example: .. code-block:: bash salt '*' file.contains_glob /etc/foobar '*cheese*' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if fnmatch.fnmatch(chunk, glob_expr): return True return False except (IOError, OSError): return False def append(path, *args, **kwargs): ''' .. versionadded:: 0.9.5 Append text to the end of a file path path to file `*args` strings to append to file CLI Example: .. code-block:: bash salt '*' file.append /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.append /etc/motd args='cheese=spam' salt '*' file.append /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) # Largely inspired by Fabric's contrib.files.append() if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] # Make sure we have a newline at the end of the file. Do this in binary # mode so SEEK_END with nonzero offset will work. with salt.utils.files.fopen(path, 'rb+') as ofile: linesep = salt.utils.stringutils.to_bytes(os.linesep) try: ofile.seek(-len(linesep), os.SEEK_END) except IOError as exc: if exc.errno in (errno.EINVAL, errno.ESPIPE): # Empty file, simply append lines at the beginning of the file pass else: raise else: if ofile.read(len(linesep)) != linesep: ofile.seek(0, os.SEEK_END) ofile.write(linesep) # Append lines in text mode with salt.utils.files.fopen(path, 'a') as ofile: for new_line in args: ofile.write( salt.utils.stringutils.to_str( '{0}{1}'.format(new_line, os.linesep) ) ) return 'Wrote {0} lines to "{1}"'.format(len(args), path) def prepend(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Prepend text to the beginning of a file path path to file `*args` strings to prepend to the file CLI Example: .. code-block:: bash salt '*' file.prepend /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.prepend /etc/motd args='cheese=spam' salt '*' file.prepend /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] try: with salt.utils.files.fopen(path) as fhr: contents = [salt.utils.stringutils.to_unicode(line) for line in fhr.readlines()] except IOError: contents = [] preface = [] for line in args: preface.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, 'w') as ofile: contents = preface + contents ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Prepended {0} lines to "{1}"'.format(len(args), path) def write(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Write text to a file, overwriting any existing contents. path path to file `*args` strings to write to the file CLI Example: .. code-block:: bash salt '*' file.write /etc/motd \\ "With all thine offerings thou shalt offer salt." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.write /etc/motd args='cheese=spam' salt '*' file.write /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] contents = [] for line in args: contents.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, "w") as ofile: ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Wrote {0} lines to "{1}"'.format(len(contents), path) def touch(name, atime=None, mtime=None): ''' .. versionadded:: 0.9.5 Just like the ``touch`` command, create a file if it doesn't exist or simply update the atime and mtime if it already does. atime: Access time in Unix epoch time. Set it to 0 to set atime of the file with Unix date of birth. If this parameter isn't set, atime will be set with current time. mtime: Last modification in Unix epoch time. Set it to 0 to set mtime of the file with Unix date of birth. If this parameter isn't set, mtime will be set with current time. CLI Example: .. code-block:: bash salt '*' file.touch /var/log/emptyfile ''' name = os.path.expanduser(name) if atime and atime.isdigit(): atime = int(atime) if mtime and mtime.isdigit(): mtime = int(mtime) try: if not os.path.exists(name): with salt.utils.files.fopen(name, 'a'): pass if atime is None and mtime is None: times = None elif mtime is None and atime is not None: times = (atime, time.time()) elif atime is None and mtime is not None: times = (time.time(), mtime) else: times = (atime, mtime) os.utime(name, times) except TypeError: raise SaltInvocationError('atime and mtime must be integers') except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return os.path.exists(name) def tail(path, lines): ''' .. versionadded:: Neon Read the last n lines from a file path path to file lines number of lines to read CLI Example: .. code-block:: bash salt '*' file.tail /path/to/file 10 ''' path = os.path.expanduser(path) lines_found = [] buffer_size = 4098 if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot tail a binary file: {0}'.format(path)) try: lines = int(lines) except ValueError: raise SaltInvocationError('file.tail: \'lines\' value must be an integer') try: with salt.utils.fopen(path) as tail_fh: blk_cnt = 1 size = os.stat(path).st_size if size > buffer_size: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size), os.linesep) for i in range(lines): while len(data) == 1 and ((blk_cnt * buffer_size) < size): blk_cnt += 1 line = data[0] try: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size) + line, os.linesep) except IOError: tail_fh.seek(0) data = string.split(tail_fh.read(size - (buffer_size * (blk_cnt - 1))) + line, os.linesep) line = data[-1] data.pop() lines_found.append(line) return lines_found[-lines:] except (OSError, IOError): raise CommandExecutionError('Could not tail \'{0}\''.format(path)) def seek_read(path, size, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and read it path path to file seek amount to read at once offset offset to start into the file CLI Example: .. code-block:: bash salt '*' file.seek_read /path/to/file 4096 0 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_RDONLY) try: os.lseek(seek_fh, int(offset), 0) data = os.read(seek_fh, int(size)) finally: os.close(seek_fh) return data def seek_write(path, data, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and write to it path path to file data data to write to file offset position in file to start writing CLI Example: .. code-block:: bash salt '*' file.seek_write /path/to/file 'some data' 4096 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_WRONLY) try: os.lseek(seek_fh, int(offset), 0) ret = os.write(seek_fh, data) os.fsync(seek_fh) finally: os.close(seek_fh) return ret def truncate(path, length): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and delete everything after that point path path to file length offset into file to truncate CLI Example: .. code-block:: bash salt '*' file.truncate /path/to/file 512 ''' path = os.path.expanduser(path) with salt.utils.files.fopen(path, 'rb+') as seek_fh: seek_fh.truncate(int(length)) def link(src, path): ''' .. versionadded:: 2014.1.0 Create a hard link to a file CLI Example: .. code-block:: bash salt '*' file.link /path/to/file /path/to/link ''' src = os.path.expanduser(src) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.link(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def is_link(path): ''' Check if the path is a symbolic link CLI Example: .. code-block:: bash salt '*' file.is_link /path/to/link ''' # This function exists because os.path.islink does not support Windows, # therefore a custom function will need to be called. This function # therefore helps API consistency by providing a single function to call for # both operating systems. return os.path.islink(os.path.expanduser(path)) def symlink(src, path): ''' Create a symbolic link (symlink, soft link) to a file CLI Example: .. code-block:: bash salt '*' file.symlink /path/to/file /path/to/link ''' path = os.path.expanduser(path) try: if os.path.normpath(os.readlink(path)) == os.path.normpath(src): log.debug('link already in correct state: %s -> %s', path, src) return True except OSError: pass if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: os.symlink(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def rename(src, dst): ''' Rename a file or directory CLI Example: .. code-block:: bash salt '*' file.rename /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.rename(src, dst) return True except OSError: raise CommandExecutionError( 'Could not rename \'{0}\' to \'{1}\''.format(src, dst) ) return False def copy(src, dst, recurse=False, remove_existing=False): ''' Copy a file or directory from source to dst In order to copy a directory, the recurse flag is required, and will by default overwrite files in the destination with the same path, and retain all other existing files. (similar to cp -r on unix) remove_existing will remove all files in the target directory, and then copy files from the source. .. note:: The copy function accepts paths that are local to the Salt minion. This function does not support salt://, http://, or the other additional file paths that are supported by :mod:`states.file.managed <salt.states.file.managed>` and :mod:`states.file.recurse <salt.states.file.recurse>`. CLI Example: .. code-block:: bash salt '*' file.copy /path/to/src /path/to/dst salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True remove_existing=True ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') if not os.path.exists(src): raise CommandExecutionError('No such file or directory \'{0}\''.format(src)) if not salt.utils.platform.is_windows(): pre_user = get_user(src) pre_group = get_group(src) pre_mode = salt.utils.files.normalize_mode(get_mode(src)) try: if (os.path.exists(dst) and os.path.isdir(dst)) or os.path.isdir(src): if not recurse: raise SaltInvocationError( "Cannot copy overwriting a directory without recurse flag set to true!") if remove_existing: if os.path.exists(dst): shutil.rmtree(dst) shutil.copytree(src, dst) else: salt.utils.files.recursive_copy(src, dst) else: shutil.copyfile(src, dst) except OSError: raise CommandExecutionError( 'Could not copy \'{0}\' to \'{1}\''.format(src, dst) ) if not salt.utils.platform.is_windows(): check_perms(dst, None, pre_user, pre_group, pre_mode) return True def lstat(path): ''' .. versionadded:: 2014.1.0 Returns the lstat attributes for the given file or dir. Does not support symbolic links. CLI Example: .. code-block:: bash salt '*' file.lstat /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to file must be absolute.') try: lst = os.lstat(path) return dict((key, getattr(lst, key)) for key in ('st_atime', 'st_ctime', 'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid')) except Exception: return {} def access(path, mode): ''' .. versionadded:: 2014.1.0 Test whether the Salt process has the specified access to the file. One of the following modes must be specified: .. code-block::text f: Test the existence of the path r: Test the readability of the path w: Test the writability of the path x: Test whether the path can be executed CLI Example: .. code-block:: bash salt '*' file.access /path/to/file f salt '*' file.access /path/to/file x ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') modes = {'f': os.F_OK, 'r': os.R_OK, 'w': os.W_OK, 'x': os.X_OK} if mode in modes: return os.access(path, modes[mode]) elif mode in six.itervalues(modes): return os.access(path, mode) else: raise SaltInvocationError('Invalid mode specified.') def read(path, binary=False): ''' .. versionadded:: 2017.7.0 Return the content of the file. CLI Example: .. code-block:: bash salt '*' file.read /path/to/file ''' access_mode = 'r' if binary is True: access_mode += 'b' with salt.utils.files.fopen(path, access_mode) as file_obj: return salt.utils.stringutils.to_unicode(file_obj.read()) def readlink(path, canonicalize=False): ''' .. versionadded:: 2014.1.0 Return the path that a symlink points to If canonicalize is set to True, then it return the final target CLI Example: .. code-block:: bash salt '*' file.readlink /path/to/link ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') if not os.path.islink(path): raise SaltInvocationError('A valid link was not specified.') if canonicalize: return os.path.realpath(path) else: return os.readlink(path) def readdir(path): ''' .. versionadded:: 2014.1.0 Return a list containing the contents of a directory CLI Example: .. code-block:: bash salt '*' file.readdir /path/to/dir/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Dir path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') dirents = ['.', '..'] dirents.extend(os.listdir(path)) return dirents def statvfs(path): ''' .. versionadded:: 2014.1.0 Perform a statvfs call against the filesystem that the file resides on CLI Example: .. code-block:: bash salt '*' file.statvfs /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: stv = os.statvfs(path) return dict((key, getattr(stv, key)) for key in ('f_bavail', 'f_bfree', 'f_blocks', 'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag', 'f_frsize', 'f_namemax')) except (OSError, IOError): raise CommandExecutionError('Could not statvfs \'{0}\''.format(path)) return False def stats(path, hash_type=None, follow_symlinks=True): ''' Return a dict containing the stats for a given file CLI Example: .. code-block:: bash salt '*' file.stats /etc/passwd ''' path = os.path.expanduser(path) ret = {} if not os.path.exists(path): try: # Broken symlinks will return False for os.path.exists(), but still # have a uid and gid pstat = os.lstat(path) except OSError: # Not a broken symlink, just a nonexistent path # NOTE: The file.directory state checks the content of the error # message in this exception. Any changes made to the message for this # exception will reflect the file.directory state as well, and will # likely require changes there. raise CommandExecutionError('Path not found: {0}'.format(path)) else: if follow_symlinks: pstat = os.stat(path) else: pstat = os.lstat(path) ret['inode'] = pstat.st_ino ret['uid'] = pstat.st_uid ret['gid'] = pstat.st_gid ret['group'] = gid_to_group(pstat.st_gid) ret['user'] = uid_to_user(pstat.st_uid) ret['atime'] = pstat.st_atime ret['mtime'] = pstat.st_mtime ret['ctime'] = pstat.st_ctime ret['size'] = pstat.st_size ret['mode'] = six.text_type(oct(stat.S_IMODE(pstat.st_mode))) if hash_type: ret['sum'] = get_hash(path, hash_type) ret['type'] = 'file' if stat.S_ISDIR(pstat.st_mode): ret['type'] = 'dir' if stat.S_ISCHR(pstat.st_mode): ret['type'] = 'char' if stat.S_ISBLK(pstat.st_mode): ret['type'] = 'block' if stat.S_ISREG(pstat.st_mode): ret['type'] = 'file' if stat.S_ISLNK(pstat.st_mode): ret['type'] = 'link' if stat.S_ISFIFO(pstat.st_mode): ret['type'] = 'pipe' if stat.S_ISSOCK(pstat.st_mode): ret['type'] = 'socket' ret['target'] = os.path.realpath(path) return ret def rmdir(path): ''' .. versionadded:: 2014.1.0 Remove the specified directory. Fails if a directory is not empty. CLI Example: .. code-block:: bash salt '*' file.rmdir /tmp/foo/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') try: os.rmdir(path) return True except OSError as exc: return exc.strerror def remove(path, **kwargs): ''' Remove the named file. If a directory is supplied, it will be recursively deleted. CLI Example: .. code-block:: bash salt '*' file.remove /tmp/foo ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute: {0}'.format(path)) try: if os.path.isfile(path) or os.path.islink(path): os.remove(path) return True elif os.path.isdir(path): shutil.rmtree(path) return True except (OSError, IOError) as exc: raise CommandExecutionError( 'Could not remove \'{0}\': {1}'.format(path, exc) ) return False def directory_exists(path): ''' Tests to see if path is a valid directory. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.directory_exists /etc ''' return os.path.isdir(os.path.expanduser(path)) def file_exists(path): ''' Tests to see if path is a valid file. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.file_exists /etc/passwd ''' return os.path.isfile(os.path.expanduser(path)) def path_exists_glob(path): ''' Tests to see if path after expansion is a valid path (file or directory). Expansion allows usage of ? * and character ranges []. Tilde expansion is not supported. Returns True/False. .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' file.path_exists_glob /etc/pam*/pass* ''' return True if glob.glob(os.path.expanduser(path)) else False def restorecon(path, recursive=False): ''' Reset the SELinux context on a given path CLI Example: .. code-block:: bash salt '*' file.restorecon /home/user/.ssh/authorized_keys ''' if recursive: cmd = ['restorecon', '-FR', path] else: cmd = ['restorecon', '-F', path] return not __salt__['cmd.retcode'](cmd, python_shell=False) def get_selinux_context(path): ''' Get an SELinux context from a given path CLI Example: .. code-block:: bash salt '*' file.get_selinux_context /etc/hosts ''' out = __salt__['cmd.run'](['ls', '-Z', path], python_shell=False) try: ret = re.search(r'\w+:\w+:\w+:\w+', out).group(0) except AttributeError: ret = ( 'No selinux context information is available for {0}'.format(path) ) return ret def set_selinux_context(path, user=None, role=None, type=None, # pylint: disable=W0622 range=None, # pylint: disable=W0622 persist=False): ''' .. versionchanged:: Neon Added persist option Set a specific SELinux label on a given path CLI Example: .. code-block:: bash salt '*' file.set_selinux_context path <user> <role> <type> <range> salt '*' file.set_selinux_context /etc/yum.repos.d/epel.repo system_u object_r system_conf_t s0 ''' if not any((user, role, type, range)): return False if persist: fcontext_result = __salt__['selinux.fcontext_add_policy'](path, sel_type=type, sel_user=user, sel_level=range) if fcontext_result.get('retcode', None) is not 0: # Problem setting fcontext policy raise CommandExecutionError( 'Problem setting fcontext: {0}'.format(fcontext_result) ) cmd = ['chcon'] if user: cmd.extend(['-u', user]) if role: cmd.extend(['-r', role]) if type: cmd.extend(['-t', type]) if range: cmd.extend(['-l', range]) cmd.append(path) ret = not __salt__['cmd.retcode'](cmd, python_shell=False) if ret: return get_selinux_context(path) else: return ret def source_list(source, source_hash, saltenv): ''' Check the source list and return the source to use CLI Example: .. code-block:: bash salt '*' file.source_list salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' base ''' contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv) if contextkey in __context__: return __context__[contextkey] # get the master file list if isinstance(source, list): mfiles = [(f, saltenv) for f in __salt__['cp.list_master'](saltenv)] mdirs = [(d, saltenv) for d in __salt__['cp.list_master_dirs'](saltenv)] for single in source: if isinstance(single, dict): single = next(iter(single)) path, senv = salt.utils.url.parse(single) if senv: mfiles += [(f, senv) for f in __salt__['cp.list_master'](senv)] mdirs += [(d, senv) for d in __salt__['cp.list_master_dirs'](senv)] ret = None for single in source: if isinstance(single, dict): # check the proto, if it is http or ftp then download the file # to check, if it is salt then check the master list # if it is a local file, check if the file exists if len(single) != 1: continue single_src = next(iter(single)) single_hash = single[single_src] if single[single_src] else source_hash urlparsed_single_src = _urlparse(single_src) # Fix this for Windows if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_single_src.scheme.lower() in string.ascii_lowercase: urlparsed_single_src = _urlparse('file://' + single_src) proto = urlparsed_single_src.scheme if proto == 'salt': path, senv = salt.utils.url.parse(single_src) if not senv: senv = saltenv if (path, saltenv) in mfiles or (path, saltenv) in mdirs: ret = (single_src, single_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single_src, single_hash) break elif proto == 'file' and ( os.path.exists(urlparsed_single_src.netloc) or os.path.exists(urlparsed_single_src.path) or os.path.exists(os.path.join( urlparsed_single_src.netloc, urlparsed_single_src.path))): ret = (single_src, single_hash) break elif single_src.startswith(os.sep) and os.path.exists(single_src): ret = (single_src, single_hash) break elif isinstance(single, six.string_types): path, senv = salt.utils.url.parse(single) if not senv: senv = saltenv if (path, senv) in mfiles or (path, senv) in mdirs: ret = (single, source_hash) break urlparsed_src = _urlparse(single) if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_src.scheme.lower() in string.ascii_lowercase: urlparsed_src = _urlparse('file://' + single) proto = urlparsed_src.scheme if proto == 'file' and ( os.path.exists(urlparsed_src.netloc) or os.path.exists(urlparsed_src.path) or os.path.exists(os.path.join( urlparsed_src.netloc, urlparsed_src.path))): ret = (single, source_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single, source_hash) break elif single.startswith(os.sep) and os.path.exists(single): ret = (single, source_hash) break if ret is None: # None of the list items matched raise CommandExecutionError( 'none of the specified sources were found' ) else: ret = (source, source_hash) __context__[contextkey] = ret return ret def apply_template_on_contents( contents, template, context, defaults, saltenv): ''' Return the contents after applying the templating engine contents template string template template format context Overrides default context variables passed to the template. defaults Default context passed to the template. CLI Example: .. code-block:: bash salt '*' file.apply_template_on_contents \\ contents='This is a {{ template }} string.' \\ template=jinja \\ "context={}" "defaults={'template': 'cool'}" \\ saltenv=base ''' if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) # Apply templating contents = salt.utils.templates.TEMPLATE_REGISTRY[template]( contents, from_str=True, to_str=True, context=context_dict, saltenv=saltenv, grains=__opts__['grains'], pillar=__pillar__, salt=__salt__, opts=__opts__)['data'] if six.PY2: contents = contents.encode('utf-8') elif six.PY3 and isinstance(contents, bytes): # bytes -> str contents = contents.decode('utf-8') else: ret = {} ret['result'] = False ret['comment'] = ('Specified template format {0} is not supported' ).format(template) return ret return contents def get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify=False, **kwargs): ''' Return the managed file data for file.managed name location where the file lives on the server template template format source managed source file source_hash hash of the source file source_hash_name When ``source_hash`` refers to a remote file, this specifies the filename to look for in that file. .. versionadded:: 2016.3.5 user Owner of file group Group owner of file mode Permissions of file attrs Attributes of file .. versionadded:: 2018.3.0 context Variables to add to the template context defaults Default values of for context_dict skip_verify If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' file.get_managed /etc/httpd/conf.d/httpd.conf jinja salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' None root root '755' base None None ''' # Copy the file to the minion and templatize it sfn = '' source_sum = {} def _get_local_file_source_sum(path): ''' DRY helper for getting the source_sum value from a locally cached path. ''' return {'hsum': get_hash(path, form='sha256'), 'hash_type': 'sha256'} # If we have a source defined, let's figure out what the hash is if source: urlparsed_source = _urlparse(source) if urlparsed_source.scheme in salt.utils.files.VALID_PROTOS: parsed_scheme = urlparsed_source.scheme else: parsed_scheme = '' parsed_path = os.path.join( urlparsed_source.netloc, urlparsed_source.path).rstrip(os.sep) unix_local_source = parsed_scheme in ('file', '') if parsed_scheme == '': parsed_path = sfn = source if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg elif parsed_scheme == 'file': sfn = parsed_path if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg if parsed_scheme and parsed_scheme.lower() in string.ascii_lowercase: parsed_path = ':'.join([parsed_scheme, parsed_path]) parsed_scheme = 'file' if parsed_scheme == 'salt': source_sum = __salt__['cp.hash_file'](source, saltenv) if not source_sum: return '', {}, 'Source file {0} not found in saltenv \'{1}\''.format(source, saltenv) elif not source_hash and unix_local_source: source_sum = _get_local_file_source_sum(parsed_path) elif not source_hash and source.startswith(os.sep): # This should happen on Windows source_sum = _get_local_file_source_sum(source) else: if not skip_verify: if source_hash: try: source_sum = get_source_sum(name, source, source_hash, source_hash_name, saltenv) except CommandExecutionError as exc: return '', {}, exc.strerror else: msg = ( 'Unable to verify upstream hash of source file {0}, ' 'please set source_hash or set skip_verify to True' .format(salt.utils.url.redact_http_basic_auth(source)) ) return '', {}, msg if source and (template or parsed_scheme in salt.utils.files.REMOTE_PROTOS): # Check if we have the template or remote file cached cache_refetch = False cached_dest = __salt__['cp.is_cached'](source, saltenv) if cached_dest and (source_hash or skip_verify): htype = source_sum.get('hash_type', 'sha256') cached_sum = get_hash(cached_dest, form=htype) if skip_verify: # prev: if skip_verify or cached_sum == source_sum['hsum']: # but `cached_sum == source_sum['hsum']` is elliptical as prev if sfn = cached_dest source_sum = {'hsum': cached_sum, 'hash_type': htype} elif cached_sum != source_sum.get('hsum', __opts__['hash_type']): cache_refetch = True else: sfn = cached_dest # If we didn't have the template or remote file, or the file has been # updated and the cache has to be refreshed, download the file. if not sfn or cache_refetch: try: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum.get('hsum')) except Exception as exc: # A 404 or other error code may raise an exception, catch it # and return a comment that will fail the calling state. _source = salt.utils.url.redact_http_basic_auth(source) return '', {}, 'Failed to cache {0}: {1}'.format(_source, exc) # If cache failed, sfn will be False, so do a truth check on sfn first # as invoking os.path.exists() on a bool raises a TypeError. if not sfn or not os.path.exists(sfn): _source = salt.utils.url.redact_http_basic_auth(source) return sfn, {}, 'Source file \'{0}\' not found'.format(_source) if sfn == name: raise SaltInvocationError( 'Source file cannot be the same as destination' ) if template: if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, name=name, source=source, user=user, group=group, mode=mode, attrs=attrs, saltenv=saltenv, context=context_dict, salt=__salt__, pillar=__pillar__, grains=__opts__['grains'], opts=__opts__, **kwargs) else: return sfn, {}, ('Specified template format {0} is not supported' ).format(template) if data['result']: sfn = data['data'] hsum = get_hash(sfn, form='sha256') source_sum = {'hash_type': 'sha256', 'hsum': hsum} else: __clean_tmp(sfn) return sfn, {}, data['data'] return sfn, source_sum, '' def extract_hash(hash_fn, hash_type='sha256', file_name='', source='', source_hash_name=None): ''' .. versionchanged:: 2016.3.5 Prior to this version, only the ``file_name`` argument was considered for filename matches in the hash file. This would be problematic for cases in which the user was relying on a remote checksum file that they do not control, and they wished to use a different name for that file on the minion from the filename on the remote server (and in the checksum file). For example, managing ``/tmp/myfile.tar.gz`` when the remote file was at ``https://mydomain.tld/different_name.tar.gz``. The :py:func:`file.managed <salt.states.file.managed>` state now also passes this function the source URI as well as the ``source_hash_name`` (if specified). In cases where ``source_hash_name`` is specified, it takes precedence over both the ``file_name`` and ``source``. When it is not specified, ``file_name`` takes precedence over ``source``. This allows for better capability for matching hashes. .. versionchanged:: 2016.11.0 File name and source URI matches are no longer disregarded when ``source_hash_name`` is specified. They will be used as fallback matches if there is no match to the ``source_hash_name`` value. This routine is called from the :mod:`file.managed <salt.states.file.managed>` state to pull a hash from a remote file. Regular expressions are used line by line on the ``source_hash`` file, to find a potential candidate of the indicated hash type. This avoids many problems of arbitrary file layout rules. It specifically permits pulling hash codes from debian ``*.dsc`` files. If no exact match of a hash and filename are found, then the first hash found (if any) will be returned. If no hashes at all are found, then ``None`` will be returned. For example: .. code-block:: yaml openerp_7.0-latest-1.tar.gz: file.managed: - name: /tmp/openerp_7.0-20121227-075624-1_all.deb - source: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.tar.gz - source_hash: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.dsc CLI Example: .. code-block:: bash salt '*' file.extract_hash /path/to/hash/file sha512 /etc/foo ''' hash_len = HASHES.get(hash_type) if hash_len is None: if hash_type: log.warning( 'file.extract_hash: Unsupported hash_type \'%s\', falling ' 'back to matching any supported hash_type', hash_type ) hash_type = '' hash_len_expr = '{0},{1}'.format(min(HASHES_REVMAP), max(HASHES_REVMAP)) else: hash_len_expr = six.text_type(hash_len) filename_separators = string.whitespace + r'\/' if source_hash_name: if not isinstance(source_hash_name, six.string_types): source_hash_name = six.text_type(source_hash_name) source_hash_name_idx = (len(source_hash_name) + 1) * -1 log.debug( 'file.extract_hash: Extracting %s hash for file matching ' 'source_hash_name \'%s\'', 'any supported' if not hash_type else hash_type, source_hash_name ) if file_name: if not isinstance(file_name, six.string_types): file_name = six.text_type(file_name) file_name_basename = os.path.basename(file_name) file_name_idx = (len(file_name_basename) + 1) * -1 if source: if not isinstance(source, six.string_types): source = six.text_type(source) urlparsed_source = _urlparse(source) source_basename = os.path.basename( urlparsed_source.path or urlparsed_source.netloc ) source_idx = (len(source_basename) + 1) * -1 basename_searches = [x for x in (file_name, source) if x] if basename_searches: log.debug( 'file.extract_hash: %s %s hash for file matching%s: %s', 'If no source_hash_name match found, will extract' if source_hash_name else 'Extracting', 'any supported' if not hash_type else hash_type, '' if len(basename_searches) == 1 else ' either of the following', ', '.join(basename_searches) ) partial = None found = {} with salt.utils.files.fopen(hash_fn, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line.strip()) hash_re = r'(?i)(?<![a-z0-9])([a-f0-9]{' + hash_len_expr + '})(?![a-z0-9])' hash_match = re.search(hash_re, line) matched = None if hash_match: matched_hsum = hash_match.group(1) if matched_hsum is not None: matched_type = HASHES_REVMAP.get(len(matched_hsum)) if matched_type is None: # There was a match, but it's not of the correct length # to match one of the supported hash types. matched = None else: matched = {'hsum': matched_hsum, 'hash_type': matched_type} if matched is None: log.debug( 'file.extract_hash: In line \'%s\', no %shash found', line, '' if not hash_type else hash_type + ' ' ) continue if partial is None: partial = matched def _add_to_matches(found, line, match_type, value, matched): log.debug( 'file.extract_hash: Line \'%s\' matches %s \'%s\'', line, match_type, value ) found.setdefault(match_type, []).append(matched) hash_matched = False if source_hash_name: if line.endswith(source_hash_name): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[source_hash_name_idx] in string.whitespace: _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source_hash_name) + r'\s+', line): _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True if file_name: if line.endswith(file_name_basename): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[file_name_idx] in filename_separators: _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(file_name) + r'\s+', line): _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True if source: if line.endswith(source_basename): # Same as above, we can't just do an rsplit here. try: if line[source_idx] in filename_separators: _add_to_matches(found, line, 'source', source, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source) + r'\s+', line): _add_to_matches(found, line, 'source', source, matched) hash_matched = True if not hash_matched: log.debug( 'file.extract_hash: Line \'%s\' contains %s hash ' '\'%s\', but line did not meet the search criteria', line, matched['hash_type'], matched['hsum'] ) for found_type, found_str in (('source_hash_name', source_hash_name), ('file_name', file_name), ('source', source)): if found_type in found: if len(found[found_type]) > 1: log.debug( 'file.extract_hash: Multiple %s matches for %s: %s', found_type, found_str, ', '.join( ['{0} ({1})'.format(x['hsum'], x['hash_type']) for x in found[found_type]] ) ) ret = found[found_type][0] log.debug( 'file.extract_hash: Returning %s hash \'%s\' as a match of %s', ret['hash_type'], ret['hsum'], found_str ) return ret if partial: log.debug( 'file.extract_hash: Returning the partially identified %s hash ' '\'%s\'', partial['hash_type'], partial['hsum'] ) return partial log.debug('file.extract_hash: No matches, returning None') return None def check_perms(name, ret, user, group, mode, attrs=None, follow_symlinks=False, seuser=None, serole=None, setype=None, serange=None): ''' .. versionchanged:: Neon Added selinux options Check the permissions on files, modify attributes and chown if needed. File attributes are only verified if lsattr(1) is installed. CLI Example: .. code-block:: bash salt '*' file.check_perms /etc/sudoers '{}' root root 400 ai .. versionchanged:: 2014.1.3 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': [], 'result': True} orig_comment = '' else: orig_comment = ret['comment'] ret['comment'] = [] # Check permissions perms = {} cur = stats(name, follow_symlinks=follow_symlinks) perms['luser'] = cur['user'] perms['lgroup'] = cur['group'] perms['lmode'] = salt.utils.files.normalize_mode(cur['mode']) is_dir = os.path.isdir(name) is_link = os.path.islink(name) if attrs is not None \ and not salt.utils.platform.is_windows() \ and not is_dir and not is_link: try: lattrs = lsattr(name) except SaltInvocationError: lattrs = None if lattrs is not None: # List attributes on file perms['lattrs'] = ''.join(lattrs.get(name, '')) # Remove attributes on file so changes can be enforced. if perms['lattrs']: chattr(name, operator='remove', attributes=perms['lattrs']) # user/group changes if needed, then check if it worked if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid(perms['luser']) ) or ( not salt.utils.platform.is_windows() and user != perms['luser'] ): perms['cuser'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid(perms['lgroup']) ) or ( not salt.utils.platform.is_windows() and group != perms['lgroup'] ): perms['cgroup'] = group if 'cuser' in perms or 'cgroup' in perms: if not __opts__['test']: if os.path.islink(name) and not follow_symlinks: chown_func = lchown else: chown_func = chown if user is None: user = perms['luser'] if group is None: group = perms['lgroup'] try: chown_func(name, user, group) # Python os.chown() does reset the suid and sgid, # that's why setting the right mode again is needed here. set_mode(name, mode) except OSError: ret['result'] = False if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid( get_user(name, follow_symlinks=follow_symlinks)) and user != '' ) or ( not salt.utils.platform.is_windows() and user != get_user(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['user'] = user else: ret['result'] = False ret['comment'].append('Failed to change user to {0}' .format(user)) elif 'cuser' in perms and user != '': ret['changes']['user'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid( get_group(name, follow_symlinks=follow_symlinks)) and user != '') or ( not salt.utils.platform.is_windows() and group != get_group(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['group'] = group else: ret['result'] = False ret['comment'].append('Failed to change group to {0}' .format(group)) elif 'cgroup' in perms and user != '': ret['changes']['group'] = group if not salt.utils.platform.is_windows() and not is_dir: # Replace attributes on file if it had been removed if perms.get('lattrs', ''): chattr(name, operator='add', attributes=perms['lattrs']) # Mode changes if needed if mode is not None: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: mode = salt.utils.files.normalize_mode(mode) if mode != perms['lmode']: if __opts__['test'] is True: ret['changes']['mode'] = mode else: set_mode(name, mode) if mode != salt.utils.files.normalize_mode(get_mode(name)): ret['result'] = False ret['comment'].append( 'Failed to change mode to {0}'.format(mode) ) else: ret['changes']['mode'] = mode # Modify attributes of file if needed if attrs is not None and not is_dir: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if diff_attrs[0] is not None or diff_attrs[1] is not None: if __opts__['test'] is True: ret['changes']['attrs'] = attrs else: if diff_attrs[0] is not None: chattr(name, operator="add", attributes=diff_attrs[0]) if diff_attrs[1] is not None: chattr(name, operator="remove", attributes=diff_attrs[1]) cmp_attrs = _cmp_attrs(name, attrs) if cmp_attrs[0] is not None or cmp_attrs[1] is not None: ret['result'] = False ret['comment'].append( 'Failed to change attributes to {0}'.format(attrs) ) else: ret['changes']['attrs'] = attrs # Set selinux attributes if needed if salt.utils.platform.is_linux() and (seuser or serole or setype or serange): selinux_error = False try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError: log.error('Unable to get current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to get selinux attributes' ) selinux_error = True if not selinux_error: requested_seuser = None requested_serole = None requested_setype = None requested_serange = None # Only set new selinux variables if updates are needed if seuser and seuser != current_seuser: requested_seuser = seuser if serole and serole != current_serole: requested_serole = serole if setype and setype != current_setype: requested_setype = setype if serange and serange != current_serange: requested_serange = serange if requested_seuser or requested_serole or requested_setype or requested_serange: # selinux updates needed, prep changes output selinux_change_new = '' selinux_change_orig = '' if requested_seuser: selinux_change_new += "User: {0} ".format(requested_seuser) selinux_change_orig += "User: {0} ".format(current_seuser) if requested_serole: selinux_change_new += "Role: {0} ".format(requested_serole) selinux_change_orig += "Role: {0} ".format(current_serole) if requested_setype: selinux_change_new += "Type: {0} ".format(requested_setype) selinux_change_orig += "Type: {0} ".format(current_setype) if requested_serange: selinux_change_new += "Range: {0} ".format(requested_serange) selinux_change_orig += "Range: {0} ".format(current_serange) if __opts__['test']: ret['comment'] = 'File {0} selinux context to be updated'.format(name) ret['result'] = None ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} else: try: # set_selinux_context requires type to be set on any other change if (requested_seuser or requested_serole or requested_serange) and not requested_setype: requested_setype = current_setype result = set_selinux_context(name, user=requested_seuser, role=requested_serole, type=requested_setype, range=requested_serange, persist=True) log.debug('selinux set result: %s', result) current_seuser, current_serole, current_setype, current_serange = result.split(':') except ValueError: log.error('Unable to set current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to set selinux attributes' ) selinux_error = True if not selinux_error: ret['comment'].append('The file {0} is set to be changed'.format(name)) if requested_seuser: if current_seuser != requested_seuser: ret['comment'].append("Unable to update seuser context") ret['result'] = False if requested_serole: if current_serole != requested_serole: ret['comment'].append("Unable to update serole context") ret['result'] = False if requested_setype: if current_setype != requested_setype: ret['comment'].append("Unable to update setype context") ret['result'] = False if requested_serange: if current_serange != requested_serange: ret['comment'].append("Unable to update serange context") ret['result'] = False ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} # Only combine the comment list into a string # after all comments are added above if isinstance(orig_comment, six.string_types): if orig_comment: ret['comment'].insert(0, orig_comment) ret['comment'] = '; '.join(ret['comment']) # Set result to None at the very end of the function, # after all changes have been recorded above if __opts__['test'] is True and ret['changes']: ret['result'] = None return ret, perms def check_managed( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Check to see what changes need to be made for a file CLI Example: .. code-block:: bash salt '*' file.check_managed /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) if comments: __clean_tmp(sfn) return False, comments changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) # Ignore permission for files written temporary directories # Files in any path will still be set correctly using get_managed() if name.startswith(tempfile.gettempdir()): for key in ['user', 'group', 'mode']: changes.pop(key, None) __clean_tmp(sfn) if changes: log.info(changes) comments = ['The following values are set to be changed:\n'] comments.extend('{0}: {1}\n'.format(key, val) for key, val in six.iteritems(changes)) return None, ''.join(comments) return True, 'The file {0} is in the correct state'.format(name) def check_managed_changes( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, keep_mode=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Return a dictionary of what changes need to be made for a file .. versionchanged:: Neon selinux attributes added CLI Example: .. code-block:: bash salt '*' file.check_managed_changes /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if comments: __clean_tmp(sfn) raise CommandExecutionError(comments) if sfn and source and keep_mode: if _urlparse(source).scheme in ('salt', 'file') \ or source.startswith('/'): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) __clean_tmp(sfn) return changes def check_file_meta( name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents=None, seuser=None, serole=None, setype=None, serange=None): ''' Check for the changes in the file metadata. CLI Example: .. code-block:: bash salt '*' file.check_file_meta /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' base .. note:: Supported hash types include sha512, sha384, sha256, sha224, sha1, and md5. name Path to file destination sfn Template-processed source file contents source URL to file source source_sum File checksum information as a dictionary .. code-block:: yaml {hash_type: md5, hsum: <md5sum>} user Destination file user owner group Destination file group owner mode Destination file permissions mode attrs Destination file attributes .. versionadded:: 2018.3.0 saltenv Salt environment used to resolve source files contents File contents seuser selinux user attribute .. versionadded:: Neon serole selinux role attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon ''' changes = {} if not source_sum: source_sum = dict() try: lstats = stats(name, hash_type=source_sum.get('hash_type', None), follow_symlinks=False) except CommandExecutionError: lstats = {} if not lstats: changes['newfile'] = name return changes if 'hsum' in source_sum: if source_sum['hsum'] != lstats['sum']: if not sfn and source: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum['hsum']) if sfn: try: changes['diff'] = get_diff( name, sfn, template=True, show_filenames=False) except CommandExecutionError as exc: changes['diff'] = exc.strerror else: changes['sum'] = 'Checksum differs' if contents is not None: # Write a tempfile with the static contents tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'w') as tmp_: tmp_.write(salt.utils.stringutils.to_str(contents)) # Compare the static contents with the named file try: differences = get_diff(name, tmp, show_filenames=False) except CommandExecutionError as exc: log.error('Failed to diff files: %s', exc) differences = exc.strerror __clean_tmp(tmp) if differences: if __salt__['config.option']('obfuscate_templates'): changes['diff'] = '<Obfuscated Template>' else: changes['diff'] = differences if not salt.utils.platform.is_windows(): # Check owner if (user is not None and user != lstats['user'] and user != lstats['uid']): changes['user'] = user # Check group if (group is not None and group != lstats['group'] and group != lstats['gid']): changes['group'] = group # Normalize the file mode smode = salt.utils.files.normalize_mode(lstats['mode']) mode = salt.utils.files.normalize_mode(mode) if mode is not None and mode != smode: changes['mode'] = mode if attrs: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if attrs is not None \ and (diff_attrs[0] is not None or diff_attrs[1] is not None): changes['attrs'] = attrs # Check selinux if seuser or serole or setype or serange: try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError as exc: log.error('Unable to get current selinux attributes') changes['selinux'] = exc.strerror if seuser and seuser != current_seuser: changes['selinux'] = {"user": seuser} if serole and serole != current_serole: changes['selinux'] = {"role": serole} if setype and setype != current_setype: changes['selinux'] = {"type": setype} if serange and serange != current_serange: changes['selinux'] = {"range": serange} return changes def get_diff(file1, file2, saltenv='base', show_filenames=True, show_changes=True, template=False, source_hash_file1=None, source_hash_file2=None): ''' Return unified diff of two files file1 The first file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, thuis had to be a file local to the minion. file2 The second file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, this had to be a file on the salt fileserver (i.e. ``salt://somefile.txt``) show_filenames : True Set to ``False`` to hide the filenames in the top two lines of the diff. show_changes : True If set to ``False``, and there are differences, then instead of a diff a simple message stating that show_changes is set to ``False`` will be returned. template : False Set to ``True`` if two templates are being compared. This is not useful except for within states, with the ``obfuscate_templates`` option set to ``True``. .. versionadded:: 2018.3.0 source_hash_file1 If ``file1`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 source_hash_file2 If ``file2`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 CLI Examples: .. code-block:: bash salt '*' file.get_diff /home/fred/.vimrc salt://users/fred/.vimrc salt '*' file.get_diff /tmp/foo.txt /tmp/bar.txt ''' files = (file1, file2) source_hashes = (source_hash_file1, source_hash_file2) paths = [] errors = [] for filename, source_hash in zip(files, source_hashes): try: # Local file paths will just return the same path back when passed # to cp.cache_file. cached_path = __salt__['cp.cache_file'](filename, saltenv, source_hash=source_hash) if cached_path is False: errors.append( 'File {0} not found'.format( salt.utils.stringutils.to_unicode(filename) ) ) continue paths.append(cached_path) except MinionError as exc: errors.append(salt.utils.stringutils.to_unicode(exc.__str__())) continue if errors: raise CommandExecutionError( 'Failed to cache one or more files', info=errors ) args = [] for filename in paths: try: with salt.utils.files.fopen(filename, 'rb') as fp_: args.append(fp_.readlines()) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read {0}: {1}'.format( salt.utils.stringutils.to_unicode(filename), exc.strerror ) ) if args[0] != args[1]: if template and __salt__['config.option']('obfuscate_templates'): ret = '<Obfuscated Template>' elif not show_changes: ret = '<show_changes=False>' else: bdiff = _binary_replace(*paths) # pylint: disable=no-value-for-parameter if bdiff: ret = bdiff else: if show_filenames: args.extend(paths) ret = __utils__['stringutils.get_diff'](*args) return ret return '' def manage_file(name, sfn, ret, source, source_sum, user, group, mode, attrs, saltenv, backup, makedirs=False, template=None, # pylint: disable=W0613 show_changes=True, contents=None, dir_mode=None, follow_symlinks=True, skip_verify=False, keep_mode=False, encoding=None, encoding_errors='strict', seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Checks the destination against what was retrieved with get_managed and makes the appropriate modifications (if necessary). name location to place the file sfn location of cached file on the minion This is the path to the file stored on the minion. This file is placed on the minion using cp.cache_file. If the hash sum of that file matches the source_sum, we do not transfer the file to the minion again. This file is then grabbed and if it has template set, it renders the file to be placed into the correct place on the system using salt.files.utils.copyfile() ret The initial state return data structure. Pass in ``None`` to use the default structure. source file reference on the master source_sum sum hash for source user user owner group group owner backup backup_mode attrs attributes to be set on file: '' means remove all of them .. versionadded:: 2018.3.0 makedirs make directories if they do not exist template format of templating show_changes Include diff in state return contents: contents to be placed in the file dir_mode mode for directories created with makedirs skip_verify : False If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 keep_mode : False If ``True``, and the ``source`` is a file from the Salt fileserver (or a local file on the minion), the mode of the destination file will be set to the mode of the source file. .. note:: keep_mode does not work with salt-ssh. As a consequence of how the files are transferred to the minion, and the inability to connect back to the master with salt-ssh, salt is unable to stat the file as it exists on the fileserver and thus cannot mirror the mode on the salt-ssh minion encoding If specified, then the specified encoding will be used. Otherwise, the file will be encoded using the system locale (usually UTF-8). See https://docs.python.org/3/library/codecs.html#standard-encodings for the list of available encodings. .. versionadded:: 2017.7.0 encoding_errors : 'strict' Default is ```'strict'```. See https://docs.python.org/2/library/codecs.html#codec-base-classes for the error handling schemes. .. versionadded:: 2017.7.0 seuser selinux user attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon CLI Example: .. code-block:: bash salt '*' file.manage_file /etc/httpd/conf.d/httpd.conf '' '{}' salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' '' base '' .. versionchanged:: 2014.7.0 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if source: if not sfn: # File is not present, cache it sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) htype = source_sum.get('hash_type', __opts__['hash_type']) # Recalculate source sum now that file has been cached source_sum = { 'hash_type': htype, 'hsum': get_hash(sfn, form=htype) } if keep_mode: if _urlparse(source).scheme in ('salt', 'file', ''): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) # Check changes if the target file exists if os.path.isfile(name) or os.path.islink(name): if os.path.islink(name) and follow_symlinks: real_name = os.path.realpath(name) else: real_name = name # Only test the checksums on files with managed contents if source and not (not follow_symlinks and os.path.islink(real_name)): name_sum = get_hash(real_name, source_sum.get('hash_type', __opts__['hash_type'])) else: name_sum = None # Check if file needs to be replaced if source and (name_sum is None or source_sum.get('hsum', __opts__['hash_type']) != name_sum): if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server or local # source, and we are not skipping checksum verification, then # verify that it matches the specified checksum. if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3}). If the \'source_hash\' value ' 'refers to a remote file with multiple possible ' 'matches, then it may be necessary to set ' '\'source_hash_name\'.'.format( source_sum['hash_type'], source, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # Print a diff equivalent to diff -u old new if __salt__['config.option']('obfuscate_templates'): ret['changes']['diff'] = '<Obfuscated Template>' elif not show_changes: ret['changes']['diff'] = '<show_changes=False>' else: try: ret['changes']['diff'] = get_diff( real_name, sfn, show_filenames=False) except CommandExecutionError as exc: ret['changes']['diff'] = exc.strerror # Pre requisites are met, and the file needs to be replaced, do it try: salt.utils.files.copyfile(sfn, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) try: differences = get_diff( real_name, tmp, show_filenames=False, show_changes=show_changes, template=True) except CommandExecutionError as exc: ret.setdefault('warnings', []).append( 'Failed to detect changes to file: {0}'.format(exc.strerror) ) differences = '' if differences: ret['changes']['diff'] = differences # Pre requisites are met, the file needs to be replaced, do it try: salt.utils.files.copyfile(tmp, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(tmp) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) __clean_tmp(tmp) # Check for changing symlink to regular file here if os.path.islink(name) and not follow_symlinks: if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret try: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) ret['changes']['diff'] = \ 'Replace symbolic link with regular file' if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, follow_symlinks, seuser=seuser, serole=serole, setype=setype, serange=serange) if ret['changes']: ret['comment'] = 'File {0} updated'.format( salt.utils.data.decode(name) ) elif not ret['changes'] and ret['result']: ret['comment'] = 'File {0} is in the correct state'.format( salt.utils.data.decode(name) ) if sfn: __clean_tmp(sfn) return ret else: # target file does not exist contain_dir = os.path.dirname(name) def _set_mode_and_make_dirs(name, dir_mode, mode, user, group): # check for existence of windows drive letter if salt.utils.platform.is_windows(): drive, _ = os.path.splitdrive(name) if drive and not os.path.exists(drive): __clean_tmp(sfn) return _error(ret, '{0} drive not present'.format(drive)) if dir_mode is None and mode is not None: # Add execute bit to each nonzero digit in the mode, if # dir_mode was not specified. Otherwise, any # directories created with makedirs_() below can't be # listed via a shell. mode_list = [x for x in six.text_type(mode)][-3:] for idx in range(len(mode_list)): if mode_list[idx] != '0': mode_list[idx] = six.text_type(int(mode_list[idx]) | 1) dir_mode = ''.join(mode_list) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 makedirs_( path=name, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: makedirs_(name, user=user, group=group, mode=dir_mode) if source: # Apply the new file if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # It is a new file, set the diff accordingly ret['changes']['diff'] = 'New file' if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') else: # source != True if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') # Create the file, user rw-only if mode will be set to prevent # a small security race problem before the permissions are set with salt.utils.files.set_umask(0o077 if mode else None): # Create a new file when test is False and source is None if contents is None: if not __opts__['test']: if touch(name): ret['changes']['new'] = 'file {0} created'.format(name) ret['comment'] = 'Empty file' else: return _error( ret, 'Empty file {0} not created'.format(name) ) else: if not __opts__['test']: if touch(name): ret['changes']['diff'] = 'New file' else: return _error( ret, 'File {0} not created'.format(name) ) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) # Copy into place salt.utils.files.copyfile(tmp, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(tmp) # Now copy the file contents if there is a source file elif sfn: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(sfn) # This is a new file, if no mode specified, use the umask to figure # out what mode to use for the new file. if mode is None and not salt.utils.platform.is_windows(): # Get current umask mask = salt.utils.files.get_umask() # Calculate the mode value that results from the umask mode = oct((0o777 ^ mask) & 0o666) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, seuser=seuser, serole=serole, setype=setype, serange=serange) if not ret['comment']: ret['comment'] = 'File ' + name + ' updated' if __opts__['test']: ret['comment'] = 'File ' + name + ' not updated' elif not ret['changes'] and ret['result']: ret['comment'] = 'File ' + name + ' is in the correct state' if sfn: __clean_tmp(sfn) return ret def mkdir(dir_path, user=None, group=None, mode=None): ''' Ensure that a directory is available. CLI Example: .. code-block:: bash salt '*' file.mkdir /opt/jetty/context ''' dir_path = os.path.expanduser(dir_path) directory = os.path.normpath(dir_path) if not os.path.isdir(directory): # If a caller such as managed() is invoked with makedirs=True, make # sure that any created dirs are created with the same user and group # to follow the principal of least surprise method. makedirs_perms(directory, user, group, mode) return True def makedirs_(path, user=None, group=None, mode=None): ''' Ensure that the directory containing this path is available. .. note:: The path must end with a trailing slash otherwise the directory/directories will be created up to the parent directory. For example if path is ``/opt/code``, then it would be treated as ``/opt/`` but if the path ends with a trailing slash like ``/opt/code/``, then it would be treated as ``/opt/code/``. CLI Example: .. code-block:: bash salt '*' file.makedirs /opt/code/ ''' path = os.path.expanduser(path) if mode: mode = salt.utils.files.normalize_mode(mode) # walk up the directory structure until we find the first existing # directory dirname = os.path.normpath(os.path.dirname(path)) if os.path.isdir(dirname): # There's nothing for us to do msg = 'Directory \'{0}\' already exists'.format(dirname) log.debug(msg) return msg if os.path.exists(dirname): msg = 'The path \'{0}\' already exists and is not a directory'.format( dirname ) log.debug(msg) return msg directories_to_create = [] while True: if os.path.isdir(dirname): break directories_to_create.append(dirname) current_dirname = dirname dirname = os.path.dirname(dirname) if current_dirname == dirname: raise SaltInvocationError( 'Recursive creation for path \'{0}\' would result in an ' 'infinite loop. Please use an absolute path.'.format(dirname) ) # create parent directories from the topmost to the most deeply nested one directories_to_create.reverse() for directory_to_create in directories_to_create: # all directories have the user, group and mode set!! log.debug('Creating directory: %s', directory_to_create) mkdir(directory_to_create, user=user, group=group, mode=mode) def makedirs_perms(name, user=None, group=None, mode='0755'): ''' Taken and modified from os.makedirs to set user, group and mode for each directory created. CLI Example: .. code-block:: bash salt '*' file.makedirs_perms /opt/code ''' name = os.path.expanduser(name) path = os.path head, tail = path.split(name) if not tail: head, tail = path.split(head) if head and tail and not path.exists(head): try: makedirs_perms(head, user, group, mode) except OSError as exc: # be happy if someone already created the path if exc.errno != errno.EEXIST: raise if tail == os.curdir: # xxx/newdir/. exists if xxx/newdir exists return os.mkdir(name) check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) def get_devmm(name): ''' Get major/minor info from a device CLI Example: .. code-block:: bash salt '*' file.get_devmm /dev/chr ''' name = os.path.expanduser(name) if is_chrdev(name) or is_blkdev(name): stat_structure = os.stat(name) return ( os.major(stat_structure.st_rdev), os.minor(stat_structure.st_rdev)) else: return (0, 0) def is_chrdev(name): ''' Check if a file exists and is a character device. CLI Example: .. code-block:: bash salt '*' file.is_chrdev /dev/chr ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the character device does not exist in the first place return False else: raise return stat.S_ISCHR(stat_structure.st_mode) def mknod_chrdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a character device. CLI Example: .. code-block:: bash salt '*' file.mknod_chrdev /dev/chr 180 31 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating character device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFCHR, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created character device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_blkdev(name): ''' Check if a file exists and is a block device. CLI Example: .. code-block:: bash salt '*' file.is_blkdev /dev/blk ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the block device does not exist in the first place return False else: raise return stat.S_ISBLK(stat_structure.st_mode) def mknod_blkdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a block device. CLI Example: .. code-block:: bash salt '*' file.mknod_blkdev /dev/blk 8 999 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating block device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFBLK, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created block device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_fifo(name): ''' Check if a file exists and is a FIFO. CLI Example: .. code-block:: bash salt '*' file.is_fifo /dev/fifo ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the fifo does not exist in the first place return False else: raise return stat.S_ISFIFO(stat_structure.st_mode) def mknod_fifo(name, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a FIFO pipe. CLI Example: .. code-block:: bash salt '*' file.mknod_fifo /dev/fifo ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating FIFO name: %s', name) try: if __opts__['test']: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = None else: if os.mkfifo(name, int(six.text_type(mode).lstrip('0Oo'), 8)) is None: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created fifo check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def mknod(name, ntype, major=0, minor=0, user=None, group=None, mode='0600'): ''' .. versionadded:: 0.17.0 Create a block device, character device, or fifo pipe. Identical to the gnu mknod. CLI Examples: .. code-block:: bash salt '*' file.mknod /dev/chr c 180 31 salt '*' file.mknod /dev/blk b 8 999 salt '*' file.nknod /dev/fifo p ''' ret = False makedirs_(name, user, group) if ntype == 'c': ret = mknod_chrdev(name, major, minor, user, group, mode) elif ntype == 'b': ret = mknod_blkdev(name, major, minor, user, group, mode) elif ntype == 'p': ret = mknod_fifo(name, user, group, mode) else: raise SaltInvocationError( 'Node type unavailable: \'{0}\'. Available node types are ' 'character (\'c\'), block (\'b\'), and pipe (\'p\').'.format(ntype) ) return ret def list_backups(path, limit=None): ''' .. versionadded:: 0.17.0 Lists the previous versions of a file backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups /foo/bar/baz.txt ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows src_dir = parent_dir.replace(':', '_') else: src_dir = parent_dir[1:] # Figure out full path of location of backup file in minion cache bkdir = os.path.join(bkroot, src_dir) if not os.path.isdir(bkdir): return {} files = {} for fname in [x for x in os.listdir(bkdir) if os.path.isfile(os.path.join(bkdir, x))]: if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows strpfmt = '{0}_%a_%b_%d_%H-%M-%S_%f_%Y'.format(basename) else: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(fname, strpfmt) except ValueError: # File didn't match the strp format string, so it's not a backup # for this file. Move on to the next one. continue if salt.utils.platform.is_windows(): str_format = '%a %b %d %Y %H-%M-%S.%f' else: str_format = '%a %b %d %Y %H:%M:%S.%f' files.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime(str_format) location = os.path.join(bkdir, fname) files[timestamp]['Size'] = os.stat(location).st_size files[timestamp]['Location'] = location return dict(list(zip( list(range(len(files))), [files[x] for x in sorted(files, reverse=True)[:limit]] ))) list_backup = salt.utils.functools.alias_function(list_backups, 'list_backup') def list_backups_dir(path, limit=None): ''' Lists the previous versions of a directory backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The directory on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups_dir /foo/bar/baz/ ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups_dir: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) # Figure out full path of location of backup folder in minion cache bkdir = os.path.join(bkroot, parent_dir[1:]) if not os.path.isdir(bkdir): return {} files = {} f = dict([(i, len(list(n))) for i, n in itertools.groupby([x.split("_")[0] for x in sorted(os.listdir(bkdir))])]) ff = os.listdir(bkdir) for i, n in six.iteritems(f): ssfile = {} for x in sorted(ff): basename = x.split('_')[0] if i == basename: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(x, strpfmt) except ValueError: # Folder didn't match the strp format string, so it's not a backup # for this folder. Move on to the next one. continue ssfile.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime('%a %b %d %Y %H:%M:%S.%f') location = os.path.join(bkdir, x) ssfile[timestamp]['Size'] = os.stat(location).st_size ssfile[timestamp]['Location'] = location sfiles = dict(list(zip(list(range(n)), [ssfile[x] for x in sorted(ssfile, reverse=True)[:limit]]))) sefiles = {i: sfiles} files.update(sefiles) return files def restore_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Restore a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to restore, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.restore_backup /foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) # Note: This only supports minion backups, so this function will need to be # modified if/when master backups are implemented. ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret salt.utils.files.backup_minion(path, _get_bkroot()) try: shutil.copyfile(backup['Location'], path) except IOError as exc: ret['comment'] = \ 'Unable to restore {0} to {1}: ' \ '{2}'.format(backup['Location'], path, exc) return ret else: ret['result'] = True ret['comment'] = 'Successfully restored {0} to ' \ '{1}'.format(backup['Location'], path) # Try to set proper ownership if not salt.utils.platform.is_windows(): try: fstat = os.stat(path) except (OSError, IOError): ret['comment'] += ', but was unable to set ownership' else: os.chown(path, fstat.st_uid, fstat.st_gid) return ret def delete_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Delete a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to delete, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.delete_backup /var/cache/salt/minion/file_backup/home/foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret try: os.remove(backup['Location']) except IOError as exc: ret['comment'] = 'Unable to remove {0}: {1}'.format(backup['Location'], exc) else: ret['result'] = True ret['comment'] = 'Successfully removed {0}'.format(backup['Location']) return ret remove_backup = salt.utils.functools.alias_function(delete_backup, 'remove_backup') def grep(path, pattern, *opts): ''' Grep for a string in the specified file .. note:: This function's return value is slated for refinement in future versions of Salt path Path to the file to be searched .. note:: Globbing is supported (i.e. ``/var/log/foo/*.log``, but if globbing is being used then the path should be quoted to keep the shell from attempting to expand the glob expression. pattern Pattern to match. For example: ``test``, or ``a[0-5]`` opts Additional command-line flags to pass to the grep command. For example: ``-v``, or ``-i -B2`` .. note:: The options should come after a double-dash (as shown in the examples below) to keep Salt's own argument parser from interpreting them. CLI Example: .. code-block:: bash salt '*' file.grep /etc/passwd nobody salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i -B2 salt '*' file.grep "/etc/sysconfig/network-scripts/*" ipaddr -- -i -l ''' path = os.path.expanduser(path) # Backup the path in case the glob returns nothing _path = path path = glob.glob(path) # If the list is empty no files exist # so we revert back to the original path # so the result is an error. if not path: path = _path split_opts = [] for opt in opts: try: split = salt.utils.args.shlex_split(opt) except AttributeError: split = salt.utils.args.shlex_split(six.text_type(opt)) if len(split) > 1: raise SaltInvocationError( 'Passing multiple command line arguments in a single string ' 'is not supported, please pass the following arguments ' 'separately: {0}'.format(opt) ) split_opts.extend(split) if isinstance(path, list): cmd = ['grep'] + split_opts + [pattern] + path else: cmd = ['grep'] + split_opts + [pattern, path] try: ret = __salt__['cmd.run_all'](cmd, python_shell=False) except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return ret def open_files(by_pid=False): ''' Return a list of all physical open files on the system. CLI Examples: .. code-block:: bash salt '*' file.open_files salt '*' file.open_files by_pid=True ''' # First we collect valid PIDs pids = {} procfs = os.listdir('/proc/') for pfile in procfs: try: pids[int(pfile)] = [] except ValueError: # Not a valid PID, move on pass # Then we look at the open files for each PID files = {} for pid in pids: ppath = '/proc/{0}'.format(pid) try: tids = os.listdir('{0}/task'.format(ppath)) except OSError: continue # Collect the names of all of the file descriptors fd_ = [] #try: # fd_.append(os.path.realpath('{0}/task/{1}exe'.format(ppath, tid))) #except Exception: # pass for fpath in os.listdir('{0}/fd'.format(ppath)): fd_.append('{0}/fd/{1}'.format(ppath, fpath)) for tid in tids: try: fd_.append( os.path.realpath('{0}/task/{1}/exe'.format(ppath, tid)) ) except OSError: continue for tpath in os.listdir('{0}/task/{1}/fd'.format(ppath, tid)): fd_.append('{0}/task/{1}/fd/{2}'.format(ppath, tid, tpath)) fd_ = sorted(set(fd_)) # Loop through file descriptors and return useful data for each file for fdpath in fd_: # Sometimes PIDs and TIDs disappear before we can query them try: name = os.path.realpath(fdpath) # Running stat on the file cuts out all of the sockets and # deleted files from the list os.stat(name) except OSError: continue if name not in files: files[name] = [pid] else: # We still want to know which PIDs are using each file files[name].append(pid) files[name] = sorted(set(files[name])) pids[pid].append(name) pids[pid] = sorted(set(pids[pid])) if by_pid: return pids return files def pardir(): ''' Return the relative parent directory path symbol for underlying OS .. versionadded:: 2014.7.0 This can be useful when constructing Salt Formulas. .. code-block:: jinja {% set pardir = salt['file.pardir']() %} {% set final_path = salt['file.join']('subdir', pardir, 'confdir') %} CLI Example: .. code-block:: bash salt '*' file.pardir ''' return os.path.pardir def normpath(path): ''' Returns Normalize path, eliminating double slashes, etc. .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.normpath'](tpldir + '/../vars.jinja') import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.normpath 'a/b/c/..' ''' return os.path.normpath(path) def basename(path): ''' Returns the final component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- set filename = salt['file.basename'](source_file) %} CLI Example: .. code-block:: bash salt '*' file.basename 'test/test.config' ''' return os.path.basename(path) def dirname(path): ''' Returns the directory component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.dirname'](tpldir) + '/vars.jinja' import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.dirname 'test/path/filename.config' ''' return os.path.dirname(path) def join(*args): ''' Return a normalized file system path for the underlying OS .. versionadded:: 2014.7.0 This can be useful at the CLI but is frequently useful when scripting combining path variables: .. code-block:: jinja {% set www_root = '/var' %} {% set app_dir = 'myapp' %} myapp_config: file: - managed - name: {{ salt['file.join'](www_root, app_dir, 'config.yaml') }} CLI Example: .. code-block:: bash salt '*' file.join '/' 'usr' 'local' 'bin' ''' return os.path.join(*args) def move(src, dst): ''' Move a file or directory CLI Example: .. code-block:: bash salt '*' file.move /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('Source path must be absolute.') if not os.path.isabs(dst): raise SaltInvocationError('Destination path must be absolute.') ret = { 'result': True, 'comment': "'{0}' moved to '{1}'".format(src, dst), } try: shutil.move(src, dst) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move '{0}' to '{1}': {2}".format(src, dst, exc) ) return ret def diskusage(path): ''' Recursively calculate disk usage of path and return it in bytes CLI Example: .. code-block:: bash salt '*' file.diskusage /path/to/check ''' total_size = 0 seen = set() if os.path.isfile(path): stat_structure = os.stat(path) ret = stat_structure.st_size return ret for dirpath, dirnames, filenames in salt.utils.path.os_walk(path): for f in filenames: fp = os.path.join(dirpath, f) try: stat_structure = os.stat(fp) except OSError: continue if stat_structure.st_ino in seen: continue seen.add(stat_structure.st_ino) total_size += stat_structure.st_size ret = total_size return ret
saltstack/salt
salt/modules/file.py
gid_to_group
python
def gid_to_group(gid): ''' Convert the group id to the group name on this system gid gid to convert to a group name CLI Example: .. code-block:: bash salt '*' file.gid_to_group 0 ''' try: gid = int(gid) except ValueError: # This is not an integer, maybe it's already the group name? gid = group_to_gid(gid) if gid == '': # Don't even bother to feed it to grp return '' try: return grp.getgrgid(gid).gr_name except (KeyError, NameError): # If group is not present, fall back to the gid. return gid
Convert the group id to the group name on this system gid gid to convert to a group name CLI Example: .. code-block:: bash salt '*' file.gid_to_group 0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L162-L189
[ "def group_to_gid(group):\n '''\n Convert the group to the gid on this system\n\n group\n group to convert to its gid\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' file.group_to_gid root\n '''\n if group is None:\n return ''\n try:\n if isinstance(group, int):\n return group\n return grp.getgrnam(group).gr_gid\n except KeyError:\n return ''\n" ]
# -*- coding: utf-8 -*- ''' Manage information about regular files, directories, and special files on the minion, set/read user, group, mode, and data ''' # TODO: We should add the capability to do u+r type operations here # some time in the future from __future__ import absolute_import, print_function, unicode_literals # Import python libs import datetime import errno import fnmatch import io import itertools import logging import operator import os import re import shutil import stat import string import sys import tempfile import time import glob import hashlib import mmap from collections import Iterable, Mapping from functools import reduce # pylint: disable=redefined-builtin # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range, zip from salt.ext.six.moves.urllib.parse import urlparse as _urlparse # pylint: enable=import-error,no-name-in-module,redefined-builtin try: import grp import pwd except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.atomicfile import salt.utils.data import salt.utils.dictupdate import salt.utils.filebuffer import salt.utils.files import salt.utils.find import salt.utils.functools import salt.utils.hashutils import salt.utils.itertools import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.templates import salt.utils.url import salt.utils.user from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError, get_error_message as _get_error_message from salt.utils.files import HASHES, HASHES_REVMAP log = logging.getLogger(__name__) __func_alias__ = { 'makedirs_': 'makedirs' } def __virtual__(): ''' Only work on POSIX-like systems ''' # win_file takes care of windows if salt.utils.platform.is_windows(): return ( False, 'The file execution module cannot be loaded: only available on ' 'non-Windows systems - use win_file instead.' ) return True def __clean_tmp(sfn): ''' Clean out a template temp file ''' if sfn.startswith(os.path.join(tempfile.gettempdir(), salt.utils.files.TEMPFILE_PREFIX)): # Don't remove if it exists in file_roots (any saltenv) all_roots = itertools.chain.from_iterable( six.itervalues(__opts__['file_roots'])) in_roots = any(sfn.startswith(root) for root in all_roots) # Only clean up files that exist if os.path.exists(sfn) and not in_roots: os.remove(sfn) def _error(ret, err_msg): ''' Common function for setting error information for return dicts ''' ret['result'] = False ret['comment'] = err_msg return ret def _binary_replace(old, new): ''' This function does NOT do any diffing, it just checks the old and new files to see if either is binary, and provides an appropriate string noting the difference between the two files. If neither file is binary, an empty string is returned. This function should only be run AFTER it has been determined that the files differ. ''' old_isbin = not __utils__['files.is_text'](old) new_isbin = not __utils__['files.is_text'](new) if any((old_isbin, new_isbin)): if all((old_isbin, new_isbin)): return 'Replace binary file' elif old_isbin: return 'Replace binary file with text file' elif new_isbin: return 'Replace text file with binary file' return '' def _get_bkroot(): ''' Get the location of the backup dir in the minion cache ''' # Get the cachedir from the minion config return os.path.join(__salt__['config.get']('cachedir'), 'file_backup') def _splitlines_preserving_trailing_newline(str): ''' Returns a list of the lines in the string, breaking at line boundaries and preserving a trailing newline (if present). Essentially, this works like ``str.striplines(False)`` but preserves an empty line at the end. This is equivalent to the following code: .. code-block:: python lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') ''' lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') return lines def group_to_gid(group): ''' Convert the group to the gid on this system group group to convert to its gid CLI Example: .. code-block:: bash salt '*' file.group_to_gid root ''' if group is None: return '' try: if isinstance(group, int): return group return grp.getgrnam(group).gr_gid except KeyError: return '' def get_gid(path, follow_symlinks=True): ''' Return the id of the group that owns a given file path file or directory of which to get the gid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_gid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('gid', -1) def get_group(path, follow_symlinks=True): ''' Return the group that owns a given file path file or directory of which to get the group follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_group /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('group', False) def uid_to_user(uid): ''' Convert a uid to a user name uid uid to convert to a username CLI Example: .. code-block:: bash salt '*' file.uid_to_user 0 ''' try: return pwd.getpwuid(uid).pw_name except (KeyError, NameError): # If user is not present, fall back to the uid. return uid def user_to_uid(user): ''' Convert user name to a uid user user name to convert to its uid CLI Example: .. code-block:: bash salt '*' file.user_to_uid root ''' if user is None: user = salt.utils.user.get_user() try: if isinstance(user, int): return user return pwd.getpwnam(user).pw_uid except KeyError: return '' def get_uid(path, follow_symlinks=True): ''' Return the id of the user that owns a given file path file or directory of which to get the uid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_uid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('uid', -1) def get_user(path, follow_symlinks=True): ''' Return the user that owns a given file path file or directory of which to get the user follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_user /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('user', False) def get_mode(path, follow_symlinks=True): ''' Return the mode of a file path file or directory of which to get the mode follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_mode /etc/passwd .. versionchanged:: 2014.1.0 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('mode', '') def set_mode(path, mode): ''' Set the mode of a file path file or directory of which to set the mode mode mode to set the path to CLI Example: .. code-block:: bash salt '*' file.set_mode /etc/passwd 0644 ''' path = os.path.expanduser(path) mode = six.text_type(mode).lstrip('0Oo') if not mode: mode = '0' if not os.path.exists(path): raise CommandExecutionError('{0}: File not found'.format(path)) try: os.chmod(path, int(mode, 8)) except Exception: return 'Invalid Mode ' + mode return get_mode(path) def lchown(path, user, group): ''' Chown a file, pass the file the desired user and group without following symlinks. path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 return os.lchown(path, uid, gid) def chown(path, user, group): ''' Chown a file, pass the file the desired user and group path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 if not os.path.exists(path): try: # Broken symlinks will return false, but still need to be chowned return os.lchown(path, uid, gid) except OSError: pass err += 'File not found' if err: return err return os.chown(path, uid, gid) def chgrp(path, group): ''' Change the group of a file path path to the file or directory group group owner CLI Example: .. code-block:: bash salt '*' file.chgrp /etc/passwd root ''' path = os.path.expanduser(path) user = get_user(path) return chown(path, user, group) def _cmp_attrs(path, attrs): ''' .. versionadded:: 2018.3.0 Compare attributes of a given file to given attributes. Returns a pair (list) where first item are attributes to add and second item are to be removed. Please take into account when using this function that some minions will not have lsattr installed. path path to file to compare attributes with. attrs string of attributes to compare against a given file ''' diff = [None, None] # lsattr for AIX is not the same thing as lsattr for linux. if salt.utils.platform.is_aix(): return None try: lattrs = lsattr(path).get(path, '') except AttributeError: # lsattr not installed return None old = [chr for chr in lattrs if chr not in attrs] if old: diff[1] = ''.join(old) new = [chr for chr in attrs if chr not in lattrs] if new: diff[0] = ''.join(new) return diff def lsattr(path): ''' .. versionadded:: 2018.3.0 .. versionchanged:: 2018.3.1 If ``lsattr`` is not installed on the system, ``None`` is returned. .. versionchanged:: 2018.3.4 If on ``AIX``, ``None`` is returned even if in filesystem as lsattr on ``AIX`` is not the same thing as the linux version. Obtain the modifiable attributes of the given file. If path is to a directory, an empty list is returned. path path to file to obtain attributes of. File/directory must exist. CLI Example: .. code-block:: bash salt '*' file.lsattr foo1.txt ''' if not salt.utils.path.which('lsattr') or salt.utils.platform.is_aix(): return None if not os.path.exists(path): raise SaltInvocationError("File or directory does not exist: " + path) cmd = ['lsattr', path] result = __salt__['cmd.run'](cmd, ignore_retcode=True, python_shell=False) results = {} for line in result.splitlines(): if not line.startswith('lsattr: '): vals = line.split(None, 1) results[vals[1]] = re.findall(r"[aAcCdDeijPsStTu]", vals[0]) return results def chattr(*files, **kwargs): ''' .. versionadded:: 2018.3.0 Change the attributes of files. This function accepts one or more files and the following options: operator Can be wither ``add`` or ``remove``. Determines whether attributes should be added or removed from files attributes One or more of the following characters: ``aAcCdDeijPsStTu``, representing attributes to add to/remove from files version a version number to assign to the file(s) flags One or more of the following characters: ``RVf``, representing flags to assign to chattr (recurse, verbose, suppress most errors) CLI Example: .. code-block:: bash salt '*' file.chattr foo1.txt foo2.txt operator=add attributes=ai salt '*' file.chattr foo3.txt operator=remove attributes=i version=2 ''' operator = kwargs.pop('operator', None) attributes = kwargs.pop('attributes', None) flags = kwargs.pop('flags', None) version = kwargs.pop('version', None) if (operator is None) or (operator not in ('add', 'remove')): raise SaltInvocationError( "Need an operator: 'add' or 'remove' to modify attributes.") if attributes is None: raise SaltInvocationError("Need attributes: [aAcCdDeijPsStTu]") cmd = ['chattr'] if operator == "add": attrs = '+{0}'.format(attributes) elif operator == "remove": attrs = '-{0}'.format(attributes) cmd.append(attrs) if flags is not None: cmd.append('-{0}'.format(flags)) if version is not None: cmd.extend(['-v', version]) cmd.extend(files) result = __salt__['cmd.run'](cmd, python_shell=False) if bool(result): raise CommandExecutionError( "chattr failed to run, possibly due to bad parameters.") return True def get_sum(path, form='sha256'): ''' Return the checksum for the given file. The following checksum algorithms are supported: * md5 * sha1 * sha224 * sha256 **(default)** * sha384 * sha512 path path to the file or directory form desired sum format CLI Example: .. code-block:: bash salt '*' file.get_sum /etc/passwd sha512 ''' path = os.path.expanduser(path) if not os.path.isfile(path): return 'File not found' return salt.utils.hashutils.get_hash(path, form, 4096) def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` path path to the file or directory form desired sum format chunk_size amount to sum at once CLI Example: .. code-block:: bash salt '*' file.get_hash /etc/shadow ''' return salt.utils.hashutils.get_hash(os.path.expanduser(path), form, chunk_size) def get_source_sum(file_name='', source='', source_hash=None, source_hash_name=None, saltenv='base'): ''' .. versionadded:: 2016.11.0 Used by :py:func:`file.get_managed <salt.modules.file.get_managed>` to obtain the hash and hash type from the parameters specified below. file_name Optional file name being managed, for matching with :py:func:`file.extract_hash <salt.modules.file.extract_hash>`. source Source file, as used in :py:mod:`file <salt.states.file>` and other states. If ``source_hash`` refers to a file containing hashes, then this filename will be used to match a filename in that file. If the ``source_hash`` is a hash expression, then this argument will be ignored. source_hash Hash file/expression, as used in :py:mod:`file <salt.states.file>` and other states. If this value refers to a remote URL or absolute path to a local file, it will be cached and :py:func:`file.extract_hash <salt.modules.file.extract_hash>` will be used to obtain a hash from it. source_hash_name Specific file name to look for when ``source_hash`` refers to a remote file, used to disambiguate ambiguous matches. saltenv : base Salt fileserver environment from which to retrieve the source_hash. This value will only be used when ``source_hash`` refers to a file on the Salt fileserver (i.e. one beginning with ``salt://``). CLI Example: .. code-block:: bash salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=499ae16dcae71eeb7c3a30c75ea7a1a6 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 source_hash_name=./dir2/foo.tar.gz ''' def _invalid_source_hash_format(): ''' DRY helper for reporting invalid source_hash input ''' raise CommandExecutionError( 'Source hash {0} format is invalid. The supported formats are: ' '1) a hash, 2) an expression in the format <hash_type>=<hash>, or ' '3) either a path to a local file containing hashes, or a URI of ' 'a remote hash file. Supported protocols for remote hash files ' 'are: {1}. The hash may also not be of a valid length, the ' 'following are supported hash types and lengths: {2}.'.format( source_hash, ', '.join(salt.utils.files.VALID_PROTOS), ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) hash_fn = None if os.path.isabs(source_hash): hash_fn = source_hash else: try: proto = _urlparse(source_hash).scheme if proto in salt.utils.files.VALID_PROTOS: hash_fn = __salt__['cp.cache_file'](source_hash, saltenv) if not hash_fn: raise CommandExecutionError( 'Source hash file {0} not found'.format(source_hash) ) else: if proto != '': # Some unsupported protocol (e.g. foo://) is being used. # We'll get into this else block if a hash expression # (like md5=<md5 checksum here>), but in those cases, the # protocol will be an empty string, in which case we avoid # this error condition. _invalid_source_hash_format() except (AttributeError, TypeError): _invalid_source_hash_format() if hash_fn is not None: ret = extract_hash(hash_fn, '', file_name, source, source_hash_name) if ret is None: _invalid_source_hash_format() ret['hsum'] = ret['hsum'].lower() return ret else: # The source_hash is a hash expression ret = {} try: ret['hash_type'], ret['hsum'] = \ [x.strip() for x in source_hash.split('=', 1)] except AttributeError: _invalid_source_hash_format() except ValueError: # No hash type, try to figure out by hash length if not re.match('^[{0}]+$'.format(string.hexdigits), source_hash): _invalid_source_hash_format() ret['hsum'] = source_hash source_hash_len = len(source_hash) if source_hash_len in HASHES_REVMAP: ret['hash_type'] = HASHES_REVMAP[source_hash_len] else: _invalid_source_hash_format() if ret['hash_type'] not in HASHES: raise CommandExecutionError( 'Invalid hash type \'{0}\'. Supported hash types are: {1}. ' 'Either remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to a supported type.' .format(ret['hash_type'], ', '.join(HASHES), ret['hsum']) ) else: hsum_len = len(ret['hsum']) if hsum_len not in HASHES_REVMAP: _invalid_source_hash_format() elif hsum_len != HASHES[ret['hash_type']]: raise CommandExecutionError( 'Invalid length ({0}) for hash type \'{1}\'. Either ' 'remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to \'{3}\''.format( hsum_len, ret['hash_type'], ret['hsum'], HASHES_REVMAP[hsum_len], ) ) ret['hsum'] = ret['hsum'].lower() return ret def check_hash(path, file_hash): ''' Check if a file matches the given hash string Returns ``True`` if the hash matches, otherwise ``False``. path Path to a file local to the minion. hash The hash to check against the file specified in the ``path`` argument. .. versionchanged:: 2016.11.4 For this and newer versions the hash can be specified without an accompanying hash type (e.g. ``e138491e9d5b97023cea823fe17bac22``), but for earlier releases it is necessary to also specify the hash type in the format ``<hash_type>=<hash_value>`` (e.g. ``md5=e138491e9d5b97023cea823fe17bac22``). CLI Example: .. code-block:: bash salt '*' file.check_hash /etc/fstab e138491e9d5b97023cea823fe17bac22 salt '*' file.check_hash /etc/fstab md5=e138491e9d5b97023cea823fe17bac22 ''' path = os.path.expanduser(path) if not isinstance(file_hash, six.string_types): raise SaltInvocationError('hash must be a string') for sep in (':', '='): if sep in file_hash: hash_type, hash_value = file_hash.split(sep, 1) break else: hash_value = file_hash hash_len = len(file_hash) hash_type = HASHES_REVMAP.get(hash_len) if hash_type is None: raise SaltInvocationError( 'Hash {0} (length: {1}) could not be matched to a supported ' 'hash type. The supported hash types and lengths are: ' '{2}'.format( file_hash, hash_len, ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) return get_hash(path, hash_type) == hash_value def find(path, *args, **kwargs): ''' Approximate the Unix ``find(1)`` command and return a list of paths that meet the specified criteria. The options include match criteria: .. code-block:: text name = path-glob # case sensitive iname = path-glob # case insensitive regex = path-regex # case sensitive iregex = path-regex # case insensitive type = file-types # match any listed type user = users # match any listed user group = groups # match any listed group size = [+-]number[size-unit] # default unit = byte mtime = interval # modified since date grep = regex # search file contents and/or actions: .. code-block:: text delete [= file-types] # default type = 'f' exec = command [arg ...] # where {} is replaced by pathname print [= print-opts] and/or depth criteria: .. code-block:: text maxdepth = maximum depth to transverse in path mindepth = minimum depth to transverse before checking files or directories The default action is ``print=path`` ``path-glob``: .. code-block:: text * = match zero or more chars ? = match any char [abc] = match a, b, or c [!abc] or [^abc] = match anything except a, b, and c [x-y] = match chars x through y [!x-y] or [^x-y] = match anything except chars x through y {a,b,c} = match a or b or c ``path-regex``: a Python Regex (regular expression) pattern to match pathnames ``file-types``: a string of one or more of the following: .. code-block:: text a: all file types b: block device c: character device d: directory p: FIFO (named pipe) f: plain file l: symlink s: socket ``users``: a space and/or comma separated list of user names and/or uids ``groups``: a space and/or comma separated list of group names and/or gids ``size-unit``: .. code-block:: text b: bytes k: kilobytes m: megabytes g: gigabytes t: terabytes interval: .. code-block:: text [<num>w] [<num>d] [<num>h] [<num>m] [<num>s] where: w: week d: day h: hour m: minute s: second print-opts: a comma and/or space separated list of one or more of the following: .. code-block:: text group: group name md5: MD5 digest of file contents mode: file permissions (as integer) mtime: last modification time (as time_t) name: file basename path: file absolute path size: file size in bytes type: file type user: user name CLI Examples: .. code-block:: bash salt '*' file.find / type=f name=\\*.bak size=+10m salt '*' file.find /var mtime=+30d size=+10m print=path,size,mtime salt '*' file.find /var/log name=\\*.[0-9] mtime=+30d size=+10m delete ''' if 'delete' in args: kwargs['delete'] = 'f' elif 'print' in args: kwargs['print'] = 'path' try: finder = salt.utils.find.Finder(kwargs) except ValueError as ex: return 'error: {0}'.format(ex) ret = [item for i in [finder.find(p) for p in glob.glob(os.path.expanduser(path))] for item in i] ret.sort() return ret def _sed_esc(string, escape_all=False): ''' Escape single quotes and forward slashes ''' special_chars = "^.[$()|*+?{" string = string.replace("'", "'\"'\"'").replace("/", "\\/") if escape_all is True: for char in special_chars: string = string.replace(char, "\\" + char) return string def sed(path, before, after, limit='', backup='.bak', options='-r -e', flags='g', escape_all=False, negate_match=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup options : ``-r -e`` Options to pass to sed flags : ``g`` Flags to modify the sed search; e.g., ``i`` for case-insensitive pattern matching negate_match : False Negate the search command (``!``) .. versionadded:: 0.17.0 Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # path = os.path.expanduser(path) if not os.path.exists(path): return False # Mandate that before and after are strings before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.append('-i{0}'.format(backup) if backup else '-i') cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}{negate_match}s/{before}/{after}/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', negate_match='!' if negate_match else '', before=before, after=after, flags=flags ) ) cmd.append(path) return __salt__['cmd.run_all'](cmd, python_shell=False) def sed_contains(path, text, limit='', flags='g'): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the file at ``path`` contains ``text``. Utilizes sed to perform the search (line-wise search). Note: the ``p`` flag will be added to any flags you pass in. CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' # Largely inspired by Fabric's contrib.files.contains() path = os.path.expanduser(path) if not os.path.exists(path): return False before = _sed_esc(six.text_type(text), False) limit = _sed_esc(six.text_type(limit), False) options = '-n -r -e' if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}s/{before}/$/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', before=before, flags='p{0}'.format(flags) ) ) cmd.append(path) result = __salt__['cmd.run'](cmd, python_shell=False) return bool(result) def psed(path, before, after, limit='', backup='.bak', flags='gMS', escape_all=False, multi=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file (pure Python version) Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup flags : ``gMS`` Flags to modify the search. Valid values are: - ``g``: Replace all occurrences of the pattern, not just the first. - ``I``: Ignore case. - ``L``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\s`` and ``\\S`` dependent on the locale. - ``M``: Treat multiple lines as a single line. - ``S``: Make `.` match all characters, including newlines. - ``U``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\d``, ``\\D``, ``\\s`` and ``\\S`` dependent on Unicode. - ``X``: Verbose (whitespace is ignored). multi: ``False`` If True, treat the entire file as a single line Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # # Mandate that before and after are strings path = os.path.expanduser(path) multi = bool(multi) before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) # The pattern to replace with does not need to be escaped!!! # after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) shutil.copy2(path, '{0}{1}'.format(path, backup)) with salt.utils.files.fopen(path, 'w') as ofile: with salt.utils.files.fopen('{0}{1}'.format(path, backup), 'r') as ifile: if multi is True: for line in ifile.readline(): ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(line), before, after, limit, flags ) ) ) else: ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(ifile.read()), before, after, limit, flags ) ) ) RE_FLAG_TABLE = {'I': re.I, 'L': re.L, 'M': re.M, 'S': re.S, 'U': re.U, 'X': re.X} def _psed(text, before, after, limit, flags): ''' Does the actual work for file.psed, so that single lines can be passed in ''' atext = text if limit: limit = re.compile(limit) comps = text.split(limit) atext = ''.join(comps[1:]) count = 1 if 'g' in flags: count = 0 flags = flags.replace('g', '') aflags = 0 for flag in flags: aflags |= RE_FLAG_TABLE[flag] before = re.compile(before, flags=aflags) text = re.sub(before, after, atext, count=count) return text def uncomment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Uncomment specified commented lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be uncommented. This regex should not include the comment character. A leading ``^`` character will be stripped for convenience (for easily switching between comment() and uncomment()). char : ``#`` The character to remove in order to uncomment a line backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup CLI Example: .. code-block:: bash salt '*' file.uncomment /etc/hosts.deny 'ALL: PARANOID' ''' return comment_line(path=path, regex=regex, char=char, cmnt=False, backup=backup) def comment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Comment out specified lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be commented; this pattern will be wrapped in parenthesis and will move any preceding/trailing ``^`` or ``$`` characters outside the parenthesis (e.g., the pattern ``^foo$`` will be rewritten as ``^(foo)$``) char : ``#`` The character to be inserted at the beginning of a line in order to comment it out backup : ``.bak`` The file will be backed up before edit with this file extension .. warning:: This backup will be overwritten each time ``sed`` / ``comment`` / ``uncomment`` is called. Meaning the backup will only be useful after the first invocation. CLI Example: .. code-block:: bash salt '*' file.comment /etc/modules pcspkr ''' return comment_line(path=path, regex=regex, char=char, cmnt=True, backup=backup) def comment_line(path, regex, char='#', cmnt=True, backup='.bak'): r''' Comment or Uncomment a line in a text file. :param path: string The full path to the text file. :param regex: string A regex expression that begins with ``^`` that will find the line you wish to comment. Can be as simple as ``^color =`` :param char: string The character used to comment a line in the type of file you're referencing. Default is ``#`` :param cmnt: boolean True to comment the line. False to uncomment the line. Default is True. :param backup: string The file extension to give the backup file. Default is ``.bak`` Set to False/None to not keep a backup. :return: boolean Returns True if successful, False if not CLI Example: The following example will comment out the ``pcspkr`` line in the ``/etc/modules`` file using the default ``#`` character and create a backup file named ``modules.bak`` .. code-block:: bash salt '*' file.comment_line '/etc/modules' '^pcspkr' CLI Example: The following example will uncomment the ``log_level`` setting in ``minion`` config file if it is set to either ``warning``, ``info``, or ``debug`` using the ``#`` character and create a backup file named ``minion.bk`` .. code-block:: bash salt '*' file.comment_line 'C:\salt\conf\minion' '^log_level: (warning|info|debug)' '#' False '.bk' ''' # Get the regex for comment or uncomment if cmnt: regex = '{0}({1}){2}'.format( '^' if regex.startswith('^') else '', regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') else: regex = r'^{0}\s*({1}){2}'.format( char, regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') # Load the real path to the file path = os.path.realpath(os.path.expanduser(path)) # Make sure the file exists if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) # Make sure it is a text file if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}'.format(path)) # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes found = False # Dictionaries for comparing changes orig_file = [] new_file = [] # Buffer size for fopen bufsize = os.path.getsize(path) try: # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: # Is it in this line line = salt.utils.stringutils.to_unicode(line) if re.match(regex, line): # Load lines into dictionaries, set found to True orig_file.append(line) if cmnt: new_file.append('{0}{1}'.format(char, line)) else: new_file.append(line.lstrip(char)) found = True except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) # We've searched the whole file. If we didn't find anything, return False if not found: return False if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Create a copy to read from and to use as a backup later try: temp_file = _mkstemp_copy(path=path, preserve_inode=False) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) try: # Open the file in write mode mode = 'wb' if six.PY2 and salt.utils.platform.is_windows() else 'w' with salt.utils.files.fopen(path, mode=mode, buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: line = salt.utils.stringutils.to_unicode(line) try: # Is it in this line if re.match(regex, line): # Write the new line if cmnt: wline = '{0}{1}'.format(char, line) else: wline = line.lstrip(char) else: # Write the existing line (no change) wline = line wline = salt.utils.stringutils.to_bytes(wline) \ if six.PY2 and salt.utils.platform.is_windows() \ else salt.utils.stringutils.to_str(wline) w_file.write(wline) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if backup: # Move the backup file to the original directory backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: os.remove(temp_file) if not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) # Return a diff using the two dictionaries return __utils__['stringutils.get_diff'](orig_file, new_file) def _get_flags(flags): ''' Return an integer appropriate for use as a flag for the re module from a list of human-readable strings .. code-block:: python >>> _get_flags(['MULTILINE', 'IGNORECASE']) 10 >>> _get_flags('MULTILINE') 8 >>> _get_flags(2) 2 ''' if isinstance(flags, six.string_types): flags = [flags] if isinstance(flags, Iterable) and not isinstance(flags, Mapping): _flags_acc = [] for flag in flags: _flag = getattr(re, six.text_type(flag).upper()) if not isinstance(_flag, six.integer_types): raise SaltInvocationError( 'Invalid re flag given: {0}'.format(flag) ) _flags_acc.append(_flag) return reduce(operator.__or__, _flags_acc) elif isinstance(flags, six.integer_types): return flags else: raise SaltInvocationError( 'Invalid re flags: "{0}", must be given either as a single flag ' 'string, a list of strings, or as an integer'.format(flags) ) def _add_flags(flags, new_flags): ''' Combine ``flags`` and ``new_flags`` ''' flags = _get_flags(flags) new_flags = _get_flags(new_flags) return flags | new_flags def _mkstemp_copy(path, preserve_inode=True): ''' Create a temp file and move/copy the contents of ``path`` to the temp file. Return the path to the temp file. path The full path to the file whose contents will be moved/copied to a temp file. Whether it's moved or copied depends on the value of ``preserve_inode``. preserve_inode Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). Default is ``True``. ''' temp_file = None # Create the temp file try: temp_file = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to create temp file. " "Exception: {0}".format(exc) ) # use `copy` to preserve the inode of the # original file, and thus preserve hardlinks # to the inode. otherwise, use `move` to # preserve prior behavior, which results in # writing the file to a new inode. if preserve_inode: try: shutil.copy2(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to copy file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: try: shutil.move(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) return temp_file def _starts_till(src, probe, strip_comments=True): ''' Returns True if src and probe at least matches at the beginning till some point. ''' def _strip_comments(txt): ''' Strip possible comments. Usually comments are one or two symbols at the beginning of the line, separated with space ''' buff = txt.split(" ", 1) return len(buff) == 2 and len(buff[0]) < 2 and buff[1] or txt def _to_words(txt): ''' Split by words ''' return txt and [w for w in txt.strip().split(" ") if w.strip()] or txt no_match = -1 equal = 0 if not src or not probe: return no_match src = src.rstrip('\n\r') probe = probe.rstrip('\n\r') if src == probe: return equal src = _to_words(strip_comments and _strip_comments(src) or src) probe = _to_words(strip_comments and _strip_comments(probe) or probe) a_buff, b_buff = len(src) < len(probe) and (src, probe) or (probe, src) b_buff = ' '.join(b_buff) for idx in range(len(a_buff)): prb = ' '.join(a_buff[:-(idx + 1)]) if prb and b_buff.startswith(prb): return idx return no_match def _regex_to_static(src, regex): ''' Expand regular expression to static match. ''' if not src or not regex: return None try: compiled = re.compile(regex, re.DOTALL) src = [line for line in src if compiled.search(line) or line.count(regex)] except Exception as ex: raise CommandExecutionError("{0}: '{1}'".format(_get_error_message(ex), regex)) return src and src or [] def _assert_occurrence(probe, target, amount=1): ''' Raise an exception, if there are different amount of specified occurrences in src. ''' occ = len(probe) if occ > amount: msg = 'more than' elif occ < amount: msg = 'less than' elif not occ: msg = 'no' else: msg = None if msg: raise CommandExecutionError('Found {0} expected occurrences in "{1}" expression'.format(msg, target)) return occ def _set_line_indent(src, line, indent): ''' Indent the line with the source line. ''' if not indent: return line idt = [] for c in src: if c not in ['\t', ' ']: break idt.append(c) return ''.join(idt) + line.lstrip() def _get_eol(line): match = re.search('((?<!\r)\n|\r(?!\n)|\r\n)$', line) return match and match.group() or '' def _set_line_eol(src, line): ''' Add line ending ''' line_ending = _get_eol(src) or os.linesep return line.rstrip() + line_ending def _insert_line_before(idx, body, content, indent): if not idx or (idx and _starts_till(body[idx - 1], content) < 0): cnd = _set_line_indent(body[idx], content, indent) body.insert(idx, cnd) return body def _insert_line_after(idx, body, content, indent): # No duplicates or append, if "after" is the last line next_line = idx + 1 < len(body) and body[idx + 1] or None if next_line is None or _starts_till(next_line, content) < 0: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) return body def line(path, content=None, match=None, mode=None, location=None, before=None, after=None, show_changes=True, backup=False, quiet=False, indent=True): ''' .. versionadded:: 2015.8.0 Edit a line in the configuration file. The ``path`` and ``content`` arguments are required, as well as passing in one of the ``mode`` options. path Filesystem path to the file to be edited. content Content of the line. Allowed to be empty if mode=delete. match Match the target line for an action by a fragment of a string or regular expression. If neither ``before`` nor ``after`` are provided, and ``match`` is also ``None``, match becomes the ``content`` value. mode Defines how to edit a line. One of the following options is required: - ensure If line does not exist, it will be added. This is based on the ``content`` argument. - replace If line already exists, it will be replaced. - delete Delete the line, once found. - insert Insert a line. .. note:: If ``mode=insert`` is used, at least one of the following options must also be defined: ``location``, ``before``, or ``after``. If ``location`` is used, it takes precedence over the other two options. location Defines where to place content in the line. Note this option is only used when ``mode=insert`` is specified. If a location is passed in, it takes precedence over both the ``before`` and ``after`` kwargs. Valid locations are: - start Place the content at the beginning of the file. - end Place the content at the end of the file. before Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. after Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. show_changes Output a unified diff of the old file and the new file. If ``False`` return a boolean if any changes were made. Default is ``True`` .. note:: Using this option will store two copies of the file in-memory (the original version and the edited version) in order to generate the diff. backup Create a backup of the original file with the extension: "Year-Month-Day-Hour-Minutes-Seconds". quiet Do not raise any exceptions. E.g. ignore the fact that the file that is tried to be edited does not exist and nothing really happened. indent Keep indentation with the previous line. This option is not considered when the ``delete`` mode is specified. CLI Example: .. code-block:: bash salt '*' file.line /etc/nsswitch.conf "networks:\tfiles dns" after="hosts:.*?" mode='ensure' .. note:: If an equal sign (``=``) appears in an argument to a Salt command, it is interpreted as a keyword argument in the format of ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.line /path/to/file content="CREATEMAIL_SPOOL=no" match="CREATE_MAIL_SPOOL=yes" mode="replace" ''' path = os.path.realpath(os.path.expanduser(path)) if not os.path.isfile(path): if not quiet: raise CommandExecutionError('File "{0}" does not exists or is not a file.'.format(path)) return False # No changes had happened mode = mode and mode.lower() or mode if mode not in ['insert', 'ensure', 'delete', 'replace']: if mode is None: raise CommandExecutionError('Mode was not defined. How to process the file?') else: raise CommandExecutionError('Unknown mode: "{0}"'.format(mode)) # We've set the content to be empty in the function params but we want to make sure # it gets passed when needed. Feature #37092 empty_content_modes = ['delete'] if mode not in empty_content_modes and content is None: raise CommandExecutionError('Content can only be empty if mode is "{0}"'.format(', '.join(empty_content_modes))) del empty_content_modes # Before/after has privilege. If nothing defined, match is used by content. if before is None and after is None and not match: match = content with salt.utils.files.fopen(path, mode='r') as fp_: body = salt.utils.data.decode_list(fp_.readlines()) body_before = hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() # Add empty line at the end if last line ends with eol. # Allows simpler code if body and _get_eol(body[-1]): body.append('') after = _regex_to_static(body, after) before = _regex_to_static(body, before) match = _regex_to_static(body, match) if os.stat(path).st_size == 0 and mode in ('delete', 'replace'): log.warning('Cannot find text to %s. File \'%s\' is empty.', mode, path) body = [] elif mode == 'delete' and match: body = [line for line in body if line != match[0]] elif mode == 'replace' and match: idx = body.index(match[0]) file_line = body.pop(idx) body.insert(idx, _set_line_indent(file_line, content, indent)) elif mode == 'insert': if not location and not before and not after: raise CommandExecutionError('On insert must be defined either "location" or "before/after" conditions.') if not location: if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') out = [] in_range = False for line in body: if line == after[0]: in_range = True elif line == before[0] and in_range: cnd = _set_line_indent(line, content, indent) out.append(cnd) out.append(line) body = out if before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif after and not before: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: if location == 'start': if body: body.insert(0, _set_line_eol(body[0], content)) else: body.append(content + os.linesep) elif location == 'end': body.append(_set_line_indent(body[-1], content, indent) if body else content) elif mode == 'ensure': if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') is_there = bool([l for l in body if l.count(content)]) if not is_there: idx = body.index(after[0]) if idx < (len(body) - 1) and body[idx + 1] == before[0]: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) else: raise CommandExecutionError('Found more than one line between ' 'boundaries "before" and "after".') elif before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif not before and after: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: raise CommandExecutionError("Wrong conditions? " "Unable to ensure line without knowing " "where to put it before and/or after.") if body: for idx, line in enumerate(body): if not _get_eol(line) and idx+1 < len(body): prev = idx and idx-1 or 1 body[idx] = _set_line_eol(body[prev], line) # We do not need empty line at the end anymore if '' == body[-1]: body.pop() changed = body_before != hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() if backup and changed and __opts__['test'] is False: try: temp_file = _mkstemp_copy(path=path, preserve_inode=True) shutil.move(temp_file, '{0}.{1}'.format(path, time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime()))) except (OSError, IOError) as exc: raise CommandExecutionError("Unable to create the backup file of {0}. Exception: {1}".format(path, exc)) changes_diff = None if changed: if show_changes: with salt.utils.files.fopen(path, 'r') as fp_: path_content = salt.utils.data.decode_list(fp_.read().splitlines(True)) changes_diff = __utils__['stringutils.get_diff'](path_content, body) if __opts__['test'] is False: fh_ = None try: # Make sure we match the file mode from salt.utils.files.fopen if six.PY2 and salt.utils.platform.is_windows(): mode = 'wb' body = salt.utils.data.encode_list(body) else: mode = 'w' body = salt.utils.data.decode_list(body, to_str=True) fh_ = salt.utils.atomicfile.atomic_open(path, mode) fh_.writelines(body) finally: if fh_: fh_.close() return show_changes and changes_diff or changed def replace(path, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, backup='.bak', dry_run=False, search_only=False, show_changes=True, ignore_if_missing=False, preserve_inode=True, backslash_literal=False, ): ''' .. versionadded:: 0.17.0 Replace occurrences of a pattern in a file. If ``show_changes`` is ``True``, then a diff of what changed will be returned, otherwise a ``True`` will be returned when changes are made, and ``False`` when no changes are made. This is a pure Python implementation that wraps Python's :py:func:`~re.sub`. path Filesystem path to the file to be edited. If a symlink is specified, it will be resolved to its target. pattern A regular expression, to be matched using Python's :py:func:`~re.search`. repl The replacement text count : 0 Maximum number of pattern occurrences to be replaced. If count is a positive integer ``n``, only ``n`` occurrences will be replaced, otherwise all occurrences will be replaced. flags (list or int) A list of flags defined in the ``re`` module documentation from the Python standard library. Each list item should be a string that will correlate to the human-friendly flag name. E.g., ``['IGNORECASE', 'MULTILINE']``. Optionally, ``flags`` may be an int, with a value corresponding to the XOR (``|``) of all the desired flags. Defaults to 8 (which supports 'MULTILINE'). bufsize (int or str) How much of the file to buffer into memory at once. The default value ``1`` processes one line at a time. The special value ``file`` may be specified which will read the entire file into memory before processing. append_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True``, and pattern is not found, then the content will be appended to the file. prepend_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True`` and pattern is not found, then the content will be prepended to the file. not_found_content .. versionadded:: 2014.7.0 Content to use for append/prepend if not found. If None (default), uses ``repl``. Useful when ``repl`` uses references to group in pattern. backup : .bak The file extension to use for a backup of the file before editing. Set to ``False`` to skip making a backup. dry_run : False If set to ``True``, no changes will be made to the file, the function will just return the changes that would have been made (or a ``True``/``False`` value if ``show_changes`` is set to ``False``). search_only : False If set to true, this no changes will be performed on the file, and this function will simply return ``True`` if the pattern was matched, and ``False`` if not. show_changes : True If ``True``, return a diff of changes made. Otherwise, return ``True`` if changes were made, and ``False`` if not. .. note:: Using this option will store two copies of the file in memory (the original version and the edited version) in order to generate the diff. This may not normally be a concern, but could impact performance if used with large files. ignore_if_missing : False .. versionadded:: 2015.8.0 If set to ``True``, this function will simply return ``False`` if the file doesn't exist. Otherwise, an error will be thrown. preserve_inode : True .. versionadded:: 2015.8.0 Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). backslash_literal : False .. versionadded:: 2016.11.7 Interpret backslashes as literal backslashes for the repl and not escape characters. This will help when using append/prepend so that the backslashes are not interpreted for the repl on the second run of the state. If an equal sign (``=``) appears in an argument to a Salt command it is interpreted as a keyword argument in the format ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.replace /path/to/file pattern='=' repl=':' salt '*' file.replace /path/to/file pattern="bind-address\\s*=" repl='bind-address:' CLI Examples: .. code-block:: bash salt '*' file.replace /etc/httpd/httpd.conf pattern='LogLevel warn' repl='LogLevel info' salt '*' file.replace /some/file pattern='before' repl='after' flags='[MULTILINE, IGNORECASE]' ''' symlink = False if is_link(path): symlink = True target_path = os.readlink(path) given_path = os.path.expanduser(path) path = os.path.realpath(os.path.expanduser(path)) if not os.path.exists(path): if ignore_if_missing: return False else: raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if search_only and (append_if_not_found or prepend_if_not_found): raise SaltInvocationError( 'search_only cannot be used with append/prepend_if_not_found' ) if append_if_not_found and prepend_if_not_found: raise SaltInvocationError( 'Only one of append and prepend_if_not_found is permitted' ) flags_num = _get_flags(flags) cpattern = re.compile(salt.utils.stringutils.to_bytes(pattern), flags_num) filesize = os.path.getsize(path) if bufsize == 'file': bufsize = filesize # Search the file; track if any changes have been made for the return val has_changes = False orig_file = [] # used for show_changes and change detection new_file = [] # used for show_changes and change detection if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Avoid TypeErrors by forcing repl to be bytearray related to mmap # Replacement text may contains integer: 123 for example repl = salt.utils.stringutils.to_bytes(six.text_type(repl)) if not_found_content: not_found_content = salt.utils.stringutils.to_bytes(not_found_content) found = False temp_file = None content = salt.utils.stringutils.to_unicode(not_found_content) \ if not_found_content and (prepend_if_not_found or append_if_not_found) \ else salt.utils.stringutils.to_unicode(repl) try: # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes r_data = None # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: try: # mmap throws a ValueError if the file is empty. r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) except (ValueError, mmap.error): # size of file in /proc is 0, but contains data r_data = salt.utils.stringutils.to_bytes("".join(r_file)) if search_only: # Just search; bail as early as a match is found if re.search(cpattern, r_data): return True # `with` block handles file closure else: return False else: result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) # found anything? (even if no change) if nrepl > 0: found = True # Identity check the potential change has_changes = True if pattern != repl else has_changes if prepend_if_not_found or append_if_not_found: # Search for content, to avoid pre/appending the # content if it was pre/appended in a previous run. if re.search(salt.utils.stringutils.to_bytes('^{0}($|(?=\r\n))'.format(re.escape(content))), r_data, flags=flags_num): # Content was found, so set found. found = True orig_file = r_data.read(filesize).splitlines(True) \ if isinstance(r_data, mmap.mmap) \ else r_data.splitlines(True) new_file = result.splitlines(True) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() if has_changes and not dry_run: # Write the replacement text in this block. try: # Create a copy to read from and to use as a backup later temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) r_data = None try: # Open the file in write mode with salt.utils.files.fopen(path, mode='w', buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='r', buffering=bufsize) as r_file: r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) try: w_file.write(salt.utils.stringutils.to_str(result)) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if not found and (append_if_not_found or prepend_if_not_found): if not_found_content is None: not_found_content = repl if prepend_if_not_found: new_file.insert(0, not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) else: # append_if_not_found # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(salt.utils.stringutils.to_bytes(os.linesep)): new_file[-1] += salt.utils.stringutils.to_bytes(os.linesep) new_file.append(not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) has_changes = True if not dry_run: try: # Create a copy to read from and for later use as a backup temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line)) finally: fh_.close() if backup and has_changes and not dry_run: # keep the backup only if it was requested # and only if there were any changes backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) if symlink: symlink_backup = '{0}{1}'.format(given_path, backup) target_backup = '{0}{1}'.format(target_path, backup) # Always clobber any existing symlink backup # to match the behaviour of the 'backup' option try: os.symlink(target_backup, symlink_backup) except OSError: os.remove(symlink_backup) os.symlink(target_backup, symlink_backup) except Exception: raise CommandExecutionError( "Unable create backup symlink '{0}'. " "Target was '{1}'. " "Exception: {2}".format(symlink_backup, target_backup, exc) ) elif temp_file: try: os.remove(temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to delete temp file '{0}'. " "Exception: {1}".format(temp_file, exc) ) if not dry_run and not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) differences = __utils__['stringutils.get_diff'](orig_file, new_file) if show_changes: return differences # We may have found a regex line match but don't need to change the line # (for situations where the pattern also matches the repl). Revert the # has_changes flag to False if the final result is unchanged. if not differences: has_changes = False return has_changes def blockreplace(path, marker_start='#-- start managed zone --', marker_end='#-- end managed zone --', content='', append_if_not_found=False, prepend_if_not_found=False, backup='.bak', dry_run=False, show_changes=True, append_newline=False, insert_before_match=None, insert_after_match=None): ''' .. versionadded:: 2014.1.0 Replace content of a text block in a file, delimited by line markers A block of content delimited by comments can help you manage several lines entries without worrying about old entries removal. .. note:: This function will store two copies of the file in-memory (the original version and the edited version) in order to detect changes and only edit the targeted file if necessary. path Filesystem path to the file to be edited marker_start The line content identifying a line as the start of the content block. Note that the whole line containing this marker will be considered, so whitespace or extra content before or after the marker is included in final output marker_end The line content identifying the end of the content block. As of versions 2017.7.5 and 2018.3.1, everything up to the text matching the marker will be replaced, so it's important to ensure that your marker includes the beginning of the text you wish to replace. content The content to be used between the two lines identified by marker_start and marker_stop. append_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be appended to the file. prepend_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be prepended to the file. insert_before_match If markers are not found, this parameter can be set to a regex which will insert the block before the first found occurrence in the file. .. versionadded:: Neon insert_after_match If markers are not found, this parameter can be set to a regex which will insert the block after the first found occurrence in the file. .. versionadded:: Neon backup The file extension to use for a backup of the file if any edit is made. Set to ``False`` to skip making a backup. dry_run : False If ``True``, do not make any edits to the file and simply return the changes that *would* be made. show_changes : True Controls how changes are presented. If ``True``, this function will return a unified diff of the changes made. If False, then it will return a boolean (``True`` if any changes were made, otherwise ``False``). append_newline : False Controls whether or not a newline is appended to the content block. If the value of this argument is ``True`` then a newline will be added to the content block. If it is ``False``, then a newline will *not* be added to the content block. If it is ``None`` then a newline will only be added to the content block if it does not already end in a newline. .. versionadded:: 2016.3.4 .. versionchanged:: 2017.7.5,2018.3.1 New behavior added when value is ``None``. .. versionchanged:: 2019.2.0 The default value of this argument will change to ``None`` to match the behavior of the :py:func:`file.blockreplace state <salt.states.file.blockreplace>` CLI Example: .. code-block:: bash salt '*' file.blockreplace /etc/hosts '#-- start managed zone foobar : DO NOT EDIT --' \\ '#-- end managed zone foobar --' $'10.0.1.1 foo.foobar\\n10.0.1.2 bar.foobar' True ''' exclusive_params = [append_if_not_found, prepend_if_not_found, bool(insert_before_match), bool(insert_after_match)] if sum(exclusive_params) > 1: raise SaltInvocationError( 'Only one of append_if_not_found, prepend_if_not_found,' ' insert_before_match, and insert_after_match is permitted' ) path = os.path.expanduser(path) if not os.path.exists(path): raise SaltInvocationError('File not found: {0}'.format(path)) try: file_encoding = __utils__['files.get_encoding'](path) except CommandExecutionError: file_encoding = None if __utils__['files.is_binary'](path): if not file_encoding: raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if insert_before_match or insert_after_match: if insert_before_match: if not isinstance(insert_before_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_before_match parameter.' ) elif insert_after_match: if not isinstance(insert_after_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_after_match parameter.' ) if append_newline is None and not content.endswith((os.linesep, '\n')): append_newline = True # Split the content into a list of lines, removing newline characters. To # ensure that we handle both Windows and POSIX newlines, first split on # Windows newlines, and then split on POSIX newlines. split_content = [] for win_line in content.split('\r\n'): for content_line in win_line.split('\n'): split_content.append(content_line) line_count = len(split_content) has_changes = False orig_file = [] new_file = [] in_block = False block_found = False linesep = None def _add_content(linesep, lines=None, include_marker_start=True, end_line=None): if lines is None: lines = [] include_marker_start = True if end_line is None: end_line = marker_end end_line = end_line.rstrip('\r\n') + linesep if include_marker_start: lines.append(marker_start + linesep) if split_content: for index, content_line in enumerate(split_content, 1): if index != line_count: lines.append(content_line + linesep) else: # We're on the last line of the content block if append_newline: lines.append(content_line + linesep) lines.append(end_line) else: lines.append(content_line + end_line) else: lines.append(end_line) return lines # We do not use in-place editing to avoid file attrs modifications when # no changes are required and to avoid any file access on a partially # written file. try: fi_file = io.open(path, mode='r', encoding=file_encoding, newline='') for line in fi_file: write_line_to_new_file = True if linesep is None: # Auto-detect line separator if line.endswith('\r\n'): linesep = '\r\n' elif line.endswith('\n'): linesep = '\n' else: # No newline(s) in file, fall back to system's linesep linesep = os.linesep if marker_start in line: # We've entered the content block in_block = True else: if in_block: # We're not going to write the lines from the old file to # the new file until we have exited the block. write_line_to_new_file = False marker_end_pos = line.find(marker_end) if marker_end_pos != -1: # End of block detected in_block = False # We've found and exited the block block_found = True _add_content(linesep, lines=new_file, include_marker_start=False, end_line=line[marker_end_pos:]) # Save the line from the original file orig_file.append(line) if write_line_to_new_file: new_file.append(line) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read from {0}: {1}'.format(path, exc) ) finally: if linesep is None: # If the file was empty, we will not have set linesep yet. Assume # the system's line separator. This is needed for when we # prepend/append later on. linesep = os.linesep try: fi_file.close() except Exception: pass if in_block: # unterminated block => bad, always fail raise CommandExecutionError( 'Unterminated marked block. End of file reached before marker_end.' ) if not block_found: if prepend_if_not_found: # add the markers and content at the beginning of file prepended_content = _add_content(linesep) prepended_content.extend(new_file) new_file = prepended_content block_found = True elif append_if_not_found: # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(linesep): new_file[-1] += linesep # add the markers and content at the end of file _add_content(linesep, lines=new_file) block_found = True elif insert_before_match or insert_after_match: match_regex = insert_before_match or insert_after_match match_idx = [i for i, item in enumerate(orig_file) if re.search(match_regex, item)] if match_idx: match_idx = match_idx[0] for line in _add_content(linesep): if insert_after_match: match_idx += 1 new_file.insert(match_idx, line) if insert_before_match: match_idx += 1 block_found = True if not block_found: raise CommandExecutionError( 'Cannot edit marked block. Markers were not found in file.' ) diff = __utils__['stringutils.get_diff'](orig_file, new_file) has_changes = diff is not '' if has_changes and not dry_run: # changes detected # backup file attrs perms = {} perms['user'] = get_user(path) perms['group'] = get_group(path) perms['mode'] = salt.utils.files.normalize_mode(get_mode(path)) # backup old content if backup is not False: backup_path = '{0}{1}'.format(path, backup) shutil.copy2(path, backup_path) # copy2 does not preserve ownership check_perms(backup_path, None, perms['user'], perms['group'], perms['mode']) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line, encoding=file_encoding)) finally: fh_.close() # this may have overwritten file attrs check_perms(path, None, perms['user'], perms['group'], perms['mode']) if show_changes: return diff return has_changes def search(path, pattern, flags=8, bufsize=1, ignore_if_missing=False, multiline=False ): ''' .. versionadded:: 0.17.0 Search for occurrences of a pattern in a file Except for multiline, params are identical to :py:func:`~salt.modules.file.replace`. multiline If true, inserts 'MULTILINE' into ``flags`` and sets ``bufsize`` to 'file'. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' file.search /etc/crontab 'mymaintenance.sh' ''' if multiline: flags = _add_flags(flags, 'MULTILINE') bufsize = 'file' # This function wraps file.replace on purpose in order to enforce # consistent usage, compatible regex's, expected behavior, *and* bugs. :) # Any enhancements or fixes to one should affect the other. return replace(path, pattern, '', flags=flags, bufsize=bufsize, dry_run=True, search_only=True, show_changes=False, ignore_if_missing=ignore_if_missing) def patch(originalfile, patchfile, options='', dry_run=False): ''' .. versionadded:: 0.10.4 Apply a patch to a file or directory. Equivalent to: .. code-block:: bash patch <options> -i <patchfile> <originalfile> Or, when a directory is patched: .. code-block:: bash patch <options> -i <patchfile> -d <originalfile> -p0 originalfile The full path to the file or directory to be patched patchfile A patch file to apply to ``originalfile`` options Options to pass to patch. CLI Example: .. code-block:: bash salt '*' file.patch /opt/file.txt /tmp/file.txt.patch ''' patchpath = salt.utils.path.which('patch') if not patchpath: raise CommandExecutionError( 'patch executable not found. Is the distribution\'s patch ' 'package installed?' ) cmd = [patchpath] cmd.extend(salt.utils.args.shlex_split(options)) if dry_run: if __grains__['kernel'] in ('FreeBSD', 'OpenBSD'): cmd.append('-C') else: cmd.append('--dry-run') # this argument prevents interactive prompts when the patch fails to apply. # the exit code will still be greater than 0 if that is the case. if '-N' not in cmd and '--forward' not in cmd: cmd.append('--forward') has_rejectfile_option = False for option in cmd: if option == '-r' or option.startswith('-r ') \ or option.startswith('--reject-file'): has_rejectfile_option = True break # by default, patch will write rejected patch files to <filename>.rej. # this option prevents that. if not has_rejectfile_option: cmd.append('--reject-file=-') cmd.extend(['-i', patchfile]) if os.path.isdir(originalfile): cmd.extend(['-d', originalfile]) has_strip_option = False for option in cmd: if option.startswith('-p') or option.startswith('--strip='): has_strip_option = True break if not has_strip_option: cmd.append('--strip=0') else: cmd.append(originalfile) return __salt__['cmd.run_all'](cmd, python_shell=False) def contains(path, text): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the file at ``path`` contains ``text`` CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False stripped_text = six.text_type(text).strip() try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if stripped_text in chunk: return True return False except (IOError, OSError): return False def contains_regex(path, regex, lchar=''): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the given regular expression matches on any line in the text of a given file. If the lchar argument (leading char) is specified, it will strip `lchar` from the left side of each line before trying to match CLI Example: .. code-block:: bash salt '*' file.contains_regex /etc/crontab ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.files.fopen(path, 'r') as target: for line in target: line = salt.utils.stringutils.to_unicode(line) if lchar: line = line.lstrip(lchar) if re.search(regex, line): return True return False except (IOError, OSError): return False def contains_glob(path, glob_expr): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the given glob matches a string in the named file CLI Example: .. code-block:: bash salt '*' file.contains_glob /etc/foobar '*cheese*' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if fnmatch.fnmatch(chunk, glob_expr): return True return False except (IOError, OSError): return False def append(path, *args, **kwargs): ''' .. versionadded:: 0.9.5 Append text to the end of a file path path to file `*args` strings to append to file CLI Example: .. code-block:: bash salt '*' file.append /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.append /etc/motd args='cheese=spam' salt '*' file.append /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) # Largely inspired by Fabric's contrib.files.append() if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] # Make sure we have a newline at the end of the file. Do this in binary # mode so SEEK_END with nonzero offset will work. with salt.utils.files.fopen(path, 'rb+') as ofile: linesep = salt.utils.stringutils.to_bytes(os.linesep) try: ofile.seek(-len(linesep), os.SEEK_END) except IOError as exc: if exc.errno in (errno.EINVAL, errno.ESPIPE): # Empty file, simply append lines at the beginning of the file pass else: raise else: if ofile.read(len(linesep)) != linesep: ofile.seek(0, os.SEEK_END) ofile.write(linesep) # Append lines in text mode with salt.utils.files.fopen(path, 'a') as ofile: for new_line in args: ofile.write( salt.utils.stringutils.to_str( '{0}{1}'.format(new_line, os.linesep) ) ) return 'Wrote {0} lines to "{1}"'.format(len(args), path) def prepend(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Prepend text to the beginning of a file path path to file `*args` strings to prepend to the file CLI Example: .. code-block:: bash salt '*' file.prepend /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.prepend /etc/motd args='cheese=spam' salt '*' file.prepend /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] try: with salt.utils.files.fopen(path) as fhr: contents = [salt.utils.stringutils.to_unicode(line) for line in fhr.readlines()] except IOError: contents = [] preface = [] for line in args: preface.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, 'w') as ofile: contents = preface + contents ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Prepended {0} lines to "{1}"'.format(len(args), path) def write(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Write text to a file, overwriting any existing contents. path path to file `*args` strings to write to the file CLI Example: .. code-block:: bash salt '*' file.write /etc/motd \\ "With all thine offerings thou shalt offer salt." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.write /etc/motd args='cheese=spam' salt '*' file.write /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] contents = [] for line in args: contents.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, "w") as ofile: ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Wrote {0} lines to "{1}"'.format(len(contents), path) def touch(name, atime=None, mtime=None): ''' .. versionadded:: 0.9.5 Just like the ``touch`` command, create a file if it doesn't exist or simply update the atime and mtime if it already does. atime: Access time in Unix epoch time. Set it to 0 to set atime of the file with Unix date of birth. If this parameter isn't set, atime will be set with current time. mtime: Last modification in Unix epoch time. Set it to 0 to set mtime of the file with Unix date of birth. If this parameter isn't set, mtime will be set with current time. CLI Example: .. code-block:: bash salt '*' file.touch /var/log/emptyfile ''' name = os.path.expanduser(name) if atime and atime.isdigit(): atime = int(atime) if mtime and mtime.isdigit(): mtime = int(mtime) try: if not os.path.exists(name): with salt.utils.files.fopen(name, 'a'): pass if atime is None and mtime is None: times = None elif mtime is None and atime is not None: times = (atime, time.time()) elif atime is None and mtime is not None: times = (time.time(), mtime) else: times = (atime, mtime) os.utime(name, times) except TypeError: raise SaltInvocationError('atime and mtime must be integers') except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return os.path.exists(name) def tail(path, lines): ''' .. versionadded:: Neon Read the last n lines from a file path path to file lines number of lines to read CLI Example: .. code-block:: bash salt '*' file.tail /path/to/file 10 ''' path = os.path.expanduser(path) lines_found = [] buffer_size = 4098 if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot tail a binary file: {0}'.format(path)) try: lines = int(lines) except ValueError: raise SaltInvocationError('file.tail: \'lines\' value must be an integer') try: with salt.utils.fopen(path) as tail_fh: blk_cnt = 1 size = os.stat(path).st_size if size > buffer_size: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size), os.linesep) for i in range(lines): while len(data) == 1 and ((blk_cnt * buffer_size) < size): blk_cnt += 1 line = data[0] try: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size) + line, os.linesep) except IOError: tail_fh.seek(0) data = string.split(tail_fh.read(size - (buffer_size * (blk_cnt - 1))) + line, os.linesep) line = data[-1] data.pop() lines_found.append(line) return lines_found[-lines:] except (OSError, IOError): raise CommandExecutionError('Could not tail \'{0}\''.format(path)) def seek_read(path, size, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and read it path path to file seek amount to read at once offset offset to start into the file CLI Example: .. code-block:: bash salt '*' file.seek_read /path/to/file 4096 0 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_RDONLY) try: os.lseek(seek_fh, int(offset), 0) data = os.read(seek_fh, int(size)) finally: os.close(seek_fh) return data def seek_write(path, data, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and write to it path path to file data data to write to file offset position in file to start writing CLI Example: .. code-block:: bash salt '*' file.seek_write /path/to/file 'some data' 4096 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_WRONLY) try: os.lseek(seek_fh, int(offset), 0) ret = os.write(seek_fh, data) os.fsync(seek_fh) finally: os.close(seek_fh) return ret def truncate(path, length): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and delete everything after that point path path to file length offset into file to truncate CLI Example: .. code-block:: bash salt '*' file.truncate /path/to/file 512 ''' path = os.path.expanduser(path) with salt.utils.files.fopen(path, 'rb+') as seek_fh: seek_fh.truncate(int(length)) def link(src, path): ''' .. versionadded:: 2014.1.0 Create a hard link to a file CLI Example: .. code-block:: bash salt '*' file.link /path/to/file /path/to/link ''' src = os.path.expanduser(src) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.link(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def is_link(path): ''' Check if the path is a symbolic link CLI Example: .. code-block:: bash salt '*' file.is_link /path/to/link ''' # This function exists because os.path.islink does not support Windows, # therefore a custom function will need to be called. This function # therefore helps API consistency by providing a single function to call for # both operating systems. return os.path.islink(os.path.expanduser(path)) def symlink(src, path): ''' Create a symbolic link (symlink, soft link) to a file CLI Example: .. code-block:: bash salt '*' file.symlink /path/to/file /path/to/link ''' path = os.path.expanduser(path) try: if os.path.normpath(os.readlink(path)) == os.path.normpath(src): log.debug('link already in correct state: %s -> %s', path, src) return True except OSError: pass if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: os.symlink(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def rename(src, dst): ''' Rename a file or directory CLI Example: .. code-block:: bash salt '*' file.rename /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.rename(src, dst) return True except OSError: raise CommandExecutionError( 'Could not rename \'{0}\' to \'{1}\''.format(src, dst) ) return False def copy(src, dst, recurse=False, remove_existing=False): ''' Copy a file or directory from source to dst In order to copy a directory, the recurse flag is required, and will by default overwrite files in the destination with the same path, and retain all other existing files. (similar to cp -r on unix) remove_existing will remove all files in the target directory, and then copy files from the source. .. note:: The copy function accepts paths that are local to the Salt minion. This function does not support salt://, http://, or the other additional file paths that are supported by :mod:`states.file.managed <salt.states.file.managed>` and :mod:`states.file.recurse <salt.states.file.recurse>`. CLI Example: .. code-block:: bash salt '*' file.copy /path/to/src /path/to/dst salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True remove_existing=True ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') if not os.path.exists(src): raise CommandExecutionError('No such file or directory \'{0}\''.format(src)) if not salt.utils.platform.is_windows(): pre_user = get_user(src) pre_group = get_group(src) pre_mode = salt.utils.files.normalize_mode(get_mode(src)) try: if (os.path.exists(dst) and os.path.isdir(dst)) or os.path.isdir(src): if not recurse: raise SaltInvocationError( "Cannot copy overwriting a directory without recurse flag set to true!") if remove_existing: if os.path.exists(dst): shutil.rmtree(dst) shutil.copytree(src, dst) else: salt.utils.files.recursive_copy(src, dst) else: shutil.copyfile(src, dst) except OSError: raise CommandExecutionError( 'Could not copy \'{0}\' to \'{1}\''.format(src, dst) ) if not salt.utils.platform.is_windows(): check_perms(dst, None, pre_user, pre_group, pre_mode) return True def lstat(path): ''' .. versionadded:: 2014.1.0 Returns the lstat attributes for the given file or dir. Does not support symbolic links. CLI Example: .. code-block:: bash salt '*' file.lstat /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to file must be absolute.') try: lst = os.lstat(path) return dict((key, getattr(lst, key)) for key in ('st_atime', 'st_ctime', 'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid')) except Exception: return {} def access(path, mode): ''' .. versionadded:: 2014.1.0 Test whether the Salt process has the specified access to the file. One of the following modes must be specified: .. code-block::text f: Test the existence of the path r: Test the readability of the path w: Test the writability of the path x: Test whether the path can be executed CLI Example: .. code-block:: bash salt '*' file.access /path/to/file f salt '*' file.access /path/to/file x ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') modes = {'f': os.F_OK, 'r': os.R_OK, 'w': os.W_OK, 'x': os.X_OK} if mode in modes: return os.access(path, modes[mode]) elif mode in six.itervalues(modes): return os.access(path, mode) else: raise SaltInvocationError('Invalid mode specified.') def read(path, binary=False): ''' .. versionadded:: 2017.7.0 Return the content of the file. CLI Example: .. code-block:: bash salt '*' file.read /path/to/file ''' access_mode = 'r' if binary is True: access_mode += 'b' with salt.utils.files.fopen(path, access_mode) as file_obj: return salt.utils.stringutils.to_unicode(file_obj.read()) def readlink(path, canonicalize=False): ''' .. versionadded:: 2014.1.0 Return the path that a symlink points to If canonicalize is set to True, then it return the final target CLI Example: .. code-block:: bash salt '*' file.readlink /path/to/link ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') if not os.path.islink(path): raise SaltInvocationError('A valid link was not specified.') if canonicalize: return os.path.realpath(path) else: return os.readlink(path) def readdir(path): ''' .. versionadded:: 2014.1.0 Return a list containing the contents of a directory CLI Example: .. code-block:: bash salt '*' file.readdir /path/to/dir/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Dir path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') dirents = ['.', '..'] dirents.extend(os.listdir(path)) return dirents def statvfs(path): ''' .. versionadded:: 2014.1.0 Perform a statvfs call against the filesystem that the file resides on CLI Example: .. code-block:: bash salt '*' file.statvfs /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: stv = os.statvfs(path) return dict((key, getattr(stv, key)) for key in ('f_bavail', 'f_bfree', 'f_blocks', 'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag', 'f_frsize', 'f_namemax')) except (OSError, IOError): raise CommandExecutionError('Could not statvfs \'{0}\''.format(path)) return False def stats(path, hash_type=None, follow_symlinks=True): ''' Return a dict containing the stats for a given file CLI Example: .. code-block:: bash salt '*' file.stats /etc/passwd ''' path = os.path.expanduser(path) ret = {} if not os.path.exists(path): try: # Broken symlinks will return False for os.path.exists(), but still # have a uid and gid pstat = os.lstat(path) except OSError: # Not a broken symlink, just a nonexistent path # NOTE: The file.directory state checks the content of the error # message in this exception. Any changes made to the message for this # exception will reflect the file.directory state as well, and will # likely require changes there. raise CommandExecutionError('Path not found: {0}'.format(path)) else: if follow_symlinks: pstat = os.stat(path) else: pstat = os.lstat(path) ret['inode'] = pstat.st_ino ret['uid'] = pstat.st_uid ret['gid'] = pstat.st_gid ret['group'] = gid_to_group(pstat.st_gid) ret['user'] = uid_to_user(pstat.st_uid) ret['atime'] = pstat.st_atime ret['mtime'] = pstat.st_mtime ret['ctime'] = pstat.st_ctime ret['size'] = pstat.st_size ret['mode'] = six.text_type(oct(stat.S_IMODE(pstat.st_mode))) if hash_type: ret['sum'] = get_hash(path, hash_type) ret['type'] = 'file' if stat.S_ISDIR(pstat.st_mode): ret['type'] = 'dir' if stat.S_ISCHR(pstat.st_mode): ret['type'] = 'char' if stat.S_ISBLK(pstat.st_mode): ret['type'] = 'block' if stat.S_ISREG(pstat.st_mode): ret['type'] = 'file' if stat.S_ISLNK(pstat.st_mode): ret['type'] = 'link' if stat.S_ISFIFO(pstat.st_mode): ret['type'] = 'pipe' if stat.S_ISSOCK(pstat.st_mode): ret['type'] = 'socket' ret['target'] = os.path.realpath(path) return ret def rmdir(path): ''' .. versionadded:: 2014.1.0 Remove the specified directory. Fails if a directory is not empty. CLI Example: .. code-block:: bash salt '*' file.rmdir /tmp/foo/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') try: os.rmdir(path) return True except OSError as exc: return exc.strerror def remove(path, **kwargs): ''' Remove the named file. If a directory is supplied, it will be recursively deleted. CLI Example: .. code-block:: bash salt '*' file.remove /tmp/foo ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute: {0}'.format(path)) try: if os.path.isfile(path) or os.path.islink(path): os.remove(path) return True elif os.path.isdir(path): shutil.rmtree(path) return True except (OSError, IOError) as exc: raise CommandExecutionError( 'Could not remove \'{0}\': {1}'.format(path, exc) ) return False def directory_exists(path): ''' Tests to see if path is a valid directory. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.directory_exists /etc ''' return os.path.isdir(os.path.expanduser(path)) def file_exists(path): ''' Tests to see if path is a valid file. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.file_exists /etc/passwd ''' return os.path.isfile(os.path.expanduser(path)) def path_exists_glob(path): ''' Tests to see if path after expansion is a valid path (file or directory). Expansion allows usage of ? * and character ranges []. Tilde expansion is not supported. Returns True/False. .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' file.path_exists_glob /etc/pam*/pass* ''' return True if glob.glob(os.path.expanduser(path)) else False def restorecon(path, recursive=False): ''' Reset the SELinux context on a given path CLI Example: .. code-block:: bash salt '*' file.restorecon /home/user/.ssh/authorized_keys ''' if recursive: cmd = ['restorecon', '-FR', path] else: cmd = ['restorecon', '-F', path] return not __salt__['cmd.retcode'](cmd, python_shell=False) def get_selinux_context(path): ''' Get an SELinux context from a given path CLI Example: .. code-block:: bash salt '*' file.get_selinux_context /etc/hosts ''' out = __salt__['cmd.run'](['ls', '-Z', path], python_shell=False) try: ret = re.search(r'\w+:\w+:\w+:\w+', out).group(0) except AttributeError: ret = ( 'No selinux context information is available for {0}'.format(path) ) return ret def set_selinux_context(path, user=None, role=None, type=None, # pylint: disable=W0622 range=None, # pylint: disable=W0622 persist=False): ''' .. versionchanged:: Neon Added persist option Set a specific SELinux label on a given path CLI Example: .. code-block:: bash salt '*' file.set_selinux_context path <user> <role> <type> <range> salt '*' file.set_selinux_context /etc/yum.repos.d/epel.repo system_u object_r system_conf_t s0 ''' if not any((user, role, type, range)): return False if persist: fcontext_result = __salt__['selinux.fcontext_add_policy'](path, sel_type=type, sel_user=user, sel_level=range) if fcontext_result.get('retcode', None) is not 0: # Problem setting fcontext policy raise CommandExecutionError( 'Problem setting fcontext: {0}'.format(fcontext_result) ) cmd = ['chcon'] if user: cmd.extend(['-u', user]) if role: cmd.extend(['-r', role]) if type: cmd.extend(['-t', type]) if range: cmd.extend(['-l', range]) cmd.append(path) ret = not __salt__['cmd.retcode'](cmd, python_shell=False) if ret: return get_selinux_context(path) else: return ret def source_list(source, source_hash, saltenv): ''' Check the source list and return the source to use CLI Example: .. code-block:: bash salt '*' file.source_list salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' base ''' contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv) if contextkey in __context__: return __context__[contextkey] # get the master file list if isinstance(source, list): mfiles = [(f, saltenv) for f in __salt__['cp.list_master'](saltenv)] mdirs = [(d, saltenv) for d in __salt__['cp.list_master_dirs'](saltenv)] for single in source: if isinstance(single, dict): single = next(iter(single)) path, senv = salt.utils.url.parse(single) if senv: mfiles += [(f, senv) for f in __salt__['cp.list_master'](senv)] mdirs += [(d, senv) for d in __salt__['cp.list_master_dirs'](senv)] ret = None for single in source: if isinstance(single, dict): # check the proto, if it is http or ftp then download the file # to check, if it is salt then check the master list # if it is a local file, check if the file exists if len(single) != 1: continue single_src = next(iter(single)) single_hash = single[single_src] if single[single_src] else source_hash urlparsed_single_src = _urlparse(single_src) # Fix this for Windows if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_single_src.scheme.lower() in string.ascii_lowercase: urlparsed_single_src = _urlparse('file://' + single_src) proto = urlparsed_single_src.scheme if proto == 'salt': path, senv = salt.utils.url.parse(single_src) if not senv: senv = saltenv if (path, saltenv) in mfiles or (path, saltenv) in mdirs: ret = (single_src, single_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single_src, single_hash) break elif proto == 'file' and ( os.path.exists(urlparsed_single_src.netloc) or os.path.exists(urlparsed_single_src.path) or os.path.exists(os.path.join( urlparsed_single_src.netloc, urlparsed_single_src.path))): ret = (single_src, single_hash) break elif single_src.startswith(os.sep) and os.path.exists(single_src): ret = (single_src, single_hash) break elif isinstance(single, six.string_types): path, senv = salt.utils.url.parse(single) if not senv: senv = saltenv if (path, senv) in mfiles or (path, senv) in mdirs: ret = (single, source_hash) break urlparsed_src = _urlparse(single) if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_src.scheme.lower() in string.ascii_lowercase: urlparsed_src = _urlparse('file://' + single) proto = urlparsed_src.scheme if proto == 'file' and ( os.path.exists(urlparsed_src.netloc) or os.path.exists(urlparsed_src.path) or os.path.exists(os.path.join( urlparsed_src.netloc, urlparsed_src.path))): ret = (single, source_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single, source_hash) break elif single.startswith(os.sep) and os.path.exists(single): ret = (single, source_hash) break if ret is None: # None of the list items matched raise CommandExecutionError( 'none of the specified sources were found' ) else: ret = (source, source_hash) __context__[contextkey] = ret return ret def apply_template_on_contents( contents, template, context, defaults, saltenv): ''' Return the contents after applying the templating engine contents template string template template format context Overrides default context variables passed to the template. defaults Default context passed to the template. CLI Example: .. code-block:: bash salt '*' file.apply_template_on_contents \\ contents='This is a {{ template }} string.' \\ template=jinja \\ "context={}" "defaults={'template': 'cool'}" \\ saltenv=base ''' if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) # Apply templating contents = salt.utils.templates.TEMPLATE_REGISTRY[template]( contents, from_str=True, to_str=True, context=context_dict, saltenv=saltenv, grains=__opts__['grains'], pillar=__pillar__, salt=__salt__, opts=__opts__)['data'] if six.PY2: contents = contents.encode('utf-8') elif six.PY3 and isinstance(contents, bytes): # bytes -> str contents = contents.decode('utf-8') else: ret = {} ret['result'] = False ret['comment'] = ('Specified template format {0} is not supported' ).format(template) return ret return contents def get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify=False, **kwargs): ''' Return the managed file data for file.managed name location where the file lives on the server template template format source managed source file source_hash hash of the source file source_hash_name When ``source_hash`` refers to a remote file, this specifies the filename to look for in that file. .. versionadded:: 2016.3.5 user Owner of file group Group owner of file mode Permissions of file attrs Attributes of file .. versionadded:: 2018.3.0 context Variables to add to the template context defaults Default values of for context_dict skip_verify If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' file.get_managed /etc/httpd/conf.d/httpd.conf jinja salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' None root root '755' base None None ''' # Copy the file to the minion and templatize it sfn = '' source_sum = {} def _get_local_file_source_sum(path): ''' DRY helper for getting the source_sum value from a locally cached path. ''' return {'hsum': get_hash(path, form='sha256'), 'hash_type': 'sha256'} # If we have a source defined, let's figure out what the hash is if source: urlparsed_source = _urlparse(source) if urlparsed_source.scheme in salt.utils.files.VALID_PROTOS: parsed_scheme = urlparsed_source.scheme else: parsed_scheme = '' parsed_path = os.path.join( urlparsed_source.netloc, urlparsed_source.path).rstrip(os.sep) unix_local_source = parsed_scheme in ('file', '') if parsed_scheme == '': parsed_path = sfn = source if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg elif parsed_scheme == 'file': sfn = parsed_path if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg if parsed_scheme and parsed_scheme.lower() in string.ascii_lowercase: parsed_path = ':'.join([parsed_scheme, parsed_path]) parsed_scheme = 'file' if parsed_scheme == 'salt': source_sum = __salt__['cp.hash_file'](source, saltenv) if not source_sum: return '', {}, 'Source file {0} not found in saltenv \'{1}\''.format(source, saltenv) elif not source_hash and unix_local_source: source_sum = _get_local_file_source_sum(parsed_path) elif not source_hash and source.startswith(os.sep): # This should happen on Windows source_sum = _get_local_file_source_sum(source) else: if not skip_verify: if source_hash: try: source_sum = get_source_sum(name, source, source_hash, source_hash_name, saltenv) except CommandExecutionError as exc: return '', {}, exc.strerror else: msg = ( 'Unable to verify upstream hash of source file {0}, ' 'please set source_hash or set skip_verify to True' .format(salt.utils.url.redact_http_basic_auth(source)) ) return '', {}, msg if source and (template or parsed_scheme in salt.utils.files.REMOTE_PROTOS): # Check if we have the template or remote file cached cache_refetch = False cached_dest = __salt__['cp.is_cached'](source, saltenv) if cached_dest and (source_hash or skip_verify): htype = source_sum.get('hash_type', 'sha256') cached_sum = get_hash(cached_dest, form=htype) if skip_verify: # prev: if skip_verify or cached_sum == source_sum['hsum']: # but `cached_sum == source_sum['hsum']` is elliptical as prev if sfn = cached_dest source_sum = {'hsum': cached_sum, 'hash_type': htype} elif cached_sum != source_sum.get('hsum', __opts__['hash_type']): cache_refetch = True else: sfn = cached_dest # If we didn't have the template or remote file, or the file has been # updated and the cache has to be refreshed, download the file. if not sfn or cache_refetch: try: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum.get('hsum')) except Exception as exc: # A 404 or other error code may raise an exception, catch it # and return a comment that will fail the calling state. _source = salt.utils.url.redact_http_basic_auth(source) return '', {}, 'Failed to cache {0}: {1}'.format(_source, exc) # If cache failed, sfn will be False, so do a truth check on sfn first # as invoking os.path.exists() on a bool raises a TypeError. if not sfn or not os.path.exists(sfn): _source = salt.utils.url.redact_http_basic_auth(source) return sfn, {}, 'Source file \'{0}\' not found'.format(_source) if sfn == name: raise SaltInvocationError( 'Source file cannot be the same as destination' ) if template: if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, name=name, source=source, user=user, group=group, mode=mode, attrs=attrs, saltenv=saltenv, context=context_dict, salt=__salt__, pillar=__pillar__, grains=__opts__['grains'], opts=__opts__, **kwargs) else: return sfn, {}, ('Specified template format {0} is not supported' ).format(template) if data['result']: sfn = data['data'] hsum = get_hash(sfn, form='sha256') source_sum = {'hash_type': 'sha256', 'hsum': hsum} else: __clean_tmp(sfn) return sfn, {}, data['data'] return sfn, source_sum, '' def extract_hash(hash_fn, hash_type='sha256', file_name='', source='', source_hash_name=None): ''' .. versionchanged:: 2016.3.5 Prior to this version, only the ``file_name`` argument was considered for filename matches in the hash file. This would be problematic for cases in which the user was relying on a remote checksum file that they do not control, and they wished to use a different name for that file on the minion from the filename on the remote server (and in the checksum file). For example, managing ``/tmp/myfile.tar.gz`` when the remote file was at ``https://mydomain.tld/different_name.tar.gz``. The :py:func:`file.managed <salt.states.file.managed>` state now also passes this function the source URI as well as the ``source_hash_name`` (if specified). In cases where ``source_hash_name`` is specified, it takes precedence over both the ``file_name`` and ``source``. When it is not specified, ``file_name`` takes precedence over ``source``. This allows for better capability for matching hashes. .. versionchanged:: 2016.11.0 File name and source URI matches are no longer disregarded when ``source_hash_name`` is specified. They will be used as fallback matches if there is no match to the ``source_hash_name`` value. This routine is called from the :mod:`file.managed <salt.states.file.managed>` state to pull a hash from a remote file. Regular expressions are used line by line on the ``source_hash`` file, to find a potential candidate of the indicated hash type. This avoids many problems of arbitrary file layout rules. It specifically permits pulling hash codes from debian ``*.dsc`` files. If no exact match of a hash and filename are found, then the first hash found (if any) will be returned. If no hashes at all are found, then ``None`` will be returned. For example: .. code-block:: yaml openerp_7.0-latest-1.tar.gz: file.managed: - name: /tmp/openerp_7.0-20121227-075624-1_all.deb - source: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.tar.gz - source_hash: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.dsc CLI Example: .. code-block:: bash salt '*' file.extract_hash /path/to/hash/file sha512 /etc/foo ''' hash_len = HASHES.get(hash_type) if hash_len is None: if hash_type: log.warning( 'file.extract_hash: Unsupported hash_type \'%s\', falling ' 'back to matching any supported hash_type', hash_type ) hash_type = '' hash_len_expr = '{0},{1}'.format(min(HASHES_REVMAP), max(HASHES_REVMAP)) else: hash_len_expr = six.text_type(hash_len) filename_separators = string.whitespace + r'\/' if source_hash_name: if not isinstance(source_hash_name, six.string_types): source_hash_name = six.text_type(source_hash_name) source_hash_name_idx = (len(source_hash_name) + 1) * -1 log.debug( 'file.extract_hash: Extracting %s hash for file matching ' 'source_hash_name \'%s\'', 'any supported' if not hash_type else hash_type, source_hash_name ) if file_name: if not isinstance(file_name, six.string_types): file_name = six.text_type(file_name) file_name_basename = os.path.basename(file_name) file_name_idx = (len(file_name_basename) + 1) * -1 if source: if not isinstance(source, six.string_types): source = six.text_type(source) urlparsed_source = _urlparse(source) source_basename = os.path.basename( urlparsed_source.path or urlparsed_source.netloc ) source_idx = (len(source_basename) + 1) * -1 basename_searches = [x for x in (file_name, source) if x] if basename_searches: log.debug( 'file.extract_hash: %s %s hash for file matching%s: %s', 'If no source_hash_name match found, will extract' if source_hash_name else 'Extracting', 'any supported' if not hash_type else hash_type, '' if len(basename_searches) == 1 else ' either of the following', ', '.join(basename_searches) ) partial = None found = {} with salt.utils.files.fopen(hash_fn, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line.strip()) hash_re = r'(?i)(?<![a-z0-9])([a-f0-9]{' + hash_len_expr + '})(?![a-z0-9])' hash_match = re.search(hash_re, line) matched = None if hash_match: matched_hsum = hash_match.group(1) if matched_hsum is not None: matched_type = HASHES_REVMAP.get(len(matched_hsum)) if matched_type is None: # There was a match, but it's not of the correct length # to match one of the supported hash types. matched = None else: matched = {'hsum': matched_hsum, 'hash_type': matched_type} if matched is None: log.debug( 'file.extract_hash: In line \'%s\', no %shash found', line, '' if not hash_type else hash_type + ' ' ) continue if partial is None: partial = matched def _add_to_matches(found, line, match_type, value, matched): log.debug( 'file.extract_hash: Line \'%s\' matches %s \'%s\'', line, match_type, value ) found.setdefault(match_type, []).append(matched) hash_matched = False if source_hash_name: if line.endswith(source_hash_name): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[source_hash_name_idx] in string.whitespace: _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source_hash_name) + r'\s+', line): _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True if file_name: if line.endswith(file_name_basename): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[file_name_idx] in filename_separators: _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(file_name) + r'\s+', line): _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True if source: if line.endswith(source_basename): # Same as above, we can't just do an rsplit here. try: if line[source_idx] in filename_separators: _add_to_matches(found, line, 'source', source, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source) + r'\s+', line): _add_to_matches(found, line, 'source', source, matched) hash_matched = True if not hash_matched: log.debug( 'file.extract_hash: Line \'%s\' contains %s hash ' '\'%s\', but line did not meet the search criteria', line, matched['hash_type'], matched['hsum'] ) for found_type, found_str in (('source_hash_name', source_hash_name), ('file_name', file_name), ('source', source)): if found_type in found: if len(found[found_type]) > 1: log.debug( 'file.extract_hash: Multiple %s matches for %s: %s', found_type, found_str, ', '.join( ['{0} ({1})'.format(x['hsum'], x['hash_type']) for x in found[found_type]] ) ) ret = found[found_type][0] log.debug( 'file.extract_hash: Returning %s hash \'%s\' as a match of %s', ret['hash_type'], ret['hsum'], found_str ) return ret if partial: log.debug( 'file.extract_hash: Returning the partially identified %s hash ' '\'%s\'', partial['hash_type'], partial['hsum'] ) return partial log.debug('file.extract_hash: No matches, returning None') return None def check_perms(name, ret, user, group, mode, attrs=None, follow_symlinks=False, seuser=None, serole=None, setype=None, serange=None): ''' .. versionchanged:: Neon Added selinux options Check the permissions on files, modify attributes and chown if needed. File attributes are only verified if lsattr(1) is installed. CLI Example: .. code-block:: bash salt '*' file.check_perms /etc/sudoers '{}' root root 400 ai .. versionchanged:: 2014.1.3 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': [], 'result': True} orig_comment = '' else: orig_comment = ret['comment'] ret['comment'] = [] # Check permissions perms = {} cur = stats(name, follow_symlinks=follow_symlinks) perms['luser'] = cur['user'] perms['lgroup'] = cur['group'] perms['lmode'] = salt.utils.files.normalize_mode(cur['mode']) is_dir = os.path.isdir(name) is_link = os.path.islink(name) if attrs is not None \ and not salt.utils.platform.is_windows() \ and not is_dir and not is_link: try: lattrs = lsattr(name) except SaltInvocationError: lattrs = None if lattrs is not None: # List attributes on file perms['lattrs'] = ''.join(lattrs.get(name, '')) # Remove attributes on file so changes can be enforced. if perms['lattrs']: chattr(name, operator='remove', attributes=perms['lattrs']) # user/group changes if needed, then check if it worked if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid(perms['luser']) ) or ( not salt.utils.platform.is_windows() and user != perms['luser'] ): perms['cuser'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid(perms['lgroup']) ) or ( not salt.utils.platform.is_windows() and group != perms['lgroup'] ): perms['cgroup'] = group if 'cuser' in perms or 'cgroup' in perms: if not __opts__['test']: if os.path.islink(name) and not follow_symlinks: chown_func = lchown else: chown_func = chown if user is None: user = perms['luser'] if group is None: group = perms['lgroup'] try: chown_func(name, user, group) # Python os.chown() does reset the suid and sgid, # that's why setting the right mode again is needed here. set_mode(name, mode) except OSError: ret['result'] = False if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid( get_user(name, follow_symlinks=follow_symlinks)) and user != '' ) or ( not salt.utils.platform.is_windows() and user != get_user(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['user'] = user else: ret['result'] = False ret['comment'].append('Failed to change user to {0}' .format(user)) elif 'cuser' in perms and user != '': ret['changes']['user'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid( get_group(name, follow_symlinks=follow_symlinks)) and user != '') or ( not salt.utils.platform.is_windows() and group != get_group(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['group'] = group else: ret['result'] = False ret['comment'].append('Failed to change group to {0}' .format(group)) elif 'cgroup' in perms and user != '': ret['changes']['group'] = group if not salt.utils.platform.is_windows() and not is_dir: # Replace attributes on file if it had been removed if perms.get('lattrs', ''): chattr(name, operator='add', attributes=perms['lattrs']) # Mode changes if needed if mode is not None: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: mode = salt.utils.files.normalize_mode(mode) if mode != perms['lmode']: if __opts__['test'] is True: ret['changes']['mode'] = mode else: set_mode(name, mode) if mode != salt.utils.files.normalize_mode(get_mode(name)): ret['result'] = False ret['comment'].append( 'Failed to change mode to {0}'.format(mode) ) else: ret['changes']['mode'] = mode # Modify attributes of file if needed if attrs is not None and not is_dir: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if diff_attrs[0] is not None or diff_attrs[1] is not None: if __opts__['test'] is True: ret['changes']['attrs'] = attrs else: if diff_attrs[0] is not None: chattr(name, operator="add", attributes=diff_attrs[0]) if diff_attrs[1] is not None: chattr(name, operator="remove", attributes=diff_attrs[1]) cmp_attrs = _cmp_attrs(name, attrs) if cmp_attrs[0] is not None or cmp_attrs[1] is not None: ret['result'] = False ret['comment'].append( 'Failed to change attributes to {0}'.format(attrs) ) else: ret['changes']['attrs'] = attrs # Set selinux attributes if needed if salt.utils.platform.is_linux() and (seuser or serole or setype or serange): selinux_error = False try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError: log.error('Unable to get current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to get selinux attributes' ) selinux_error = True if not selinux_error: requested_seuser = None requested_serole = None requested_setype = None requested_serange = None # Only set new selinux variables if updates are needed if seuser and seuser != current_seuser: requested_seuser = seuser if serole and serole != current_serole: requested_serole = serole if setype and setype != current_setype: requested_setype = setype if serange and serange != current_serange: requested_serange = serange if requested_seuser or requested_serole or requested_setype or requested_serange: # selinux updates needed, prep changes output selinux_change_new = '' selinux_change_orig = '' if requested_seuser: selinux_change_new += "User: {0} ".format(requested_seuser) selinux_change_orig += "User: {0} ".format(current_seuser) if requested_serole: selinux_change_new += "Role: {0} ".format(requested_serole) selinux_change_orig += "Role: {0} ".format(current_serole) if requested_setype: selinux_change_new += "Type: {0} ".format(requested_setype) selinux_change_orig += "Type: {0} ".format(current_setype) if requested_serange: selinux_change_new += "Range: {0} ".format(requested_serange) selinux_change_orig += "Range: {0} ".format(current_serange) if __opts__['test']: ret['comment'] = 'File {0} selinux context to be updated'.format(name) ret['result'] = None ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} else: try: # set_selinux_context requires type to be set on any other change if (requested_seuser or requested_serole or requested_serange) and not requested_setype: requested_setype = current_setype result = set_selinux_context(name, user=requested_seuser, role=requested_serole, type=requested_setype, range=requested_serange, persist=True) log.debug('selinux set result: %s', result) current_seuser, current_serole, current_setype, current_serange = result.split(':') except ValueError: log.error('Unable to set current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to set selinux attributes' ) selinux_error = True if not selinux_error: ret['comment'].append('The file {0} is set to be changed'.format(name)) if requested_seuser: if current_seuser != requested_seuser: ret['comment'].append("Unable to update seuser context") ret['result'] = False if requested_serole: if current_serole != requested_serole: ret['comment'].append("Unable to update serole context") ret['result'] = False if requested_setype: if current_setype != requested_setype: ret['comment'].append("Unable to update setype context") ret['result'] = False if requested_serange: if current_serange != requested_serange: ret['comment'].append("Unable to update serange context") ret['result'] = False ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} # Only combine the comment list into a string # after all comments are added above if isinstance(orig_comment, six.string_types): if orig_comment: ret['comment'].insert(0, orig_comment) ret['comment'] = '; '.join(ret['comment']) # Set result to None at the very end of the function, # after all changes have been recorded above if __opts__['test'] is True and ret['changes']: ret['result'] = None return ret, perms def check_managed( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Check to see what changes need to be made for a file CLI Example: .. code-block:: bash salt '*' file.check_managed /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) if comments: __clean_tmp(sfn) return False, comments changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) # Ignore permission for files written temporary directories # Files in any path will still be set correctly using get_managed() if name.startswith(tempfile.gettempdir()): for key in ['user', 'group', 'mode']: changes.pop(key, None) __clean_tmp(sfn) if changes: log.info(changes) comments = ['The following values are set to be changed:\n'] comments.extend('{0}: {1}\n'.format(key, val) for key, val in six.iteritems(changes)) return None, ''.join(comments) return True, 'The file {0} is in the correct state'.format(name) def check_managed_changes( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, keep_mode=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Return a dictionary of what changes need to be made for a file .. versionchanged:: Neon selinux attributes added CLI Example: .. code-block:: bash salt '*' file.check_managed_changes /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if comments: __clean_tmp(sfn) raise CommandExecutionError(comments) if sfn and source and keep_mode: if _urlparse(source).scheme in ('salt', 'file') \ or source.startswith('/'): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) __clean_tmp(sfn) return changes def check_file_meta( name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents=None, seuser=None, serole=None, setype=None, serange=None): ''' Check for the changes in the file metadata. CLI Example: .. code-block:: bash salt '*' file.check_file_meta /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' base .. note:: Supported hash types include sha512, sha384, sha256, sha224, sha1, and md5. name Path to file destination sfn Template-processed source file contents source URL to file source source_sum File checksum information as a dictionary .. code-block:: yaml {hash_type: md5, hsum: <md5sum>} user Destination file user owner group Destination file group owner mode Destination file permissions mode attrs Destination file attributes .. versionadded:: 2018.3.0 saltenv Salt environment used to resolve source files contents File contents seuser selinux user attribute .. versionadded:: Neon serole selinux role attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon ''' changes = {} if not source_sum: source_sum = dict() try: lstats = stats(name, hash_type=source_sum.get('hash_type', None), follow_symlinks=False) except CommandExecutionError: lstats = {} if not lstats: changes['newfile'] = name return changes if 'hsum' in source_sum: if source_sum['hsum'] != lstats['sum']: if not sfn and source: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum['hsum']) if sfn: try: changes['diff'] = get_diff( name, sfn, template=True, show_filenames=False) except CommandExecutionError as exc: changes['diff'] = exc.strerror else: changes['sum'] = 'Checksum differs' if contents is not None: # Write a tempfile with the static contents tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'w') as tmp_: tmp_.write(salt.utils.stringutils.to_str(contents)) # Compare the static contents with the named file try: differences = get_diff(name, tmp, show_filenames=False) except CommandExecutionError as exc: log.error('Failed to diff files: %s', exc) differences = exc.strerror __clean_tmp(tmp) if differences: if __salt__['config.option']('obfuscate_templates'): changes['diff'] = '<Obfuscated Template>' else: changes['diff'] = differences if not salt.utils.platform.is_windows(): # Check owner if (user is not None and user != lstats['user'] and user != lstats['uid']): changes['user'] = user # Check group if (group is not None and group != lstats['group'] and group != lstats['gid']): changes['group'] = group # Normalize the file mode smode = salt.utils.files.normalize_mode(lstats['mode']) mode = salt.utils.files.normalize_mode(mode) if mode is not None and mode != smode: changes['mode'] = mode if attrs: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if attrs is not None \ and (diff_attrs[0] is not None or diff_attrs[1] is not None): changes['attrs'] = attrs # Check selinux if seuser or serole or setype or serange: try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError as exc: log.error('Unable to get current selinux attributes') changes['selinux'] = exc.strerror if seuser and seuser != current_seuser: changes['selinux'] = {"user": seuser} if serole and serole != current_serole: changes['selinux'] = {"role": serole} if setype and setype != current_setype: changes['selinux'] = {"type": setype} if serange and serange != current_serange: changes['selinux'] = {"range": serange} return changes def get_diff(file1, file2, saltenv='base', show_filenames=True, show_changes=True, template=False, source_hash_file1=None, source_hash_file2=None): ''' Return unified diff of two files file1 The first file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, thuis had to be a file local to the minion. file2 The second file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, this had to be a file on the salt fileserver (i.e. ``salt://somefile.txt``) show_filenames : True Set to ``False`` to hide the filenames in the top two lines of the diff. show_changes : True If set to ``False``, and there are differences, then instead of a diff a simple message stating that show_changes is set to ``False`` will be returned. template : False Set to ``True`` if two templates are being compared. This is not useful except for within states, with the ``obfuscate_templates`` option set to ``True``. .. versionadded:: 2018.3.0 source_hash_file1 If ``file1`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 source_hash_file2 If ``file2`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 CLI Examples: .. code-block:: bash salt '*' file.get_diff /home/fred/.vimrc salt://users/fred/.vimrc salt '*' file.get_diff /tmp/foo.txt /tmp/bar.txt ''' files = (file1, file2) source_hashes = (source_hash_file1, source_hash_file2) paths = [] errors = [] for filename, source_hash in zip(files, source_hashes): try: # Local file paths will just return the same path back when passed # to cp.cache_file. cached_path = __salt__['cp.cache_file'](filename, saltenv, source_hash=source_hash) if cached_path is False: errors.append( 'File {0} not found'.format( salt.utils.stringutils.to_unicode(filename) ) ) continue paths.append(cached_path) except MinionError as exc: errors.append(salt.utils.stringutils.to_unicode(exc.__str__())) continue if errors: raise CommandExecutionError( 'Failed to cache one or more files', info=errors ) args = [] for filename in paths: try: with salt.utils.files.fopen(filename, 'rb') as fp_: args.append(fp_.readlines()) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read {0}: {1}'.format( salt.utils.stringutils.to_unicode(filename), exc.strerror ) ) if args[0] != args[1]: if template and __salt__['config.option']('obfuscate_templates'): ret = '<Obfuscated Template>' elif not show_changes: ret = '<show_changes=False>' else: bdiff = _binary_replace(*paths) # pylint: disable=no-value-for-parameter if bdiff: ret = bdiff else: if show_filenames: args.extend(paths) ret = __utils__['stringutils.get_diff'](*args) return ret return '' def manage_file(name, sfn, ret, source, source_sum, user, group, mode, attrs, saltenv, backup, makedirs=False, template=None, # pylint: disable=W0613 show_changes=True, contents=None, dir_mode=None, follow_symlinks=True, skip_verify=False, keep_mode=False, encoding=None, encoding_errors='strict', seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Checks the destination against what was retrieved with get_managed and makes the appropriate modifications (if necessary). name location to place the file sfn location of cached file on the minion This is the path to the file stored on the minion. This file is placed on the minion using cp.cache_file. If the hash sum of that file matches the source_sum, we do not transfer the file to the minion again. This file is then grabbed and if it has template set, it renders the file to be placed into the correct place on the system using salt.files.utils.copyfile() ret The initial state return data structure. Pass in ``None`` to use the default structure. source file reference on the master source_sum sum hash for source user user owner group group owner backup backup_mode attrs attributes to be set on file: '' means remove all of them .. versionadded:: 2018.3.0 makedirs make directories if they do not exist template format of templating show_changes Include diff in state return contents: contents to be placed in the file dir_mode mode for directories created with makedirs skip_verify : False If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 keep_mode : False If ``True``, and the ``source`` is a file from the Salt fileserver (or a local file on the minion), the mode of the destination file will be set to the mode of the source file. .. note:: keep_mode does not work with salt-ssh. As a consequence of how the files are transferred to the minion, and the inability to connect back to the master with salt-ssh, salt is unable to stat the file as it exists on the fileserver and thus cannot mirror the mode on the salt-ssh minion encoding If specified, then the specified encoding will be used. Otherwise, the file will be encoded using the system locale (usually UTF-8). See https://docs.python.org/3/library/codecs.html#standard-encodings for the list of available encodings. .. versionadded:: 2017.7.0 encoding_errors : 'strict' Default is ```'strict'```. See https://docs.python.org/2/library/codecs.html#codec-base-classes for the error handling schemes. .. versionadded:: 2017.7.0 seuser selinux user attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon CLI Example: .. code-block:: bash salt '*' file.manage_file /etc/httpd/conf.d/httpd.conf '' '{}' salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' '' base '' .. versionchanged:: 2014.7.0 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if source: if not sfn: # File is not present, cache it sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) htype = source_sum.get('hash_type', __opts__['hash_type']) # Recalculate source sum now that file has been cached source_sum = { 'hash_type': htype, 'hsum': get_hash(sfn, form=htype) } if keep_mode: if _urlparse(source).scheme in ('salt', 'file', ''): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) # Check changes if the target file exists if os.path.isfile(name) or os.path.islink(name): if os.path.islink(name) and follow_symlinks: real_name = os.path.realpath(name) else: real_name = name # Only test the checksums on files with managed contents if source and not (not follow_symlinks and os.path.islink(real_name)): name_sum = get_hash(real_name, source_sum.get('hash_type', __opts__['hash_type'])) else: name_sum = None # Check if file needs to be replaced if source and (name_sum is None or source_sum.get('hsum', __opts__['hash_type']) != name_sum): if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server or local # source, and we are not skipping checksum verification, then # verify that it matches the specified checksum. if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3}). If the \'source_hash\' value ' 'refers to a remote file with multiple possible ' 'matches, then it may be necessary to set ' '\'source_hash_name\'.'.format( source_sum['hash_type'], source, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # Print a diff equivalent to diff -u old new if __salt__['config.option']('obfuscate_templates'): ret['changes']['diff'] = '<Obfuscated Template>' elif not show_changes: ret['changes']['diff'] = '<show_changes=False>' else: try: ret['changes']['diff'] = get_diff( real_name, sfn, show_filenames=False) except CommandExecutionError as exc: ret['changes']['diff'] = exc.strerror # Pre requisites are met, and the file needs to be replaced, do it try: salt.utils.files.copyfile(sfn, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) try: differences = get_diff( real_name, tmp, show_filenames=False, show_changes=show_changes, template=True) except CommandExecutionError as exc: ret.setdefault('warnings', []).append( 'Failed to detect changes to file: {0}'.format(exc.strerror) ) differences = '' if differences: ret['changes']['diff'] = differences # Pre requisites are met, the file needs to be replaced, do it try: salt.utils.files.copyfile(tmp, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(tmp) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) __clean_tmp(tmp) # Check for changing symlink to regular file here if os.path.islink(name) and not follow_symlinks: if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret try: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) ret['changes']['diff'] = \ 'Replace symbolic link with regular file' if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, follow_symlinks, seuser=seuser, serole=serole, setype=setype, serange=serange) if ret['changes']: ret['comment'] = 'File {0} updated'.format( salt.utils.data.decode(name) ) elif not ret['changes'] and ret['result']: ret['comment'] = 'File {0} is in the correct state'.format( salt.utils.data.decode(name) ) if sfn: __clean_tmp(sfn) return ret else: # target file does not exist contain_dir = os.path.dirname(name) def _set_mode_and_make_dirs(name, dir_mode, mode, user, group): # check for existence of windows drive letter if salt.utils.platform.is_windows(): drive, _ = os.path.splitdrive(name) if drive and not os.path.exists(drive): __clean_tmp(sfn) return _error(ret, '{0} drive not present'.format(drive)) if dir_mode is None and mode is not None: # Add execute bit to each nonzero digit in the mode, if # dir_mode was not specified. Otherwise, any # directories created with makedirs_() below can't be # listed via a shell. mode_list = [x for x in six.text_type(mode)][-3:] for idx in range(len(mode_list)): if mode_list[idx] != '0': mode_list[idx] = six.text_type(int(mode_list[idx]) | 1) dir_mode = ''.join(mode_list) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 makedirs_( path=name, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: makedirs_(name, user=user, group=group, mode=dir_mode) if source: # Apply the new file if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # It is a new file, set the diff accordingly ret['changes']['diff'] = 'New file' if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') else: # source != True if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') # Create the file, user rw-only if mode will be set to prevent # a small security race problem before the permissions are set with salt.utils.files.set_umask(0o077 if mode else None): # Create a new file when test is False and source is None if contents is None: if not __opts__['test']: if touch(name): ret['changes']['new'] = 'file {0} created'.format(name) ret['comment'] = 'Empty file' else: return _error( ret, 'Empty file {0} not created'.format(name) ) else: if not __opts__['test']: if touch(name): ret['changes']['diff'] = 'New file' else: return _error( ret, 'File {0} not created'.format(name) ) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) # Copy into place salt.utils.files.copyfile(tmp, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(tmp) # Now copy the file contents if there is a source file elif sfn: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(sfn) # This is a new file, if no mode specified, use the umask to figure # out what mode to use for the new file. if mode is None and not salt.utils.platform.is_windows(): # Get current umask mask = salt.utils.files.get_umask() # Calculate the mode value that results from the umask mode = oct((0o777 ^ mask) & 0o666) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, seuser=seuser, serole=serole, setype=setype, serange=serange) if not ret['comment']: ret['comment'] = 'File ' + name + ' updated' if __opts__['test']: ret['comment'] = 'File ' + name + ' not updated' elif not ret['changes'] and ret['result']: ret['comment'] = 'File ' + name + ' is in the correct state' if sfn: __clean_tmp(sfn) return ret def mkdir(dir_path, user=None, group=None, mode=None): ''' Ensure that a directory is available. CLI Example: .. code-block:: bash salt '*' file.mkdir /opt/jetty/context ''' dir_path = os.path.expanduser(dir_path) directory = os.path.normpath(dir_path) if not os.path.isdir(directory): # If a caller such as managed() is invoked with makedirs=True, make # sure that any created dirs are created with the same user and group # to follow the principal of least surprise method. makedirs_perms(directory, user, group, mode) return True def makedirs_(path, user=None, group=None, mode=None): ''' Ensure that the directory containing this path is available. .. note:: The path must end with a trailing slash otherwise the directory/directories will be created up to the parent directory. For example if path is ``/opt/code``, then it would be treated as ``/opt/`` but if the path ends with a trailing slash like ``/opt/code/``, then it would be treated as ``/opt/code/``. CLI Example: .. code-block:: bash salt '*' file.makedirs /opt/code/ ''' path = os.path.expanduser(path) if mode: mode = salt.utils.files.normalize_mode(mode) # walk up the directory structure until we find the first existing # directory dirname = os.path.normpath(os.path.dirname(path)) if os.path.isdir(dirname): # There's nothing for us to do msg = 'Directory \'{0}\' already exists'.format(dirname) log.debug(msg) return msg if os.path.exists(dirname): msg = 'The path \'{0}\' already exists and is not a directory'.format( dirname ) log.debug(msg) return msg directories_to_create = [] while True: if os.path.isdir(dirname): break directories_to_create.append(dirname) current_dirname = dirname dirname = os.path.dirname(dirname) if current_dirname == dirname: raise SaltInvocationError( 'Recursive creation for path \'{0}\' would result in an ' 'infinite loop. Please use an absolute path.'.format(dirname) ) # create parent directories from the topmost to the most deeply nested one directories_to_create.reverse() for directory_to_create in directories_to_create: # all directories have the user, group and mode set!! log.debug('Creating directory: %s', directory_to_create) mkdir(directory_to_create, user=user, group=group, mode=mode) def makedirs_perms(name, user=None, group=None, mode='0755'): ''' Taken and modified from os.makedirs to set user, group and mode for each directory created. CLI Example: .. code-block:: bash salt '*' file.makedirs_perms /opt/code ''' name = os.path.expanduser(name) path = os.path head, tail = path.split(name) if not tail: head, tail = path.split(head) if head and tail and not path.exists(head): try: makedirs_perms(head, user, group, mode) except OSError as exc: # be happy if someone already created the path if exc.errno != errno.EEXIST: raise if tail == os.curdir: # xxx/newdir/. exists if xxx/newdir exists return os.mkdir(name) check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) def get_devmm(name): ''' Get major/minor info from a device CLI Example: .. code-block:: bash salt '*' file.get_devmm /dev/chr ''' name = os.path.expanduser(name) if is_chrdev(name) or is_blkdev(name): stat_structure = os.stat(name) return ( os.major(stat_structure.st_rdev), os.minor(stat_structure.st_rdev)) else: return (0, 0) def is_chrdev(name): ''' Check if a file exists and is a character device. CLI Example: .. code-block:: bash salt '*' file.is_chrdev /dev/chr ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the character device does not exist in the first place return False else: raise return stat.S_ISCHR(stat_structure.st_mode) def mknod_chrdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a character device. CLI Example: .. code-block:: bash salt '*' file.mknod_chrdev /dev/chr 180 31 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating character device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFCHR, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created character device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_blkdev(name): ''' Check if a file exists and is a block device. CLI Example: .. code-block:: bash salt '*' file.is_blkdev /dev/blk ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the block device does not exist in the first place return False else: raise return stat.S_ISBLK(stat_structure.st_mode) def mknod_blkdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a block device. CLI Example: .. code-block:: bash salt '*' file.mknod_blkdev /dev/blk 8 999 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating block device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFBLK, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created block device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_fifo(name): ''' Check if a file exists and is a FIFO. CLI Example: .. code-block:: bash salt '*' file.is_fifo /dev/fifo ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the fifo does not exist in the first place return False else: raise return stat.S_ISFIFO(stat_structure.st_mode) def mknod_fifo(name, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a FIFO pipe. CLI Example: .. code-block:: bash salt '*' file.mknod_fifo /dev/fifo ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating FIFO name: %s', name) try: if __opts__['test']: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = None else: if os.mkfifo(name, int(six.text_type(mode).lstrip('0Oo'), 8)) is None: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created fifo check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def mknod(name, ntype, major=0, minor=0, user=None, group=None, mode='0600'): ''' .. versionadded:: 0.17.0 Create a block device, character device, or fifo pipe. Identical to the gnu mknod. CLI Examples: .. code-block:: bash salt '*' file.mknod /dev/chr c 180 31 salt '*' file.mknod /dev/blk b 8 999 salt '*' file.nknod /dev/fifo p ''' ret = False makedirs_(name, user, group) if ntype == 'c': ret = mknod_chrdev(name, major, minor, user, group, mode) elif ntype == 'b': ret = mknod_blkdev(name, major, minor, user, group, mode) elif ntype == 'p': ret = mknod_fifo(name, user, group, mode) else: raise SaltInvocationError( 'Node type unavailable: \'{0}\'. Available node types are ' 'character (\'c\'), block (\'b\'), and pipe (\'p\').'.format(ntype) ) return ret def list_backups(path, limit=None): ''' .. versionadded:: 0.17.0 Lists the previous versions of a file backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups /foo/bar/baz.txt ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows src_dir = parent_dir.replace(':', '_') else: src_dir = parent_dir[1:] # Figure out full path of location of backup file in minion cache bkdir = os.path.join(bkroot, src_dir) if not os.path.isdir(bkdir): return {} files = {} for fname in [x for x in os.listdir(bkdir) if os.path.isfile(os.path.join(bkdir, x))]: if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows strpfmt = '{0}_%a_%b_%d_%H-%M-%S_%f_%Y'.format(basename) else: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(fname, strpfmt) except ValueError: # File didn't match the strp format string, so it's not a backup # for this file. Move on to the next one. continue if salt.utils.platform.is_windows(): str_format = '%a %b %d %Y %H-%M-%S.%f' else: str_format = '%a %b %d %Y %H:%M:%S.%f' files.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime(str_format) location = os.path.join(bkdir, fname) files[timestamp]['Size'] = os.stat(location).st_size files[timestamp]['Location'] = location return dict(list(zip( list(range(len(files))), [files[x] for x in sorted(files, reverse=True)[:limit]] ))) list_backup = salt.utils.functools.alias_function(list_backups, 'list_backup') def list_backups_dir(path, limit=None): ''' Lists the previous versions of a directory backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The directory on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups_dir /foo/bar/baz/ ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups_dir: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) # Figure out full path of location of backup folder in minion cache bkdir = os.path.join(bkroot, parent_dir[1:]) if not os.path.isdir(bkdir): return {} files = {} f = dict([(i, len(list(n))) for i, n in itertools.groupby([x.split("_")[0] for x in sorted(os.listdir(bkdir))])]) ff = os.listdir(bkdir) for i, n in six.iteritems(f): ssfile = {} for x in sorted(ff): basename = x.split('_')[0] if i == basename: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(x, strpfmt) except ValueError: # Folder didn't match the strp format string, so it's not a backup # for this folder. Move on to the next one. continue ssfile.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime('%a %b %d %Y %H:%M:%S.%f') location = os.path.join(bkdir, x) ssfile[timestamp]['Size'] = os.stat(location).st_size ssfile[timestamp]['Location'] = location sfiles = dict(list(zip(list(range(n)), [ssfile[x] for x in sorted(ssfile, reverse=True)[:limit]]))) sefiles = {i: sfiles} files.update(sefiles) return files def restore_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Restore a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to restore, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.restore_backup /foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) # Note: This only supports minion backups, so this function will need to be # modified if/when master backups are implemented. ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret salt.utils.files.backup_minion(path, _get_bkroot()) try: shutil.copyfile(backup['Location'], path) except IOError as exc: ret['comment'] = \ 'Unable to restore {0} to {1}: ' \ '{2}'.format(backup['Location'], path, exc) return ret else: ret['result'] = True ret['comment'] = 'Successfully restored {0} to ' \ '{1}'.format(backup['Location'], path) # Try to set proper ownership if not salt.utils.platform.is_windows(): try: fstat = os.stat(path) except (OSError, IOError): ret['comment'] += ', but was unable to set ownership' else: os.chown(path, fstat.st_uid, fstat.st_gid) return ret def delete_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Delete a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to delete, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.delete_backup /var/cache/salt/minion/file_backup/home/foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret try: os.remove(backup['Location']) except IOError as exc: ret['comment'] = 'Unable to remove {0}: {1}'.format(backup['Location'], exc) else: ret['result'] = True ret['comment'] = 'Successfully removed {0}'.format(backup['Location']) return ret remove_backup = salt.utils.functools.alias_function(delete_backup, 'remove_backup') def grep(path, pattern, *opts): ''' Grep for a string in the specified file .. note:: This function's return value is slated for refinement in future versions of Salt path Path to the file to be searched .. note:: Globbing is supported (i.e. ``/var/log/foo/*.log``, but if globbing is being used then the path should be quoted to keep the shell from attempting to expand the glob expression. pattern Pattern to match. For example: ``test``, or ``a[0-5]`` opts Additional command-line flags to pass to the grep command. For example: ``-v``, or ``-i -B2`` .. note:: The options should come after a double-dash (as shown in the examples below) to keep Salt's own argument parser from interpreting them. CLI Example: .. code-block:: bash salt '*' file.grep /etc/passwd nobody salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i -B2 salt '*' file.grep "/etc/sysconfig/network-scripts/*" ipaddr -- -i -l ''' path = os.path.expanduser(path) # Backup the path in case the glob returns nothing _path = path path = glob.glob(path) # If the list is empty no files exist # so we revert back to the original path # so the result is an error. if not path: path = _path split_opts = [] for opt in opts: try: split = salt.utils.args.shlex_split(opt) except AttributeError: split = salt.utils.args.shlex_split(six.text_type(opt)) if len(split) > 1: raise SaltInvocationError( 'Passing multiple command line arguments in a single string ' 'is not supported, please pass the following arguments ' 'separately: {0}'.format(opt) ) split_opts.extend(split) if isinstance(path, list): cmd = ['grep'] + split_opts + [pattern] + path else: cmd = ['grep'] + split_opts + [pattern, path] try: ret = __salt__['cmd.run_all'](cmd, python_shell=False) except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return ret def open_files(by_pid=False): ''' Return a list of all physical open files on the system. CLI Examples: .. code-block:: bash salt '*' file.open_files salt '*' file.open_files by_pid=True ''' # First we collect valid PIDs pids = {} procfs = os.listdir('/proc/') for pfile in procfs: try: pids[int(pfile)] = [] except ValueError: # Not a valid PID, move on pass # Then we look at the open files for each PID files = {} for pid in pids: ppath = '/proc/{0}'.format(pid) try: tids = os.listdir('{0}/task'.format(ppath)) except OSError: continue # Collect the names of all of the file descriptors fd_ = [] #try: # fd_.append(os.path.realpath('{0}/task/{1}exe'.format(ppath, tid))) #except Exception: # pass for fpath in os.listdir('{0}/fd'.format(ppath)): fd_.append('{0}/fd/{1}'.format(ppath, fpath)) for tid in tids: try: fd_.append( os.path.realpath('{0}/task/{1}/exe'.format(ppath, tid)) ) except OSError: continue for tpath in os.listdir('{0}/task/{1}/fd'.format(ppath, tid)): fd_.append('{0}/task/{1}/fd/{2}'.format(ppath, tid, tpath)) fd_ = sorted(set(fd_)) # Loop through file descriptors and return useful data for each file for fdpath in fd_: # Sometimes PIDs and TIDs disappear before we can query them try: name = os.path.realpath(fdpath) # Running stat on the file cuts out all of the sockets and # deleted files from the list os.stat(name) except OSError: continue if name not in files: files[name] = [pid] else: # We still want to know which PIDs are using each file files[name].append(pid) files[name] = sorted(set(files[name])) pids[pid].append(name) pids[pid] = sorted(set(pids[pid])) if by_pid: return pids return files def pardir(): ''' Return the relative parent directory path symbol for underlying OS .. versionadded:: 2014.7.0 This can be useful when constructing Salt Formulas. .. code-block:: jinja {% set pardir = salt['file.pardir']() %} {% set final_path = salt['file.join']('subdir', pardir, 'confdir') %} CLI Example: .. code-block:: bash salt '*' file.pardir ''' return os.path.pardir def normpath(path): ''' Returns Normalize path, eliminating double slashes, etc. .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.normpath'](tpldir + '/../vars.jinja') import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.normpath 'a/b/c/..' ''' return os.path.normpath(path) def basename(path): ''' Returns the final component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- set filename = salt['file.basename'](source_file) %} CLI Example: .. code-block:: bash salt '*' file.basename 'test/test.config' ''' return os.path.basename(path) def dirname(path): ''' Returns the directory component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.dirname'](tpldir) + '/vars.jinja' import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.dirname 'test/path/filename.config' ''' return os.path.dirname(path) def join(*args): ''' Return a normalized file system path for the underlying OS .. versionadded:: 2014.7.0 This can be useful at the CLI but is frequently useful when scripting combining path variables: .. code-block:: jinja {% set www_root = '/var' %} {% set app_dir = 'myapp' %} myapp_config: file: - managed - name: {{ salt['file.join'](www_root, app_dir, 'config.yaml') }} CLI Example: .. code-block:: bash salt '*' file.join '/' 'usr' 'local' 'bin' ''' return os.path.join(*args) def move(src, dst): ''' Move a file or directory CLI Example: .. code-block:: bash salt '*' file.move /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('Source path must be absolute.') if not os.path.isabs(dst): raise SaltInvocationError('Destination path must be absolute.') ret = { 'result': True, 'comment': "'{0}' moved to '{1}'".format(src, dst), } try: shutil.move(src, dst) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move '{0}' to '{1}': {2}".format(src, dst, exc) ) return ret def diskusage(path): ''' Recursively calculate disk usage of path and return it in bytes CLI Example: .. code-block:: bash salt '*' file.diskusage /path/to/check ''' total_size = 0 seen = set() if os.path.isfile(path): stat_structure = os.stat(path) ret = stat_structure.st_size return ret for dirpath, dirnames, filenames in salt.utils.path.os_walk(path): for f in filenames: fp = os.path.join(dirpath, f) try: stat_structure = os.stat(fp) except OSError: continue if stat_structure.st_ino in seen: continue seen.add(stat_structure.st_ino) total_size += stat_structure.st_size ret = total_size return ret
saltstack/salt
salt/modules/file.py
group_to_gid
python
def group_to_gid(group): ''' Convert the group to the gid on this system group group to convert to its gid CLI Example: .. code-block:: bash salt '*' file.group_to_gid root ''' if group is None: return '' try: if isinstance(group, int): return group return grp.getgrnam(group).gr_gid except KeyError: return ''
Convert the group to the gid on this system group group to convert to its gid CLI Example: .. code-block:: bash salt '*' file.group_to_gid root
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L192-L212
null
# -*- coding: utf-8 -*- ''' Manage information about regular files, directories, and special files on the minion, set/read user, group, mode, and data ''' # TODO: We should add the capability to do u+r type operations here # some time in the future from __future__ import absolute_import, print_function, unicode_literals # Import python libs import datetime import errno import fnmatch import io import itertools import logging import operator import os import re import shutil import stat import string import sys import tempfile import time import glob import hashlib import mmap from collections import Iterable, Mapping from functools import reduce # pylint: disable=redefined-builtin # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range, zip from salt.ext.six.moves.urllib.parse import urlparse as _urlparse # pylint: enable=import-error,no-name-in-module,redefined-builtin try: import grp import pwd except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.atomicfile import salt.utils.data import salt.utils.dictupdate import salt.utils.filebuffer import salt.utils.files import salt.utils.find import salt.utils.functools import salt.utils.hashutils import salt.utils.itertools import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.templates import salt.utils.url import salt.utils.user from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError, get_error_message as _get_error_message from salt.utils.files import HASHES, HASHES_REVMAP log = logging.getLogger(__name__) __func_alias__ = { 'makedirs_': 'makedirs' } def __virtual__(): ''' Only work on POSIX-like systems ''' # win_file takes care of windows if salt.utils.platform.is_windows(): return ( False, 'The file execution module cannot be loaded: only available on ' 'non-Windows systems - use win_file instead.' ) return True def __clean_tmp(sfn): ''' Clean out a template temp file ''' if sfn.startswith(os.path.join(tempfile.gettempdir(), salt.utils.files.TEMPFILE_PREFIX)): # Don't remove if it exists in file_roots (any saltenv) all_roots = itertools.chain.from_iterable( six.itervalues(__opts__['file_roots'])) in_roots = any(sfn.startswith(root) for root in all_roots) # Only clean up files that exist if os.path.exists(sfn) and not in_roots: os.remove(sfn) def _error(ret, err_msg): ''' Common function for setting error information for return dicts ''' ret['result'] = False ret['comment'] = err_msg return ret def _binary_replace(old, new): ''' This function does NOT do any diffing, it just checks the old and new files to see if either is binary, and provides an appropriate string noting the difference between the two files. If neither file is binary, an empty string is returned. This function should only be run AFTER it has been determined that the files differ. ''' old_isbin = not __utils__['files.is_text'](old) new_isbin = not __utils__['files.is_text'](new) if any((old_isbin, new_isbin)): if all((old_isbin, new_isbin)): return 'Replace binary file' elif old_isbin: return 'Replace binary file with text file' elif new_isbin: return 'Replace text file with binary file' return '' def _get_bkroot(): ''' Get the location of the backup dir in the minion cache ''' # Get the cachedir from the minion config return os.path.join(__salt__['config.get']('cachedir'), 'file_backup') def _splitlines_preserving_trailing_newline(str): ''' Returns a list of the lines in the string, breaking at line boundaries and preserving a trailing newline (if present). Essentially, this works like ``str.striplines(False)`` but preserves an empty line at the end. This is equivalent to the following code: .. code-block:: python lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') ''' lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') return lines def gid_to_group(gid): ''' Convert the group id to the group name on this system gid gid to convert to a group name CLI Example: .. code-block:: bash salt '*' file.gid_to_group 0 ''' try: gid = int(gid) except ValueError: # This is not an integer, maybe it's already the group name? gid = group_to_gid(gid) if gid == '': # Don't even bother to feed it to grp return '' try: return grp.getgrgid(gid).gr_name except (KeyError, NameError): # If group is not present, fall back to the gid. return gid def get_gid(path, follow_symlinks=True): ''' Return the id of the group that owns a given file path file or directory of which to get the gid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_gid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('gid', -1) def get_group(path, follow_symlinks=True): ''' Return the group that owns a given file path file or directory of which to get the group follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_group /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('group', False) def uid_to_user(uid): ''' Convert a uid to a user name uid uid to convert to a username CLI Example: .. code-block:: bash salt '*' file.uid_to_user 0 ''' try: return pwd.getpwuid(uid).pw_name except (KeyError, NameError): # If user is not present, fall back to the uid. return uid def user_to_uid(user): ''' Convert user name to a uid user user name to convert to its uid CLI Example: .. code-block:: bash salt '*' file.user_to_uid root ''' if user is None: user = salt.utils.user.get_user() try: if isinstance(user, int): return user return pwd.getpwnam(user).pw_uid except KeyError: return '' def get_uid(path, follow_symlinks=True): ''' Return the id of the user that owns a given file path file or directory of which to get the uid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_uid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('uid', -1) def get_user(path, follow_symlinks=True): ''' Return the user that owns a given file path file or directory of which to get the user follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_user /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('user', False) def get_mode(path, follow_symlinks=True): ''' Return the mode of a file path file or directory of which to get the mode follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_mode /etc/passwd .. versionchanged:: 2014.1.0 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('mode', '') def set_mode(path, mode): ''' Set the mode of a file path file or directory of which to set the mode mode mode to set the path to CLI Example: .. code-block:: bash salt '*' file.set_mode /etc/passwd 0644 ''' path = os.path.expanduser(path) mode = six.text_type(mode).lstrip('0Oo') if not mode: mode = '0' if not os.path.exists(path): raise CommandExecutionError('{0}: File not found'.format(path)) try: os.chmod(path, int(mode, 8)) except Exception: return 'Invalid Mode ' + mode return get_mode(path) def lchown(path, user, group): ''' Chown a file, pass the file the desired user and group without following symlinks. path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 return os.lchown(path, uid, gid) def chown(path, user, group): ''' Chown a file, pass the file the desired user and group path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 if not os.path.exists(path): try: # Broken symlinks will return false, but still need to be chowned return os.lchown(path, uid, gid) except OSError: pass err += 'File not found' if err: return err return os.chown(path, uid, gid) def chgrp(path, group): ''' Change the group of a file path path to the file or directory group group owner CLI Example: .. code-block:: bash salt '*' file.chgrp /etc/passwd root ''' path = os.path.expanduser(path) user = get_user(path) return chown(path, user, group) def _cmp_attrs(path, attrs): ''' .. versionadded:: 2018.3.0 Compare attributes of a given file to given attributes. Returns a pair (list) where first item are attributes to add and second item are to be removed. Please take into account when using this function that some minions will not have lsattr installed. path path to file to compare attributes with. attrs string of attributes to compare against a given file ''' diff = [None, None] # lsattr for AIX is not the same thing as lsattr for linux. if salt.utils.platform.is_aix(): return None try: lattrs = lsattr(path).get(path, '') except AttributeError: # lsattr not installed return None old = [chr for chr in lattrs if chr not in attrs] if old: diff[1] = ''.join(old) new = [chr for chr in attrs if chr not in lattrs] if new: diff[0] = ''.join(new) return diff def lsattr(path): ''' .. versionadded:: 2018.3.0 .. versionchanged:: 2018.3.1 If ``lsattr`` is not installed on the system, ``None`` is returned. .. versionchanged:: 2018.3.4 If on ``AIX``, ``None`` is returned even if in filesystem as lsattr on ``AIX`` is not the same thing as the linux version. Obtain the modifiable attributes of the given file. If path is to a directory, an empty list is returned. path path to file to obtain attributes of. File/directory must exist. CLI Example: .. code-block:: bash salt '*' file.lsattr foo1.txt ''' if not salt.utils.path.which('lsattr') or salt.utils.platform.is_aix(): return None if not os.path.exists(path): raise SaltInvocationError("File or directory does not exist: " + path) cmd = ['lsattr', path] result = __salt__['cmd.run'](cmd, ignore_retcode=True, python_shell=False) results = {} for line in result.splitlines(): if not line.startswith('lsattr: '): vals = line.split(None, 1) results[vals[1]] = re.findall(r"[aAcCdDeijPsStTu]", vals[0]) return results def chattr(*files, **kwargs): ''' .. versionadded:: 2018.3.0 Change the attributes of files. This function accepts one or more files and the following options: operator Can be wither ``add`` or ``remove``. Determines whether attributes should be added or removed from files attributes One or more of the following characters: ``aAcCdDeijPsStTu``, representing attributes to add to/remove from files version a version number to assign to the file(s) flags One or more of the following characters: ``RVf``, representing flags to assign to chattr (recurse, verbose, suppress most errors) CLI Example: .. code-block:: bash salt '*' file.chattr foo1.txt foo2.txt operator=add attributes=ai salt '*' file.chattr foo3.txt operator=remove attributes=i version=2 ''' operator = kwargs.pop('operator', None) attributes = kwargs.pop('attributes', None) flags = kwargs.pop('flags', None) version = kwargs.pop('version', None) if (operator is None) or (operator not in ('add', 'remove')): raise SaltInvocationError( "Need an operator: 'add' or 'remove' to modify attributes.") if attributes is None: raise SaltInvocationError("Need attributes: [aAcCdDeijPsStTu]") cmd = ['chattr'] if operator == "add": attrs = '+{0}'.format(attributes) elif operator == "remove": attrs = '-{0}'.format(attributes) cmd.append(attrs) if flags is not None: cmd.append('-{0}'.format(flags)) if version is not None: cmd.extend(['-v', version]) cmd.extend(files) result = __salt__['cmd.run'](cmd, python_shell=False) if bool(result): raise CommandExecutionError( "chattr failed to run, possibly due to bad parameters.") return True def get_sum(path, form='sha256'): ''' Return the checksum for the given file. The following checksum algorithms are supported: * md5 * sha1 * sha224 * sha256 **(default)** * sha384 * sha512 path path to the file or directory form desired sum format CLI Example: .. code-block:: bash salt '*' file.get_sum /etc/passwd sha512 ''' path = os.path.expanduser(path) if not os.path.isfile(path): return 'File not found' return salt.utils.hashutils.get_hash(path, form, 4096) def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` path path to the file or directory form desired sum format chunk_size amount to sum at once CLI Example: .. code-block:: bash salt '*' file.get_hash /etc/shadow ''' return salt.utils.hashutils.get_hash(os.path.expanduser(path), form, chunk_size) def get_source_sum(file_name='', source='', source_hash=None, source_hash_name=None, saltenv='base'): ''' .. versionadded:: 2016.11.0 Used by :py:func:`file.get_managed <salt.modules.file.get_managed>` to obtain the hash and hash type from the parameters specified below. file_name Optional file name being managed, for matching with :py:func:`file.extract_hash <salt.modules.file.extract_hash>`. source Source file, as used in :py:mod:`file <salt.states.file>` and other states. If ``source_hash`` refers to a file containing hashes, then this filename will be used to match a filename in that file. If the ``source_hash`` is a hash expression, then this argument will be ignored. source_hash Hash file/expression, as used in :py:mod:`file <salt.states.file>` and other states. If this value refers to a remote URL or absolute path to a local file, it will be cached and :py:func:`file.extract_hash <salt.modules.file.extract_hash>` will be used to obtain a hash from it. source_hash_name Specific file name to look for when ``source_hash`` refers to a remote file, used to disambiguate ambiguous matches. saltenv : base Salt fileserver environment from which to retrieve the source_hash. This value will only be used when ``source_hash`` refers to a file on the Salt fileserver (i.e. one beginning with ``salt://``). CLI Example: .. code-block:: bash salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=499ae16dcae71eeb7c3a30c75ea7a1a6 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 source_hash_name=./dir2/foo.tar.gz ''' def _invalid_source_hash_format(): ''' DRY helper for reporting invalid source_hash input ''' raise CommandExecutionError( 'Source hash {0} format is invalid. The supported formats are: ' '1) a hash, 2) an expression in the format <hash_type>=<hash>, or ' '3) either a path to a local file containing hashes, or a URI of ' 'a remote hash file. Supported protocols for remote hash files ' 'are: {1}. The hash may also not be of a valid length, the ' 'following are supported hash types and lengths: {2}.'.format( source_hash, ', '.join(salt.utils.files.VALID_PROTOS), ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) hash_fn = None if os.path.isabs(source_hash): hash_fn = source_hash else: try: proto = _urlparse(source_hash).scheme if proto in salt.utils.files.VALID_PROTOS: hash_fn = __salt__['cp.cache_file'](source_hash, saltenv) if not hash_fn: raise CommandExecutionError( 'Source hash file {0} not found'.format(source_hash) ) else: if proto != '': # Some unsupported protocol (e.g. foo://) is being used. # We'll get into this else block if a hash expression # (like md5=<md5 checksum here>), but in those cases, the # protocol will be an empty string, in which case we avoid # this error condition. _invalid_source_hash_format() except (AttributeError, TypeError): _invalid_source_hash_format() if hash_fn is not None: ret = extract_hash(hash_fn, '', file_name, source, source_hash_name) if ret is None: _invalid_source_hash_format() ret['hsum'] = ret['hsum'].lower() return ret else: # The source_hash is a hash expression ret = {} try: ret['hash_type'], ret['hsum'] = \ [x.strip() for x in source_hash.split('=', 1)] except AttributeError: _invalid_source_hash_format() except ValueError: # No hash type, try to figure out by hash length if not re.match('^[{0}]+$'.format(string.hexdigits), source_hash): _invalid_source_hash_format() ret['hsum'] = source_hash source_hash_len = len(source_hash) if source_hash_len in HASHES_REVMAP: ret['hash_type'] = HASHES_REVMAP[source_hash_len] else: _invalid_source_hash_format() if ret['hash_type'] not in HASHES: raise CommandExecutionError( 'Invalid hash type \'{0}\'. Supported hash types are: {1}. ' 'Either remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to a supported type.' .format(ret['hash_type'], ', '.join(HASHES), ret['hsum']) ) else: hsum_len = len(ret['hsum']) if hsum_len not in HASHES_REVMAP: _invalid_source_hash_format() elif hsum_len != HASHES[ret['hash_type']]: raise CommandExecutionError( 'Invalid length ({0}) for hash type \'{1}\'. Either ' 'remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to \'{3}\''.format( hsum_len, ret['hash_type'], ret['hsum'], HASHES_REVMAP[hsum_len], ) ) ret['hsum'] = ret['hsum'].lower() return ret def check_hash(path, file_hash): ''' Check if a file matches the given hash string Returns ``True`` if the hash matches, otherwise ``False``. path Path to a file local to the minion. hash The hash to check against the file specified in the ``path`` argument. .. versionchanged:: 2016.11.4 For this and newer versions the hash can be specified without an accompanying hash type (e.g. ``e138491e9d5b97023cea823fe17bac22``), but for earlier releases it is necessary to also specify the hash type in the format ``<hash_type>=<hash_value>`` (e.g. ``md5=e138491e9d5b97023cea823fe17bac22``). CLI Example: .. code-block:: bash salt '*' file.check_hash /etc/fstab e138491e9d5b97023cea823fe17bac22 salt '*' file.check_hash /etc/fstab md5=e138491e9d5b97023cea823fe17bac22 ''' path = os.path.expanduser(path) if not isinstance(file_hash, six.string_types): raise SaltInvocationError('hash must be a string') for sep in (':', '='): if sep in file_hash: hash_type, hash_value = file_hash.split(sep, 1) break else: hash_value = file_hash hash_len = len(file_hash) hash_type = HASHES_REVMAP.get(hash_len) if hash_type is None: raise SaltInvocationError( 'Hash {0} (length: {1}) could not be matched to a supported ' 'hash type. The supported hash types and lengths are: ' '{2}'.format( file_hash, hash_len, ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) return get_hash(path, hash_type) == hash_value def find(path, *args, **kwargs): ''' Approximate the Unix ``find(1)`` command and return a list of paths that meet the specified criteria. The options include match criteria: .. code-block:: text name = path-glob # case sensitive iname = path-glob # case insensitive regex = path-regex # case sensitive iregex = path-regex # case insensitive type = file-types # match any listed type user = users # match any listed user group = groups # match any listed group size = [+-]number[size-unit] # default unit = byte mtime = interval # modified since date grep = regex # search file contents and/or actions: .. code-block:: text delete [= file-types] # default type = 'f' exec = command [arg ...] # where {} is replaced by pathname print [= print-opts] and/or depth criteria: .. code-block:: text maxdepth = maximum depth to transverse in path mindepth = minimum depth to transverse before checking files or directories The default action is ``print=path`` ``path-glob``: .. code-block:: text * = match zero or more chars ? = match any char [abc] = match a, b, or c [!abc] or [^abc] = match anything except a, b, and c [x-y] = match chars x through y [!x-y] or [^x-y] = match anything except chars x through y {a,b,c} = match a or b or c ``path-regex``: a Python Regex (regular expression) pattern to match pathnames ``file-types``: a string of one or more of the following: .. code-block:: text a: all file types b: block device c: character device d: directory p: FIFO (named pipe) f: plain file l: symlink s: socket ``users``: a space and/or comma separated list of user names and/or uids ``groups``: a space and/or comma separated list of group names and/or gids ``size-unit``: .. code-block:: text b: bytes k: kilobytes m: megabytes g: gigabytes t: terabytes interval: .. code-block:: text [<num>w] [<num>d] [<num>h] [<num>m] [<num>s] where: w: week d: day h: hour m: minute s: second print-opts: a comma and/or space separated list of one or more of the following: .. code-block:: text group: group name md5: MD5 digest of file contents mode: file permissions (as integer) mtime: last modification time (as time_t) name: file basename path: file absolute path size: file size in bytes type: file type user: user name CLI Examples: .. code-block:: bash salt '*' file.find / type=f name=\\*.bak size=+10m salt '*' file.find /var mtime=+30d size=+10m print=path,size,mtime salt '*' file.find /var/log name=\\*.[0-9] mtime=+30d size=+10m delete ''' if 'delete' in args: kwargs['delete'] = 'f' elif 'print' in args: kwargs['print'] = 'path' try: finder = salt.utils.find.Finder(kwargs) except ValueError as ex: return 'error: {0}'.format(ex) ret = [item for i in [finder.find(p) for p in glob.glob(os.path.expanduser(path))] for item in i] ret.sort() return ret def _sed_esc(string, escape_all=False): ''' Escape single quotes and forward slashes ''' special_chars = "^.[$()|*+?{" string = string.replace("'", "'\"'\"'").replace("/", "\\/") if escape_all is True: for char in special_chars: string = string.replace(char, "\\" + char) return string def sed(path, before, after, limit='', backup='.bak', options='-r -e', flags='g', escape_all=False, negate_match=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup options : ``-r -e`` Options to pass to sed flags : ``g`` Flags to modify the sed search; e.g., ``i`` for case-insensitive pattern matching negate_match : False Negate the search command (``!``) .. versionadded:: 0.17.0 Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # path = os.path.expanduser(path) if not os.path.exists(path): return False # Mandate that before and after are strings before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.append('-i{0}'.format(backup) if backup else '-i') cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}{negate_match}s/{before}/{after}/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', negate_match='!' if negate_match else '', before=before, after=after, flags=flags ) ) cmd.append(path) return __salt__['cmd.run_all'](cmd, python_shell=False) def sed_contains(path, text, limit='', flags='g'): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the file at ``path`` contains ``text``. Utilizes sed to perform the search (line-wise search). Note: the ``p`` flag will be added to any flags you pass in. CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' # Largely inspired by Fabric's contrib.files.contains() path = os.path.expanduser(path) if not os.path.exists(path): return False before = _sed_esc(six.text_type(text), False) limit = _sed_esc(six.text_type(limit), False) options = '-n -r -e' if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}s/{before}/$/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', before=before, flags='p{0}'.format(flags) ) ) cmd.append(path) result = __salt__['cmd.run'](cmd, python_shell=False) return bool(result) def psed(path, before, after, limit='', backup='.bak', flags='gMS', escape_all=False, multi=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file (pure Python version) Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup flags : ``gMS`` Flags to modify the search. Valid values are: - ``g``: Replace all occurrences of the pattern, not just the first. - ``I``: Ignore case. - ``L``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\s`` and ``\\S`` dependent on the locale. - ``M``: Treat multiple lines as a single line. - ``S``: Make `.` match all characters, including newlines. - ``U``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\d``, ``\\D``, ``\\s`` and ``\\S`` dependent on Unicode. - ``X``: Verbose (whitespace is ignored). multi: ``False`` If True, treat the entire file as a single line Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # # Mandate that before and after are strings path = os.path.expanduser(path) multi = bool(multi) before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) # The pattern to replace with does not need to be escaped!!! # after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) shutil.copy2(path, '{0}{1}'.format(path, backup)) with salt.utils.files.fopen(path, 'w') as ofile: with salt.utils.files.fopen('{0}{1}'.format(path, backup), 'r') as ifile: if multi is True: for line in ifile.readline(): ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(line), before, after, limit, flags ) ) ) else: ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(ifile.read()), before, after, limit, flags ) ) ) RE_FLAG_TABLE = {'I': re.I, 'L': re.L, 'M': re.M, 'S': re.S, 'U': re.U, 'X': re.X} def _psed(text, before, after, limit, flags): ''' Does the actual work for file.psed, so that single lines can be passed in ''' atext = text if limit: limit = re.compile(limit) comps = text.split(limit) atext = ''.join(comps[1:]) count = 1 if 'g' in flags: count = 0 flags = flags.replace('g', '') aflags = 0 for flag in flags: aflags |= RE_FLAG_TABLE[flag] before = re.compile(before, flags=aflags) text = re.sub(before, after, atext, count=count) return text def uncomment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Uncomment specified commented lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be uncommented. This regex should not include the comment character. A leading ``^`` character will be stripped for convenience (for easily switching between comment() and uncomment()). char : ``#`` The character to remove in order to uncomment a line backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup CLI Example: .. code-block:: bash salt '*' file.uncomment /etc/hosts.deny 'ALL: PARANOID' ''' return comment_line(path=path, regex=regex, char=char, cmnt=False, backup=backup) def comment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Comment out specified lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be commented; this pattern will be wrapped in parenthesis and will move any preceding/trailing ``^`` or ``$`` characters outside the parenthesis (e.g., the pattern ``^foo$`` will be rewritten as ``^(foo)$``) char : ``#`` The character to be inserted at the beginning of a line in order to comment it out backup : ``.bak`` The file will be backed up before edit with this file extension .. warning:: This backup will be overwritten each time ``sed`` / ``comment`` / ``uncomment`` is called. Meaning the backup will only be useful after the first invocation. CLI Example: .. code-block:: bash salt '*' file.comment /etc/modules pcspkr ''' return comment_line(path=path, regex=regex, char=char, cmnt=True, backup=backup) def comment_line(path, regex, char='#', cmnt=True, backup='.bak'): r''' Comment or Uncomment a line in a text file. :param path: string The full path to the text file. :param regex: string A regex expression that begins with ``^`` that will find the line you wish to comment. Can be as simple as ``^color =`` :param char: string The character used to comment a line in the type of file you're referencing. Default is ``#`` :param cmnt: boolean True to comment the line. False to uncomment the line. Default is True. :param backup: string The file extension to give the backup file. Default is ``.bak`` Set to False/None to not keep a backup. :return: boolean Returns True if successful, False if not CLI Example: The following example will comment out the ``pcspkr`` line in the ``/etc/modules`` file using the default ``#`` character and create a backup file named ``modules.bak`` .. code-block:: bash salt '*' file.comment_line '/etc/modules' '^pcspkr' CLI Example: The following example will uncomment the ``log_level`` setting in ``minion`` config file if it is set to either ``warning``, ``info``, or ``debug`` using the ``#`` character and create a backup file named ``minion.bk`` .. code-block:: bash salt '*' file.comment_line 'C:\salt\conf\minion' '^log_level: (warning|info|debug)' '#' False '.bk' ''' # Get the regex for comment or uncomment if cmnt: regex = '{0}({1}){2}'.format( '^' if regex.startswith('^') else '', regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') else: regex = r'^{0}\s*({1}){2}'.format( char, regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') # Load the real path to the file path = os.path.realpath(os.path.expanduser(path)) # Make sure the file exists if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) # Make sure it is a text file if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}'.format(path)) # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes found = False # Dictionaries for comparing changes orig_file = [] new_file = [] # Buffer size for fopen bufsize = os.path.getsize(path) try: # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: # Is it in this line line = salt.utils.stringutils.to_unicode(line) if re.match(regex, line): # Load lines into dictionaries, set found to True orig_file.append(line) if cmnt: new_file.append('{0}{1}'.format(char, line)) else: new_file.append(line.lstrip(char)) found = True except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) # We've searched the whole file. If we didn't find anything, return False if not found: return False if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Create a copy to read from and to use as a backup later try: temp_file = _mkstemp_copy(path=path, preserve_inode=False) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) try: # Open the file in write mode mode = 'wb' if six.PY2 and salt.utils.platform.is_windows() else 'w' with salt.utils.files.fopen(path, mode=mode, buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: line = salt.utils.stringutils.to_unicode(line) try: # Is it in this line if re.match(regex, line): # Write the new line if cmnt: wline = '{0}{1}'.format(char, line) else: wline = line.lstrip(char) else: # Write the existing line (no change) wline = line wline = salt.utils.stringutils.to_bytes(wline) \ if six.PY2 and salt.utils.platform.is_windows() \ else salt.utils.stringutils.to_str(wline) w_file.write(wline) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if backup: # Move the backup file to the original directory backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: os.remove(temp_file) if not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) # Return a diff using the two dictionaries return __utils__['stringutils.get_diff'](orig_file, new_file) def _get_flags(flags): ''' Return an integer appropriate for use as a flag for the re module from a list of human-readable strings .. code-block:: python >>> _get_flags(['MULTILINE', 'IGNORECASE']) 10 >>> _get_flags('MULTILINE') 8 >>> _get_flags(2) 2 ''' if isinstance(flags, six.string_types): flags = [flags] if isinstance(flags, Iterable) and not isinstance(flags, Mapping): _flags_acc = [] for flag in flags: _flag = getattr(re, six.text_type(flag).upper()) if not isinstance(_flag, six.integer_types): raise SaltInvocationError( 'Invalid re flag given: {0}'.format(flag) ) _flags_acc.append(_flag) return reduce(operator.__or__, _flags_acc) elif isinstance(flags, six.integer_types): return flags else: raise SaltInvocationError( 'Invalid re flags: "{0}", must be given either as a single flag ' 'string, a list of strings, or as an integer'.format(flags) ) def _add_flags(flags, new_flags): ''' Combine ``flags`` and ``new_flags`` ''' flags = _get_flags(flags) new_flags = _get_flags(new_flags) return flags | new_flags def _mkstemp_copy(path, preserve_inode=True): ''' Create a temp file and move/copy the contents of ``path`` to the temp file. Return the path to the temp file. path The full path to the file whose contents will be moved/copied to a temp file. Whether it's moved or copied depends on the value of ``preserve_inode``. preserve_inode Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). Default is ``True``. ''' temp_file = None # Create the temp file try: temp_file = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to create temp file. " "Exception: {0}".format(exc) ) # use `copy` to preserve the inode of the # original file, and thus preserve hardlinks # to the inode. otherwise, use `move` to # preserve prior behavior, which results in # writing the file to a new inode. if preserve_inode: try: shutil.copy2(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to copy file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: try: shutil.move(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) return temp_file def _starts_till(src, probe, strip_comments=True): ''' Returns True if src and probe at least matches at the beginning till some point. ''' def _strip_comments(txt): ''' Strip possible comments. Usually comments are one or two symbols at the beginning of the line, separated with space ''' buff = txt.split(" ", 1) return len(buff) == 2 and len(buff[0]) < 2 and buff[1] or txt def _to_words(txt): ''' Split by words ''' return txt and [w for w in txt.strip().split(" ") if w.strip()] or txt no_match = -1 equal = 0 if not src or not probe: return no_match src = src.rstrip('\n\r') probe = probe.rstrip('\n\r') if src == probe: return equal src = _to_words(strip_comments and _strip_comments(src) or src) probe = _to_words(strip_comments and _strip_comments(probe) or probe) a_buff, b_buff = len(src) < len(probe) and (src, probe) or (probe, src) b_buff = ' '.join(b_buff) for idx in range(len(a_buff)): prb = ' '.join(a_buff[:-(idx + 1)]) if prb and b_buff.startswith(prb): return idx return no_match def _regex_to_static(src, regex): ''' Expand regular expression to static match. ''' if not src or not regex: return None try: compiled = re.compile(regex, re.DOTALL) src = [line for line in src if compiled.search(line) or line.count(regex)] except Exception as ex: raise CommandExecutionError("{0}: '{1}'".format(_get_error_message(ex), regex)) return src and src or [] def _assert_occurrence(probe, target, amount=1): ''' Raise an exception, if there are different amount of specified occurrences in src. ''' occ = len(probe) if occ > amount: msg = 'more than' elif occ < amount: msg = 'less than' elif not occ: msg = 'no' else: msg = None if msg: raise CommandExecutionError('Found {0} expected occurrences in "{1}" expression'.format(msg, target)) return occ def _set_line_indent(src, line, indent): ''' Indent the line with the source line. ''' if not indent: return line idt = [] for c in src: if c not in ['\t', ' ']: break idt.append(c) return ''.join(idt) + line.lstrip() def _get_eol(line): match = re.search('((?<!\r)\n|\r(?!\n)|\r\n)$', line) return match and match.group() or '' def _set_line_eol(src, line): ''' Add line ending ''' line_ending = _get_eol(src) or os.linesep return line.rstrip() + line_ending def _insert_line_before(idx, body, content, indent): if not idx or (idx and _starts_till(body[idx - 1], content) < 0): cnd = _set_line_indent(body[idx], content, indent) body.insert(idx, cnd) return body def _insert_line_after(idx, body, content, indent): # No duplicates or append, if "after" is the last line next_line = idx + 1 < len(body) and body[idx + 1] or None if next_line is None or _starts_till(next_line, content) < 0: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) return body def line(path, content=None, match=None, mode=None, location=None, before=None, after=None, show_changes=True, backup=False, quiet=False, indent=True): ''' .. versionadded:: 2015.8.0 Edit a line in the configuration file. The ``path`` and ``content`` arguments are required, as well as passing in one of the ``mode`` options. path Filesystem path to the file to be edited. content Content of the line. Allowed to be empty if mode=delete. match Match the target line for an action by a fragment of a string or regular expression. If neither ``before`` nor ``after`` are provided, and ``match`` is also ``None``, match becomes the ``content`` value. mode Defines how to edit a line. One of the following options is required: - ensure If line does not exist, it will be added. This is based on the ``content`` argument. - replace If line already exists, it will be replaced. - delete Delete the line, once found. - insert Insert a line. .. note:: If ``mode=insert`` is used, at least one of the following options must also be defined: ``location``, ``before``, or ``after``. If ``location`` is used, it takes precedence over the other two options. location Defines where to place content in the line. Note this option is only used when ``mode=insert`` is specified. If a location is passed in, it takes precedence over both the ``before`` and ``after`` kwargs. Valid locations are: - start Place the content at the beginning of the file. - end Place the content at the end of the file. before Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. after Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. show_changes Output a unified diff of the old file and the new file. If ``False`` return a boolean if any changes were made. Default is ``True`` .. note:: Using this option will store two copies of the file in-memory (the original version and the edited version) in order to generate the diff. backup Create a backup of the original file with the extension: "Year-Month-Day-Hour-Minutes-Seconds". quiet Do not raise any exceptions. E.g. ignore the fact that the file that is tried to be edited does not exist and nothing really happened. indent Keep indentation with the previous line. This option is not considered when the ``delete`` mode is specified. CLI Example: .. code-block:: bash salt '*' file.line /etc/nsswitch.conf "networks:\tfiles dns" after="hosts:.*?" mode='ensure' .. note:: If an equal sign (``=``) appears in an argument to a Salt command, it is interpreted as a keyword argument in the format of ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.line /path/to/file content="CREATEMAIL_SPOOL=no" match="CREATE_MAIL_SPOOL=yes" mode="replace" ''' path = os.path.realpath(os.path.expanduser(path)) if not os.path.isfile(path): if not quiet: raise CommandExecutionError('File "{0}" does not exists or is not a file.'.format(path)) return False # No changes had happened mode = mode and mode.lower() or mode if mode not in ['insert', 'ensure', 'delete', 'replace']: if mode is None: raise CommandExecutionError('Mode was not defined. How to process the file?') else: raise CommandExecutionError('Unknown mode: "{0}"'.format(mode)) # We've set the content to be empty in the function params but we want to make sure # it gets passed when needed. Feature #37092 empty_content_modes = ['delete'] if mode not in empty_content_modes and content is None: raise CommandExecutionError('Content can only be empty if mode is "{0}"'.format(', '.join(empty_content_modes))) del empty_content_modes # Before/after has privilege. If nothing defined, match is used by content. if before is None and after is None and not match: match = content with salt.utils.files.fopen(path, mode='r') as fp_: body = salt.utils.data.decode_list(fp_.readlines()) body_before = hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() # Add empty line at the end if last line ends with eol. # Allows simpler code if body and _get_eol(body[-1]): body.append('') after = _regex_to_static(body, after) before = _regex_to_static(body, before) match = _regex_to_static(body, match) if os.stat(path).st_size == 0 and mode in ('delete', 'replace'): log.warning('Cannot find text to %s. File \'%s\' is empty.', mode, path) body = [] elif mode == 'delete' and match: body = [line for line in body if line != match[0]] elif mode == 'replace' and match: idx = body.index(match[0]) file_line = body.pop(idx) body.insert(idx, _set_line_indent(file_line, content, indent)) elif mode == 'insert': if not location and not before and not after: raise CommandExecutionError('On insert must be defined either "location" or "before/after" conditions.') if not location: if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') out = [] in_range = False for line in body: if line == after[0]: in_range = True elif line == before[0] and in_range: cnd = _set_line_indent(line, content, indent) out.append(cnd) out.append(line) body = out if before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif after and not before: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: if location == 'start': if body: body.insert(0, _set_line_eol(body[0], content)) else: body.append(content + os.linesep) elif location == 'end': body.append(_set_line_indent(body[-1], content, indent) if body else content) elif mode == 'ensure': if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') is_there = bool([l for l in body if l.count(content)]) if not is_there: idx = body.index(after[0]) if idx < (len(body) - 1) and body[idx + 1] == before[0]: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) else: raise CommandExecutionError('Found more than one line between ' 'boundaries "before" and "after".') elif before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif not before and after: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: raise CommandExecutionError("Wrong conditions? " "Unable to ensure line without knowing " "where to put it before and/or after.") if body: for idx, line in enumerate(body): if not _get_eol(line) and idx+1 < len(body): prev = idx and idx-1 or 1 body[idx] = _set_line_eol(body[prev], line) # We do not need empty line at the end anymore if '' == body[-1]: body.pop() changed = body_before != hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() if backup and changed and __opts__['test'] is False: try: temp_file = _mkstemp_copy(path=path, preserve_inode=True) shutil.move(temp_file, '{0}.{1}'.format(path, time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime()))) except (OSError, IOError) as exc: raise CommandExecutionError("Unable to create the backup file of {0}. Exception: {1}".format(path, exc)) changes_diff = None if changed: if show_changes: with salt.utils.files.fopen(path, 'r') as fp_: path_content = salt.utils.data.decode_list(fp_.read().splitlines(True)) changes_diff = __utils__['stringutils.get_diff'](path_content, body) if __opts__['test'] is False: fh_ = None try: # Make sure we match the file mode from salt.utils.files.fopen if six.PY2 and salt.utils.platform.is_windows(): mode = 'wb' body = salt.utils.data.encode_list(body) else: mode = 'w' body = salt.utils.data.decode_list(body, to_str=True) fh_ = salt.utils.atomicfile.atomic_open(path, mode) fh_.writelines(body) finally: if fh_: fh_.close() return show_changes and changes_diff or changed def replace(path, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, backup='.bak', dry_run=False, search_only=False, show_changes=True, ignore_if_missing=False, preserve_inode=True, backslash_literal=False, ): ''' .. versionadded:: 0.17.0 Replace occurrences of a pattern in a file. If ``show_changes`` is ``True``, then a diff of what changed will be returned, otherwise a ``True`` will be returned when changes are made, and ``False`` when no changes are made. This is a pure Python implementation that wraps Python's :py:func:`~re.sub`. path Filesystem path to the file to be edited. If a symlink is specified, it will be resolved to its target. pattern A regular expression, to be matched using Python's :py:func:`~re.search`. repl The replacement text count : 0 Maximum number of pattern occurrences to be replaced. If count is a positive integer ``n``, only ``n`` occurrences will be replaced, otherwise all occurrences will be replaced. flags (list or int) A list of flags defined in the ``re`` module documentation from the Python standard library. Each list item should be a string that will correlate to the human-friendly flag name. E.g., ``['IGNORECASE', 'MULTILINE']``. Optionally, ``flags`` may be an int, with a value corresponding to the XOR (``|``) of all the desired flags. Defaults to 8 (which supports 'MULTILINE'). bufsize (int or str) How much of the file to buffer into memory at once. The default value ``1`` processes one line at a time. The special value ``file`` may be specified which will read the entire file into memory before processing. append_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True``, and pattern is not found, then the content will be appended to the file. prepend_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True`` and pattern is not found, then the content will be prepended to the file. not_found_content .. versionadded:: 2014.7.0 Content to use for append/prepend if not found. If None (default), uses ``repl``. Useful when ``repl`` uses references to group in pattern. backup : .bak The file extension to use for a backup of the file before editing. Set to ``False`` to skip making a backup. dry_run : False If set to ``True``, no changes will be made to the file, the function will just return the changes that would have been made (or a ``True``/``False`` value if ``show_changes`` is set to ``False``). search_only : False If set to true, this no changes will be performed on the file, and this function will simply return ``True`` if the pattern was matched, and ``False`` if not. show_changes : True If ``True``, return a diff of changes made. Otherwise, return ``True`` if changes were made, and ``False`` if not. .. note:: Using this option will store two copies of the file in memory (the original version and the edited version) in order to generate the diff. This may not normally be a concern, but could impact performance if used with large files. ignore_if_missing : False .. versionadded:: 2015.8.0 If set to ``True``, this function will simply return ``False`` if the file doesn't exist. Otherwise, an error will be thrown. preserve_inode : True .. versionadded:: 2015.8.0 Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). backslash_literal : False .. versionadded:: 2016.11.7 Interpret backslashes as literal backslashes for the repl and not escape characters. This will help when using append/prepend so that the backslashes are not interpreted for the repl on the second run of the state. If an equal sign (``=``) appears in an argument to a Salt command it is interpreted as a keyword argument in the format ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.replace /path/to/file pattern='=' repl=':' salt '*' file.replace /path/to/file pattern="bind-address\\s*=" repl='bind-address:' CLI Examples: .. code-block:: bash salt '*' file.replace /etc/httpd/httpd.conf pattern='LogLevel warn' repl='LogLevel info' salt '*' file.replace /some/file pattern='before' repl='after' flags='[MULTILINE, IGNORECASE]' ''' symlink = False if is_link(path): symlink = True target_path = os.readlink(path) given_path = os.path.expanduser(path) path = os.path.realpath(os.path.expanduser(path)) if not os.path.exists(path): if ignore_if_missing: return False else: raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if search_only and (append_if_not_found or prepend_if_not_found): raise SaltInvocationError( 'search_only cannot be used with append/prepend_if_not_found' ) if append_if_not_found and prepend_if_not_found: raise SaltInvocationError( 'Only one of append and prepend_if_not_found is permitted' ) flags_num = _get_flags(flags) cpattern = re.compile(salt.utils.stringutils.to_bytes(pattern), flags_num) filesize = os.path.getsize(path) if bufsize == 'file': bufsize = filesize # Search the file; track if any changes have been made for the return val has_changes = False orig_file = [] # used for show_changes and change detection new_file = [] # used for show_changes and change detection if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Avoid TypeErrors by forcing repl to be bytearray related to mmap # Replacement text may contains integer: 123 for example repl = salt.utils.stringutils.to_bytes(six.text_type(repl)) if not_found_content: not_found_content = salt.utils.stringutils.to_bytes(not_found_content) found = False temp_file = None content = salt.utils.stringutils.to_unicode(not_found_content) \ if not_found_content and (prepend_if_not_found or append_if_not_found) \ else salt.utils.stringutils.to_unicode(repl) try: # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes r_data = None # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: try: # mmap throws a ValueError if the file is empty. r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) except (ValueError, mmap.error): # size of file in /proc is 0, but contains data r_data = salt.utils.stringutils.to_bytes("".join(r_file)) if search_only: # Just search; bail as early as a match is found if re.search(cpattern, r_data): return True # `with` block handles file closure else: return False else: result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) # found anything? (even if no change) if nrepl > 0: found = True # Identity check the potential change has_changes = True if pattern != repl else has_changes if prepend_if_not_found or append_if_not_found: # Search for content, to avoid pre/appending the # content if it was pre/appended in a previous run. if re.search(salt.utils.stringutils.to_bytes('^{0}($|(?=\r\n))'.format(re.escape(content))), r_data, flags=flags_num): # Content was found, so set found. found = True orig_file = r_data.read(filesize).splitlines(True) \ if isinstance(r_data, mmap.mmap) \ else r_data.splitlines(True) new_file = result.splitlines(True) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() if has_changes and not dry_run: # Write the replacement text in this block. try: # Create a copy to read from and to use as a backup later temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) r_data = None try: # Open the file in write mode with salt.utils.files.fopen(path, mode='w', buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='r', buffering=bufsize) as r_file: r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) try: w_file.write(salt.utils.stringutils.to_str(result)) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if not found and (append_if_not_found or prepend_if_not_found): if not_found_content is None: not_found_content = repl if prepend_if_not_found: new_file.insert(0, not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) else: # append_if_not_found # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(salt.utils.stringutils.to_bytes(os.linesep)): new_file[-1] += salt.utils.stringutils.to_bytes(os.linesep) new_file.append(not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) has_changes = True if not dry_run: try: # Create a copy to read from and for later use as a backup temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line)) finally: fh_.close() if backup and has_changes and not dry_run: # keep the backup only if it was requested # and only if there were any changes backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) if symlink: symlink_backup = '{0}{1}'.format(given_path, backup) target_backup = '{0}{1}'.format(target_path, backup) # Always clobber any existing symlink backup # to match the behaviour of the 'backup' option try: os.symlink(target_backup, symlink_backup) except OSError: os.remove(symlink_backup) os.symlink(target_backup, symlink_backup) except Exception: raise CommandExecutionError( "Unable create backup symlink '{0}'. " "Target was '{1}'. " "Exception: {2}".format(symlink_backup, target_backup, exc) ) elif temp_file: try: os.remove(temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to delete temp file '{0}'. " "Exception: {1}".format(temp_file, exc) ) if not dry_run and not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) differences = __utils__['stringutils.get_diff'](orig_file, new_file) if show_changes: return differences # We may have found a regex line match but don't need to change the line # (for situations where the pattern also matches the repl). Revert the # has_changes flag to False if the final result is unchanged. if not differences: has_changes = False return has_changes def blockreplace(path, marker_start='#-- start managed zone --', marker_end='#-- end managed zone --', content='', append_if_not_found=False, prepend_if_not_found=False, backup='.bak', dry_run=False, show_changes=True, append_newline=False, insert_before_match=None, insert_after_match=None): ''' .. versionadded:: 2014.1.0 Replace content of a text block in a file, delimited by line markers A block of content delimited by comments can help you manage several lines entries without worrying about old entries removal. .. note:: This function will store two copies of the file in-memory (the original version and the edited version) in order to detect changes and only edit the targeted file if necessary. path Filesystem path to the file to be edited marker_start The line content identifying a line as the start of the content block. Note that the whole line containing this marker will be considered, so whitespace or extra content before or after the marker is included in final output marker_end The line content identifying the end of the content block. As of versions 2017.7.5 and 2018.3.1, everything up to the text matching the marker will be replaced, so it's important to ensure that your marker includes the beginning of the text you wish to replace. content The content to be used between the two lines identified by marker_start and marker_stop. append_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be appended to the file. prepend_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be prepended to the file. insert_before_match If markers are not found, this parameter can be set to a regex which will insert the block before the first found occurrence in the file. .. versionadded:: Neon insert_after_match If markers are not found, this parameter can be set to a regex which will insert the block after the first found occurrence in the file. .. versionadded:: Neon backup The file extension to use for a backup of the file if any edit is made. Set to ``False`` to skip making a backup. dry_run : False If ``True``, do not make any edits to the file and simply return the changes that *would* be made. show_changes : True Controls how changes are presented. If ``True``, this function will return a unified diff of the changes made. If False, then it will return a boolean (``True`` if any changes were made, otherwise ``False``). append_newline : False Controls whether or not a newline is appended to the content block. If the value of this argument is ``True`` then a newline will be added to the content block. If it is ``False``, then a newline will *not* be added to the content block. If it is ``None`` then a newline will only be added to the content block if it does not already end in a newline. .. versionadded:: 2016.3.4 .. versionchanged:: 2017.7.5,2018.3.1 New behavior added when value is ``None``. .. versionchanged:: 2019.2.0 The default value of this argument will change to ``None`` to match the behavior of the :py:func:`file.blockreplace state <salt.states.file.blockreplace>` CLI Example: .. code-block:: bash salt '*' file.blockreplace /etc/hosts '#-- start managed zone foobar : DO NOT EDIT --' \\ '#-- end managed zone foobar --' $'10.0.1.1 foo.foobar\\n10.0.1.2 bar.foobar' True ''' exclusive_params = [append_if_not_found, prepend_if_not_found, bool(insert_before_match), bool(insert_after_match)] if sum(exclusive_params) > 1: raise SaltInvocationError( 'Only one of append_if_not_found, prepend_if_not_found,' ' insert_before_match, and insert_after_match is permitted' ) path = os.path.expanduser(path) if not os.path.exists(path): raise SaltInvocationError('File not found: {0}'.format(path)) try: file_encoding = __utils__['files.get_encoding'](path) except CommandExecutionError: file_encoding = None if __utils__['files.is_binary'](path): if not file_encoding: raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if insert_before_match or insert_after_match: if insert_before_match: if not isinstance(insert_before_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_before_match parameter.' ) elif insert_after_match: if not isinstance(insert_after_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_after_match parameter.' ) if append_newline is None and not content.endswith((os.linesep, '\n')): append_newline = True # Split the content into a list of lines, removing newline characters. To # ensure that we handle both Windows and POSIX newlines, first split on # Windows newlines, and then split on POSIX newlines. split_content = [] for win_line in content.split('\r\n'): for content_line in win_line.split('\n'): split_content.append(content_line) line_count = len(split_content) has_changes = False orig_file = [] new_file = [] in_block = False block_found = False linesep = None def _add_content(linesep, lines=None, include_marker_start=True, end_line=None): if lines is None: lines = [] include_marker_start = True if end_line is None: end_line = marker_end end_line = end_line.rstrip('\r\n') + linesep if include_marker_start: lines.append(marker_start + linesep) if split_content: for index, content_line in enumerate(split_content, 1): if index != line_count: lines.append(content_line + linesep) else: # We're on the last line of the content block if append_newline: lines.append(content_line + linesep) lines.append(end_line) else: lines.append(content_line + end_line) else: lines.append(end_line) return lines # We do not use in-place editing to avoid file attrs modifications when # no changes are required and to avoid any file access on a partially # written file. try: fi_file = io.open(path, mode='r', encoding=file_encoding, newline='') for line in fi_file: write_line_to_new_file = True if linesep is None: # Auto-detect line separator if line.endswith('\r\n'): linesep = '\r\n' elif line.endswith('\n'): linesep = '\n' else: # No newline(s) in file, fall back to system's linesep linesep = os.linesep if marker_start in line: # We've entered the content block in_block = True else: if in_block: # We're not going to write the lines from the old file to # the new file until we have exited the block. write_line_to_new_file = False marker_end_pos = line.find(marker_end) if marker_end_pos != -1: # End of block detected in_block = False # We've found and exited the block block_found = True _add_content(linesep, lines=new_file, include_marker_start=False, end_line=line[marker_end_pos:]) # Save the line from the original file orig_file.append(line) if write_line_to_new_file: new_file.append(line) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read from {0}: {1}'.format(path, exc) ) finally: if linesep is None: # If the file was empty, we will not have set linesep yet. Assume # the system's line separator. This is needed for when we # prepend/append later on. linesep = os.linesep try: fi_file.close() except Exception: pass if in_block: # unterminated block => bad, always fail raise CommandExecutionError( 'Unterminated marked block. End of file reached before marker_end.' ) if not block_found: if prepend_if_not_found: # add the markers and content at the beginning of file prepended_content = _add_content(linesep) prepended_content.extend(new_file) new_file = prepended_content block_found = True elif append_if_not_found: # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(linesep): new_file[-1] += linesep # add the markers and content at the end of file _add_content(linesep, lines=new_file) block_found = True elif insert_before_match or insert_after_match: match_regex = insert_before_match or insert_after_match match_idx = [i for i, item in enumerate(orig_file) if re.search(match_regex, item)] if match_idx: match_idx = match_idx[0] for line in _add_content(linesep): if insert_after_match: match_idx += 1 new_file.insert(match_idx, line) if insert_before_match: match_idx += 1 block_found = True if not block_found: raise CommandExecutionError( 'Cannot edit marked block. Markers were not found in file.' ) diff = __utils__['stringutils.get_diff'](orig_file, new_file) has_changes = diff is not '' if has_changes and not dry_run: # changes detected # backup file attrs perms = {} perms['user'] = get_user(path) perms['group'] = get_group(path) perms['mode'] = salt.utils.files.normalize_mode(get_mode(path)) # backup old content if backup is not False: backup_path = '{0}{1}'.format(path, backup) shutil.copy2(path, backup_path) # copy2 does not preserve ownership check_perms(backup_path, None, perms['user'], perms['group'], perms['mode']) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line, encoding=file_encoding)) finally: fh_.close() # this may have overwritten file attrs check_perms(path, None, perms['user'], perms['group'], perms['mode']) if show_changes: return diff return has_changes def search(path, pattern, flags=8, bufsize=1, ignore_if_missing=False, multiline=False ): ''' .. versionadded:: 0.17.0 Search for occurrences of a pattern in a file Except for multiline, params are identical to :py:func:`~salt.modules.file.replace`. multiline If true, inserts 'MULTILINE' into ``flags`` and sets ``bufsize`` to 'file'. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' file.search /etc/crontab 'mymaintenance.sh' ''' if multiline: flags = _add_flags(flags, 'MULTILINE') bufsize = 'file' # This function wraps file.replace on purpose in order to enforce # consistent usage, compatible regex's, expected behavior, *and* bugs. :) # Any enhancements or fixes to one should affect the other. return replace(path, pattern, '', flags=flags, bufsize=bufsize, dry_run=True, search_only=True, show_changes=False, ignore_if_missing=ignore_if_missing) def patch(originalfile, patchfile, options='', dry_run=False): ''' .. versionadded:: 0.10.4 Apply a patch to a file or directory. Equivalent to: .. code-block:: bash patch <options> -i <patchfile> <originalfile> Or, when a directory is patched: .. code-block:: bash patch <options> -i <patchfile> -d <originalfile> -p0 originalfile The full path to the file or directory to be patched patchfile A patch file to apply to ``originalfile`` options Options to pass to patch. CLI Example: .. code-block:: bash salt '*' file.patch /opt/file.txt /tmp/file.txt.patch ''' patchpath = salt.utils.path.which('patch') if not patchpath: raise CommandExecutionError( 'patch executable not found. Is the distribution\'s patch ' 'package installed?' ) cmd = [patchpath] cmd.extend(salt.utils.args.shlex_split(options)) if dry_run: if __grains__['kernel'] in ('FreeBSD', 'OpenBSD'): cmd.append('-C') else: cmd.append('--dry-run') # this argument prevents interactive prompts when the patch fails to apply. # the exit code will still be greater than 0 if that is the case. if '-N' not in cmd and '--forward' not in cmd: cmd.append('--forward') has_rejectfile_option = False for option in cmd: if option == '-r' or option.startswith('-r ') \ or option.startswith('--reject-file'): has_rejectfile_option = True break # by default, patch will write rejected patch files to <filename>.rej. # this option prevents that. if not has_rejectfile_option: cmd.append('--reject-file=-') cmd.extend(['-i', patchfile]) if os.path.isdir(originalfile): cmd.extend(['-d', originalfile]) has_strip_option = False for option in cmd: if option.startswith('-p') or option.startswith('--strip='): has_strip_option = True break if not has_strip_option: cmd.append('--strip=0') else: cmd.append(originalfile) return __salt__['cmd.run_all'](cmd, python_shell=False) def contains(path, text): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the file at ``path`` contains ``text`` CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False stripped_text = six.text_type(text).strip() try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if stripped_text in chunk: return True return False except (IOError, OSError): return False def contains_regex(path, regex, lchar=''): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the given regular expression matches on any line in the text of a given file. If the lchar argument (leading char) is specified, it will strip `lchar` from the left side of each line before trying to match CLI Example: .. code-block:: bash salt '*' file.contains_regex /etc/crontab ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.files.fopen(path, 'r') as target: for line in target: line = salt.utils.stringutils.to_unicode(line) if lchar: line = line.lstrip(lchar) if re.search(regex, line): return True return False except (IOError, OSError): return False def contains_glob(path, glob_expr): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the given glob matches a string in the named file CLI Example: .. code-block:: bash salt '*' file.contains_glob /etc/foobar '*cheese*' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if fnmatch.fnmatch(chunk, glob_expr): return True return False except (IOError, OSError): return False def append(path, *args, **kwargs): ''' .. versionadded:: 0.9.5 Append text to the end of a file path path to file `*args` strings to append to file CLI Example: .. code-block:: bash salt '*' file.append /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.append /etc/motd args='cheese=spam' salt '*' file.append /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) # Largely inspired by Fabric's contrib.files.append() if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] # Make sure we have a newline at the end of the file. Do this in binary # mode so SEEK_END with nonzero offset will work. with salt.utils.files.fopen(path, 'rb+') as ofile: linesep = salt.utils.stringutils.to_bytes(os.linesep) try: ofile.seek(-len(linesep), os.SEEK_END) except IOError as exc: if exc.errno in (errno.EINVAL, errno.ESPIPE): # Empty file, simply append lines at the beginning of the file pass else: raise else: if ofile.read(len(linesep)) != linesep: ofile.seek(0, os.SEEK_END) ofile.write(linesep) # Append lines in text mode with salt.utils.files.fopen(path, 'a') as ofile: for new_line in args: ofile.write( salt.utils.stringutils.to_str( '{0}{1}'.format(new_line, os.linesep) ) ) return 'Wrote {0} lines to "{1}"'.format(len(args), path) def prepend(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Prepend text to the beginning of a file path path to file `*args` strings to prepend to the file CLI Example: .. code-block:: bash salt '*' file.prepend /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.prepend /etc/motd args='cheese=spam' salt '*' file.prepend /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] try: with salt.utils.files.fopen(path) as fhr: contents = [salt.utils.stringutils.to_unicode(line) for line in fhr.readlines()] except IOError: contents = [] preface = [] for line in args: preface.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, 'w') as ofile: contents = preface + contents ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Prepended {0} lines to "{1}"'.format(len(args), path) def write(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Write text to a file, overwriting any existing contents. path path to file `*args` strings to write to the file CLI Example: .. code-block:: bash salt '*' file.write /etc/motd \\ "With all thine offerings thou shalt offer salt." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.write /etc/motd args='cheese=spam' salt '*' file.write /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] contents = [] for line in args: contents.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, "w") as ofile: ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Wrote {0} lines to "{1}"'.format(len(contents), path) def touch(name, atime=None, mtime=None): ''' .. versionadded:: 0.9.5 Just like the ``touch`` command, create a file if it doesn't exist or simply update the atime and mtime if it already does. atime: Access time in Unix epoch time. Set it to 0 to set atime of the file with Unix date of birth. If this parameter isn't set, atime will be set with current time. mtime: Last modification in Unix epoch time. Set it to 0 to set mtime of the file with Unix date of birth. If this parameter isn't set, mtime will be set with current time. CLI Example: .. code-block:: bash salt '*' file.touch /var/log/emptyfile ''' name = os.path.expanduser(name) if atime and atime.isdigit(): atime = int(atime) if mtime and mtime.isdigit(): mtime = int(mtime) try: if not os.path.exists(name): with salt.utils.files.fopen(name, 'a'): pass if atime is None and mtime is None: times = None elif mtime is None and atime is not None: times = (atime, time.time()) elif atime is None and mtime is not None: times = (time.time(), mtime) else: times = (atime, mtime) os.utime(name, times) except TypeError: raise SaltInvocationError('atime and mtime must be integers') except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return os.path.exists(name) def tail(path, lines): ''' .. versionadded:: Neon Read the last n lines from a file path path to file lines number of lines to read CLI Example: .. code-block:: bash salt '*' file.tail /path/to/file 10 ''' path = os.path.expanduser(path) lines_found = [] buffer_size = 4098 if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot tail a binary file: {0}'.format(path)) try: lines = int(lines) except ValueError: raise SaltInvocationError('file.tail: \'lines\' value must be an integer') try: with salt.utils.fopen(path) as tail_fh: blk_cnt = 1 size = os.stat(path).st_size if size > buffer_size: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size), os.linesep) for i in range(lines): while len(data) == 1 and ((blk_cnt * buffer_size) < size): blk_cnt += 1 line = data[0] try: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size) + line, os.linesep) except IOError: tail_fh.seek(0) data = string.split(tail_fh.read(size - (buffer_size * (blk_cnt - 1))) + line, os.linesep) line = data[-1] data.pop() lines_found.append(line) return lines_found[-lines:] except (OSError, IOError): raise CommandExecutionError('Could not tail \'{0}\''.format(path)) def seek_read(path, size, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and read it path path to file seek amount to read at once offset offset to start into the file CLI Example: .. code-block:: bash salt '*' file.seek_read /path/to/file 4096 0 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_RDONLY) try: os.lseek(seek_fh, int(offset), 0) data = os.read(seek_fh, int(size)) finally: os.close(seek_fh) return data def seek_write(path, data, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and write to it path path to file data data to write to file offset position in file to start writing CLI Example: .. code-block:: bash salt '*' file.seek_write /path/to/file 'some data' 4096 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_WRONLY) try: os.lseek(seek_fh, int(offset), 0) ret = os.write(seek_fh, data) os.fsync(seek_fh) finally: os.close(seek_fh) return ret def truncate(path, length): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and delete everything after that point path path to file length offset into file to truncate CLI Example: .. code-block:: bash salt '*' file.truncate /path/to/file 512 ''' path = os.path.expanduser(path) with salt.utils.files.fopen(path, 'rb+') as seek_fh: seek_fh.truncate(int(length)) def link(src, path): ''' .. versionadded:: 2014.1.0 Create a hard link to a file CLI Example: .. code-block:: bash salt '*' file.link /path/to/file /path/to/link ''' src = os.path.expanduser(src) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.link(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def is_link(path): ''' Check if the path is a symbolic link CLI Example: .. code-block:: bash salt '*' file.is_link /path/to/link ''' # This function exists because os.path.islink does not support Windows, # therefore a custom function will need to be called. This function # therefore helps API consistency by providing a single function to call for # both operating systems. return os.path.islink(os.path.expanduser(path)) def symlink(src, path): ''' Create a symbolic link (symlink, soft link) to a file CLI Example: .. code-block:: bash salt '*' file.symlink /path/to/file /path/to/link ''' path = os.path.expanduser(path) try: if os.path.normpath(os.readlink(path)) == os.path.normpath(src): log.debug('link already in correct state: %s -> %s', path, src) return True except OSError: pass if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: os.symlink(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def rename(src, dst): ''' Rename a file or directory CLI Example: .. code-block:: bash salt '*' file.rename /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.rename(src, dst) return True except OSError: raise CommandExecutionError( 'Could not rename \'{0}\' to \'{1}\''.format(src, dst) ) return False def copy(src, dst, recurse=False, remove_existing=False): ''' Copy a file or directory from source to dst In order to copy a directory, the recurse flag is required, and will by default overwrite files in the destination with the same path, and retain all other existing files. (similar to cp -r on unix) remove_existing will remove all files in the target directory, and then copy files from the source. .. note:: The copy function accepts paths that are local to the Salt minion. This function does not support salt://, http://, or the other additional file paths that are supported by :mod:`states.file.managed <salt.states.file.managed>` and :mod:`states.file.recurse <salt.states.file.recurse>`. CLI Example: .. code-block:: bash salt '*' file.copy /path/to/src /path/to/dst salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True remove_existing=True ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') if not os.path.exists(src): raise CommandExecutionError('No such file or directory \'{0}\''.format(src)) if not salt.utils.platform.is_windows(): pre_user = get_user(src) pre_group = get_group(src) pre_mode = salt.utils.files.normalize_mode(get_mode(src)) try: if (os.path.exists(dst) and os.path.isdir(dst)) or os.path.isdir(src): if not recurse: raise SaltInvocationError( "Cannot copy overwriting a directory without recurse flag set to true!") if remove_existing: if os.path.exists(dst): shutil.rmtree(dst) shutil.copytree(src, dst) else: salt.utils.files.recursive_copy(src, dst) else: shutil.copyfile(src, dst) except OSError: raise CommandExecutionError( 'Could not copy \'{0}\' to \'{1}\''.format(src, dst) ) if not salt.utils.platform.is_windows(): check_perms(dst, None, pre_user, pre_group, pre_mode) return True def lstat(path): ''' .. versionadded:: 2014.1.0 Returns the lstat attributes for the given file or dir. Does not support symbolic links. CLI Example: .. code-block:: bash salt '*' file.lstat /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to file must be absolute.') try: lst = os.lstat(path) return dict((key, getattr(lst, key)) for key in ('st_atime', 'st_ctime', 'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid')) except Exception: return {} def access(path, mode): ''' .. versionadded:: 2014.1.0 Test whether the Salt process has the specified access to the file. One of the following modes must be specified: .. code-block::text f: Test the existence of the path r: Test the readability of the path w: Test the writability of the path x: Test whether the path can be executed CLI Example: .. code-block:: bash salt '*' file.access /path/to/file f salt '*' file.access /path/to/file x ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') modes = {'f': os.F_OK, 'r': os.R_OK, 'w': os.W_OK, 'x': os.X_OK} if mode in modes: return os.access(path, modes[mode]) elif mode in six.itervalues(modes): return os.access(path, mode) else: raise SaltInvocationError('Invalid mode specified.') def read(path, binary=False): ''' .. versionadded:: 2017.7.0 Return the content of the file. CLI Example: .. code-block:: bash salt '*' file.read /path/to/file ''' access_mode = 'r' if binary is True: access_mode += 'b' with salt.utils.files.fopen(path, access_mode) as file_obj: return salt.utils.stringutils.to_unicode(file_obj.read()) def readlink(path, canonicalize=False): ''' .. versionadded:: 2014.1.0 Return the path that a symlink points to If canonicalize is set to True, then it return the final target CLI Example: .. code-block:: bash salt '*' file.readlink /path/to/link ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') if not os.path.islink(path): raise SaltInvocationError('A valid link was not specified.') if canonicalize: return os.path.realpath(path) else: return os.readlink(path) def readdir(path): ''' .. versionadded:: 2014.1.0 Return a list containing the contents of a directory CLI Example: .. code-block:: bash salt '*' file.readdir /path/to/dir/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Dir path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') dirents = ['.', '..'] dirents.extend(os.listdir(path)) return dirents def statvfs(path): ''' .. versionadded:: 2014.1.0 Perform a statvfs call against the filesystem that the file resides on CLI Example: .. code-block:: bash salt '*' file.statvfs /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: stv = os.statvfs(path) return dict((key, getattr(stv, key)) for key in ('f_bavail', 'f_bfree', 'f_blocks', 'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag', 'f_frsize', 'f_namemax')) except (OSError, IOError): raise CommandExecutionError('Could not statvfs \'{0}\''.format(path)) return False def stats(path, hash_type=None, follow_symlinks=True): ''' Return a dict containing the stats for a given file CLI Example: .. code-block:: bash salt '*' file.stats /etc/passwd ''' path = os.path.expanduser(path) ret = {} if not os.path.exists(path): try: # Broken symlinks will return False for os.path.exists(), but still # have a uid and gid pstat = os.lstat(path) except OSError: # Not a broken symlink, just a nonexistent path # NOTE: The file.directory state checks the content of the error # message in this exception. Any changes made to the message for this # exception will reflect the file.directory state as well, and will # likely require changes there. raise CommandExecutionError('Path not found: {0}'.format(path)) else: if follow_symlinks: pstat = os.stat(path) else: pstat = os.lstat(path) ret['inode'] = pstat.st_ino ret['uid'] = pstat.st_uid ret['gid'] = pstat.st_gid ret['group'] = gid_to_group(pstat.st_gid) ret['user'] = uid_to_user(pstat.st_uid) ret['atime'] = pstat.st_atime ret['mtime'] = pstat.st_mtime ret['ctime'] = pstat.st_ctime ret['size'] = pstat.st_size ret['mode'] = six.text_type(oct(stat.S_IMODE(pstat.st_mode))) if hash_type: ret['sum'] = get_hash(path, hash_type) ret['type'] = 'file' if stat.S_ISDIR(pstat.st_mode): ret['type'] = 'dir' if stat.S_ISCHR(pstat.st_mode): ret['type'] = 'char' if stat.S_ISBLK(pstat.st_mode): ret['type'] = 'block' if stat.S_ISREG(pstat.st_mode): ret['type'] = 'file' if stat.S_ISLNK(pstat.st_mode): ret['type'] = 'link' if stat.S_ISFIFO(pstat.st_mode): ret['type'] = 'pipe' if stat.S_ISSOCK(pstat.st_mode): ret['type'] = 'socket' ret['target'] = os.path.realpath(path) return ret def rmdir(path): ''' .. versionadded:: 2014.1.0 Remove the specified directory. Fails if a directory is not empty. CLI Example: .. code-block:: bash salt '*' file.rmdir /tmp/foo/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') try: os.rmdir(path) return True except OSError as exc: return exc.strerror def remove(path, **kwargs): ''' Remove the named file. If a directory is supplied, it will be recursively deleted. CLI Example: .. code-block:: bash salt '*' file.remove /tmp/foo ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute: {0}'.format(path)) try: if os.path.isfile(path) or os.path.islink(path): os.remove(path) return True elif os.path.isdir(path): shutil.rmtree(path) return True except (OSError, IOError) as exc: raise CommandExecutionError( 'Could not remove \'{0}\': {1}'.format(path, exc) ) return False def directory_exists(path): ''' Tests to see if path is a valid directory. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.directory_exists /etc ''' return os.path.isdir(os.path.expanduser(path)) def file_exists(path): ''' Tests to see if path is a valid file. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.file_exists /etc/passwd ''' return os.path.isfile(os.path.expanduser(path)) def path_exists_glob(path): ''' Tests to see if path after expansion is a valid path (file or directory). Expansion allows usage of ? * and character ranges []. Tilde expansion is not supported. Returns True/False. .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' file.path_exists_glob /etc/pam*/pass* ''' return True if glob.glob(os.path.expanduser(path)) else False def restorecon(path, recursive=False): ''' Reset the SELinux context on a given path CLI Example: .. code-block:: bash salt '*' file.restorecon /home/user/.ssh/authorized_keys ''' if recursive: cmd = ['restorecon', '-FR', path] else: cmd = ['restorecon', '-F', path] return not __salt__['cmd.retcode'](cmd, python_shell=False) def get_selinux_context(path): ''' Get an SELinux context from a given path CLI Example: .. code-block:: bash salt '*' file.get_selinux_context /etc/hosts ''' out = __salt__['cmd.run'](['ls', '-Z', path], python_shell=False) try: ret = re.search(r'\w+:\w+:\w+:\w+', out).group(0) except AttributeError: ret = ( 'No selinux context information is available for {0}'.format(path) ) return ret def set_selinux_context(path, user=None, role=None, type=None, # pylint: disable=W0622 range=None, # pylint: disable=W0622 persist=False): ''' .. versionchanged:: Neon Added persist option Set a specific SELinux label on a given path CLI Example: .. code-block:: bash salt '*' file.set_selinux_context path <user> <role> <type> <range> salt '*' file.set_selinux_context /etc/yum.repos.d/epel.repo system_u object_r system_conf_t s0 ''' if not any((user, role, type, range)): return False if persist: fcontext_result = __salt__['selinux.fcontext_add_policy'](path, sel_type=type, sel_user=user, sel_level=range) if fcontext_result.get('retcode', None) is not 0: # Problem setting fcontext policy raise CommandExecutionError( 'Problem setting fcontext: {0}'.format(fcontext_result) ) cmd = ['chcon'] if user: cmd.extend(['-u', user]) if role: cmd.extend(['-r', role]) if type: cmd.extend(['-t', type]) if range: cmd.extend(['-l', range]) cmd.append(path) ret = not __salt__['cmd.retcode'](cmd, python_shell=False) if ret: return get_selinux_context(path) else: return ret def source_list(source, source_hash, saltenv): ''' Check the source list and return the source to use CLI Example: .. code-block:: bash salt '*' file.source_list salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' base ''' contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv) if contextkey in __context__: return __context__[contextkey] # get the master file list if isinstance(source, list): mfiles = [(f, saltenv) for f in __salt__['cp.list_master'](saltenv)] mdirs = [(d, saltenv) for d in __salt__['cp.list_master_dirs'](saltenv)] for single in source: if isinstance(single, dict): single = next(iter(single)) path, senv = salt.utils.url.parse(single) if senv: mfiles += [(f, senv) for f in __salt__['cp.list_master'](senv)] mdirs += [(d, senv) for d in __salt__['cp.list_master_dirs'](senv)] ret = None for single in source: if isinstance(single, dict): # check the proto, if it is http or ftp then download the file # to check, if it is salt then check the master list # if it is a local file, check if the file exists if len(single) != 1: continue single_src = next(iter(single)) single_hash = single[single_src] if single[single_src] else source_hash urlparsed_single_src = _urlparse(single_src) # Fix this for Windows if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_single_src.scheme.lower() in string.ascii_lowercase: urlparsed_single_src = _urlparse('file://' + single_src) proto = urlparsed_single_src.scheme if proto == 'salt': path, senv = salt.utils.url.parse(single_src) if not senv: senv = saltenv if (path, saltenv) in mfiles or (path, saltenv) in mdirs: ret = (single_src, single_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single_src, single_hash) break elif proto == 'file' and ( os.path.exists(urlparsed_single_src.netloc) or os.path.exists(urlparsed_single_src.path) or os.path.exists(os.path.join( urlparsed_single_src.netloc, urlparsed_single_src.path))): ret = (single_src, single_hash) break elif single_src.startswith(os.sep) and os.path.exists(single_src): ret = (single_src, single_hash) break elif isinstance(single, six.string_types): path, senv = salt.utils.url.parse(single) if not senv: senv = saltenv if (path, senv) in mfiles or (path, senv) in mdirs: ret = (single, source_hash) break urlparsed_src = _urlparse(single) if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_src.scheme.lower() in string.ascii_lowercase: urlparsed_src = _urlparse('file://' + single) proto = urlparsed_src.scheme if proto == 'file' and ( os.path.exists(urlparsed_src.netloc) or os.path.exists(urlparsed_src.path) or os.path.exists(os.path.join( urlparsed_src.netloc, urlparsed_src.path))): ret = (single, source_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single, source_hash) break elif single.startswith(os.sep) and os.path.exists(single): ret = (single, source_hash) break if ret is None: # None of the list items matched raise CommandExecutionError( 'none of the specified sources were found' ) else: ret = (source, source_hash) __context__[contextkey] = ret return ret def apply_template_on_contents( contents, template, context, defaults, saltenv): ''' Return the contents after applying the templating engine contents template string template template format context Overrides default context variables passed to the template. defaults Default context passed to the template. CLI Example: .. code-block:: bash salt '*' file.apply_template_on_contents \\ contents='This is a {{ template }} string.' \\ template=jinja \\ "context={}" "defaults={'template': 'cool'}" \\ saltenv=base ''' if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) # Apply templating contents = salt.utils.templates.TEMPLATE_REGISTRY[template]( contents, from_str=True, to_str=True, context=context_dict, saltenv=saltenv, grains=__opts__['grains'], pillar=__pillar__, salt=__salt__, opts=__opts__)['data'] if six.PY2: contents = contents.encode('utf-8') elif six.PY3 and isinstance(contents, bytes): # bytes -> str contents = contents.decode('utf-8') else: ret = {} ret['result'] = False ret['comment'] = ('Specified template format {0} is not supported' ).format(template) return ret return contents def get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify=False, **kwargs): ''' Return the managed file data for file.managed name location where the file lives on the server template template format source managed source file source_hash hash of the source file source_hash_name When ``source_hash`` refers to a remote file, this specifies the filename to look for in that file. .. versionadded:: 2016.3.5 user Owner of file group Group owner of file mode Permissions of file attrs Attributes of file .. versionadded:: 2018.3.0 context Variables to add to the template context defaults Default values of for context_dict skip_verify If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' file.get_managed /etc/httpd/conf.d/httpd.conf jinja salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' None root root '755' base None None ''' # Copy the file to the minion and templatize it sfn = '' source_sum = {} def _get_local_file_source_sum(path): ''' DRY helper for getting the source_sum value from a locally cached path. ''' return {'hsum': get_hash(path, form='sha256'), 'hash_type': 'sha256'} # If we have a source defined, let's figure out what the hash is if source: urlparsed_source = _urlparse(source) if urlparsed_source.scheme in salt.utils.files.VALID_PROTOS: parsed_scheme = urlparsed_source.scheme else: parsed_scheme = '' parsed_path = os.path.join( urlparsed_source.netloc, urlparsed_source.path).rstrip(os.sep) unix_local_source = parsed_scheme in ('file', '') if parsed_scheme == '': parsed_path = sfn = source if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg elif parsed_scheme == 'file': sfn = parsed_path if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg if parsed_scheme and parsed_scheme.lower() in string.ascii_lowercase: parsed_path = ':'.join([parsed_scheme, parsed_path]) parsed_scheme = 'file' if parsed_scheme == 'salt': source_sum = __salt__['cp.hash_file'](source, saltenv) if not source_sum: return '', {}, 'Source file {0} not found in saltenv \'{1}\''.format(source, saltenv) elif not source_hash and unix_local_source: source_sum = _get_local_file_source_sum(parsed_path) elif not source_hash and source.startswith(os.sep): # This should happen on Windows source_sum = _get_local_file_source_sum(source) else: if not skip_verify: if source_hash: try: source_sum = get_source_sum(name, source, source_hash, source_hash_name, saltenv) except CommandExecutionError as exc: return '', {}, exc.strerror else: msg = ( 'Unable to verify upstream hash of source file {0}, ' 'please set source_hash or set skip_verify to True' .format(salt.utils.url.redact_http_basic_auth(source)) ) return '', {}, msg if source and (template or parsed_scheme in salt.utils.files.REMOTE_PROTOS): # Check if we have the template or remote file cached cache_refetch = False cached_dest = __salt__['cp.is_cached'](source, saltenv) if cached_dest and (source_hash or skip_verify): htype = source_sum.get('hash_type', 'sha256') cached_sum = get_hash(cached_dest, form=htype) if skip_verify: # prev: if skip_verify or cached_sum == source_sum['hsum']: # but `cached_sum == source_sum['hsum']` is elliptical as prev if sfn = cached_dest source_sum = {'hsum': cached_sum, 'hash_type': htype} elif cached_sum != source_sum.get('hsum', __opts__['hash_type']): cache_refetch = True else: sfn = cached_dest # If we didn't have the template or remote file, or the file has been # updated and the cache has to be refreshed, download the file. if not sfn or cache_refetch: try: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum.get('hsum')) except Exception as exc: # A 404 or other error code may raise an exception, catch it # and return a comment that will fail the calling state. _source = salt.utils.url.redact_http_basic_auth(source) return '', {}, 'Failed to cache {0}: {1}'.format(_source, exc) # If cache failed, sfn will be False, so do a truth check on sfn first # as invoking os.path.exists() on a bool raises a TypeError. if not sfn or not os.path.exists(sfn): _source = salt.utils.url.redact_http_basic_auth(source) return sfn, {}, 'Source file \'{0}\' not found'.format(_source) if sfn == name: raise SaltInvocationError( 'Source file cannot be the same as destination' ) if template: if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, name=name, source=source, user=user, group=group, mode=mode, attrs=attrs, saltenv=saltenv, context=context_dict, salt=__salt__, pillar=__pillar__, grains=__opts__['grains'], opts=__opts__, **kwargs) else: return sfn, {}, ('Specified template format {0} is not supported' ).format(template) if data['result']: sfn = data['data'] hsum = get_hash(sfn, form='sha256') source_sum = {'hash_type': 'sha256', 'hsum': hsum} else: __clean_tmp(sfn) return sfn, {}, data['data'] return sfn, source_sum, '' def extract_hash(hash_fn, hash_type='sha256', file_name='', source='', source_hash_name=None): ''' .. versionchanged:: 2016.3.5 Prior to this version, only the ``file_name`` argument was considered for filename matches in the hash file. This would be problematic for cases in which the user was relying on a remote checksum file that they do not control, and they wished to use a different name for that file on the minion from the filename on the remote server (and in the checksum file). For example, managing ``/tmp/myfile.tar.gz`` when the remote file was at ``https://mydomain.tld/different_name.tar.gz``. The :py:func:`file.managed <salt.states.file.managed>` state now also passes this function the source URI as well as the ``source_hash_name`` (if specified). In cases where ``source_hash_name`` is specified, it takes precedence over both the ``file_name`` and ``source``. When it is not specified, ``file_name`` takes precedence over ``source``. This allows for better capability for matching hashes. .. versionchanged:: 2016.11.0 File name and source URI matches are no longer disregarded when ``source_hash_name`` is specified. They will be used as fallback matches if there is no match to the ``source_hash_name`` value. This routine is called from the :mod:`file.managed <salt.states.file.managed>` state to pull a hash from a remote file. Regular expressions are used line by line on the ``source_hash`` file, to find a potential candidate of the indicated hash type. This avoids many problems of arbitrary file layout rules. It specifically permits pulling hash codes from debian ``*.dsc`` files. If no exact match of a hash and filename are found, then the first hash found (if any) will be returned. If no hashes at all are found, then ``None`` will be returned. For example: .. code-block:: yaml openerp_7.0-latest-1.tar.gz: file.managed: - name: /tmp/openerp_7.0-20121227-075624-1_all.deb - source: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.tar.gz - source_hash: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.dsc CLI Example: .. code-block:: bash salt '*' file.extract_hash /path/to/hash/file sha512 /etc/foo ''' hash_len = HASHES.get(hash_type) if hash_len is None: if hash_type: log.warning( 'file.extract_hash: Unsupported hash_type \'%s\', falling ' 'back to matching any supported hash_type', hash_type ) hash_type = '' hash_len_expr = '{0},{1}'.format(min(HASHES_REVMAP), max(HASHES_REVMAP)) else: hash_len_expr = six.text_type(hash_len) filename_separators = string.whitespace + r'\/' if source_hash_name: if not isinstance(source_hash_name, six.string_types): source_hash_name = six.text_type(source_hash_name) source_hash_name_idx = (len(source_hash_name) + 1) * -1 log.debug( 'file.extract_hash: Extracting %s hash for file matching ' 'source_hash_name \'%s\'', 'any supported' if not hash_type else hash_type, source_hash_name ) if file_name: if not isinstance(file_name, six.string_types): file_name = six.text_type(file_name) file_name_basename = os.path.basename(file_name) file_name_idx = (len(file_name_basename) + 1) * -1 if source: if not isinstance(source, six.string_types): source = six.text_type(source) urlparsed_source = _urlparse(source) source_basename = os.path.basename( urlparsed_source.path or urlparsed_source.netloc ) source_idx = (len(source_basename) + 1) * -1 basename_searches = [x for x in (file_name, source) if x] if basename_searches: log.debug( 'file.extract_hash: %s %s hash for file matching%s: %s', 'If no source_hash_name match found, will extract' if source_hash_name else 'Extracting', 'any supported' if not hash_type else hash_type, '' if len(basename_searches) == 1 else ' either of the following', ', '.join(basename_searches) ) partial = None found = {} with salt.utils.files.fopen(hash_fn, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line.strip()) hash_re = r'(?i)(?<![a-z0-9])([a-f0-9]{' + hash_len_expr + '})(?![a-z0-9])' hash_match = re.search(hash_re, line) matched = None if hash_match: matched_hsum = hash_match.group(1) if matched_hsum is not None: matched_type = HASHES_REVMAP.get(len(matched_hsum)) if matched_type is None: # There was a match, but it's not of the correct length # to match one of the supported hash types. matched = None else: matched = {'hsum': matched_hsum, 'hash_type': matched_type} if matched is None: log.debug( 'file.extract_hash: In line \'%s\', no %shash found', line, '' if not hash_type else hash_type + ' ' ) continue if partial is None: partial = matched def _add_to_matches(found, line, match_type, value, matched): log.debug( 'file.extract_hash: Line \'%s\' matches %s \'%s\'', line, match_type, value ) found.setdefault(match_type, []).append(matched) hash_matched = False if source_hash_name: if line.endswith(source_hash_name): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[source_hash_name_idx] in string.whitespace: _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source_hash_name) + r'\s+', line): _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True if file_name: if line.endswith(file_name_basename): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[file_name_idx] in filename_separators: _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(file_name) + r'\s+', line): _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True if source: if line.endswith(source_basename): # Same as above, we can't just do an rsplit here. try: if line[source_idx] in filename_separators: _add_to_matches(found, line, 'source', source, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source) + r'\s+', line): _add_to_matches(found, line, 'source', source, matched) hash_matched = True if not hash_matched: log.debug( 'file.extract_hash: Line \'%s\' contains %s hash ' '\'%s\', but line did not meet the search criteria', line, matched['hash_type'], matched['hsum'] ) for found_type, found_str in (('source_hash_name', source_hash_name), ('file_name', file_name), ('source', source)): if found_type in found: if len(found[found_type]) > 1: log.debug( 'file.extract_hash: Multiple %s matches for %s: %s', found_type, found_str, ', '.join( ['{0} ({1})'.format(x['hsum'], x['hash_type']) for x in found[found_type]] ) ) ret = found[found_type][0] log.debug( 'file.extract_hash: Returning %s hash \'%s\' as a match of %s', ret['hash_type'], ret['hsum'], found_str ) return ret if partial: log.debug( 'file.extract_hash: Returning the partially identified %s hash ' '\'%s\'', partial['hash_type'], partial['hsum'] ) return partial log.debug('file.extract_hash: No matches, returning None') return None def check_perms(name, ret, user, group, mode, attrs=None, follow_symlinks=False, seuser=None, serole=None, setype=None, serange=None): ''' .. versionchanged:: Neon Added selinux options Check the permissions on files, modify attributes and chown if needed. File attributes are only verified if lsattr(1) is installed. CLI Example: .. code-block:: bash salt '*' file.check_perms /etc/sudoers '{}' root root 400 ai .. versionchanged:: 2014.1.3 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': [], 'result': True} orig_comment = '' else: orig_comment = ret['comment'] ret['comment'] = [] # Check permissions perms = {} cur = stats(name, follow_symlinks=follow_symlinks) perms['luser'] = cur['user'] perms['lgroup'] = cur['group'] perms['lmode'] = salt.utils.files.normalize_mode(cur['mode']) is_dir = os.path.isdir(name) is_link = os.path.islink(name) if attrs is not None \ and not salt.utils.platform.is_windows() \ and not is_dir and not is_link: try: lattrs = lsattr(name) except SaltInvocationError: lattrs = None if lattrs is not None: # List attributes on file perms['lattrs'] = ''.join(lattrs.get(name, '')) # Remove attributes on file so changes can be enforced. if perms['lattrs']: chattr(name, operator='remove', attributes=perms['lattrs']) # user/group changes if needed, then check if it worked if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid(perms['luser']) ) or ( not salt.utils.platform.is_windows() and user != perms['luser'] ): perms['cuser'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid(perms['lgroup']) ) or ( not salt.utils.platform.is_windows() and group != perms['lgroup'] ): perms['cgroup'] = group if 'cuser' in perms or 'cgroup' in perms: if not __opts__['test']: if os.path.islink(name) and not follow_symlinks: chown_func = lchown else: chown_func = chown if user is None: user = perms['luser'] if group is None: group = perms['lgroup'] try: chown_func(name, user, group) # Python os.chown() does reset the suid and sgid, # that's why setting the right mode again is needed here. set_mode(name, mode) except OSError: ret['result'] = False if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid( get_user(name, follow_symlinks=follow_symlinks)) and user != '' ) or ( not salt.utils.platform.is_windows() and user != get_user(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['user'] = user else: ret['result'] = False ret['comment'].append('Failed to change user to {0}' .format(user)) elif 'cuser' in perms and user != '': ret['changes']['user'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid( get_group(name, follow_symlinks=follow_symlinks)) and user != '') or ( not salt.utils.platform.is_windows() and group != get_group(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['group'] = group else: ret['result'] = False ret['comment'].append('Failed to change group to {0}' .format(group)) elif 'cgroup' in perms and user != '': ret['changes']['group'] = group if not salt.utils.platform.is_windows() and not is_dir: # Replace attributes on file if it had been removed if perms.get('lattrs', ''): chattr(name, operator='add', attributes=perms['lattrs']) # Mode changes if needed if mode is not None: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: mode = salt.utils.files.normalize_mode(mode) if mode != perms['lmode']: if __opts__['test'] is True: ret['changes']['mode'] = mode else: set_mode(name, mode) if mode != salt.utils.files.normalize_mode(get_mode(name)): ret['result'] = False ret['comment'].append( 'Failed to change mode to {0}'.format(mode) ) else: ret['changes']['mode'] = mode # Modify attributes of file if needed if attrs is not None and not is_dir: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if diff_attrs[0] is not None or diff_attrs[1] is not None: if __opts__['test'] is True: ret['changes']['attrs'] = attrs else: if diff_attrs[0] is not None: chattr(name, operator="add", attributes=diff_attrs[0]) if diff_attrs[1] is not None: chattr(name, operator="remove", attributes=diff_attrs[1]) cmp_attrs = _cmp_attrs(name, attrs) if cmp_attrs[0] is not None or cmp_attrs[1] is not None: ret['result'] = False ret['comment'].append( 'Failed to change attributes to {0}'.format(attrs) ) else: ret['changes']['attrs'] = attrs # Set selinux attributes if needed if salt.utils.platform.is_linux() and (seuser or serole or setype or serange): selinux_error = False try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError: log.error('Unable to get current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to get selinux attributes' ) selinux_error = True if not selinux_error: requested_seuser = None requested_serole = None requested_setype = None requested_serange = None # Only set new selinux variables if updates are needed if seuser and seuser != current_seuser: requested_seuser = seuser if serole and serole != current_serole: requested_serole = serole if setype and setype != current_setype: requested_setype = setype if serange and serange != current_serange: requested_serange = serange if requested_seuser or requested_serole or requested_setype or requested_serange: # selinux updates needed, prep changes output selinux_change_new = '' selinux_change_orig = '' if requested_seuser: selinux_change_new += "User: {0} ".format(requested_seuser) selinux_change_orig += "User: {0} ".format(current_seuser) if requested_serole: selinux_change_new += "Role: {0} ".format(requested_serole) selinux_change_orig += "Role: {0} ".format(current_serole) if requested_setype: selinux_change_new += "Type: {0} ".format(requested_setype) selinux_change_orig += "Type: {0} ".format(current_setype) if requested_serange: selinux_change_new += "Range: {0} ".format(requested_serange) selinux_change_orig += "Range: {0} ".format(current_serange) if __opts__['test']: ret['comment'] = 'File {0} selinux context to be updated'.format(name) ret['result'] = None ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} else: try: # set_selinux_context requires type to be set on any other change if (requested_seuser or requested_serole or requested_serange) and not requested_setype: requested_setype = current_setype result = set_selinux_context(name, user=requested_seuser, role=requested_serole, type=requested_setype, range=requested_serange, persist=True) log.debug('selinux set result: %s', result) current_seuser, current_serole, current_setype, current_serange = result.split(':') except ValueError: log.error('Unable to set current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to set selinux attributes' ) selinux_error = True if not selinux_error: ret['comment'].append('The file {0} is set to be changed'.format(name)) if requested_seuser: if current_seuser != requested_seuser: ret['comment'].append("Unable to update seuser context") ret['result'] = False if requested_serole: if current_serole != requested_serole: ret['comment'].append("Unable to update serole context") ret['result'] = False if requested_setype: if current_setype != requested_setype: ret['comment'].append("Unable to update setype context") ret['result'] = False if requested_serange: if current_serange != requested_serange: ret['comment'].append("Unable to update serange context") ret['result'] = False ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} # Only combine the comment list into a string # after all comments are added above if isinstance(orig_comment, six.string_types): if orig_comment: ret['comment'].insert(0, orig_comment) ret['comment'] = '; '.join(ret['comment']) # Set result to None at the very end of the function, # after all changes have been recorded above if __opts__['test'] is True and ret['changes']: ret['result'] = None return ret, perms def check_managed( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Check to see what changes need to be made for a file CLI Example: .. code-block:: bash salt '*' file.check_managed /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) if comments: __clean_tmp(sfn) return False, comments changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) # Ignore permission for files written temporary directories # Files in any path will still be set correctly using get_managed() if name.startswith(tempfile.gettempdir()): for key in ['user', 'group', 'mode']: changes.pop(key, None) __clean_tmp(sfn) if changes: log.info(changes) comments = ['The following values are set to be changed:\n'] comments.extend('{0}: {1}\n'.format(key, val) for key, val in six.iteritems(changes)) return None, ''.join(comments) return True, 'The file {0} is in the correct state'.format(name) def check_managed_changes( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, keep_mode=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Return a dictionary of what changes need to be made for a file .. versionchanged:: Neon selinux attributes added CLI Example: .. code-block:: bash salt '*' file.check_managed_changes /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if comments: __clean_tmp(sfn) raise CommandExecutionError(comments) if sfn and source and keep_mode: if _urlparse(source).scheme in ('salt', 'file') \ or source.startswith('/'): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) __clean_tmp(sfn) return changes def check_file_meta( name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents=None, seuser=None, serole=None, setype=None, serange=None): ''' Check for the changes in the file metadata. CLI Example: .. code-block:: bash salt '*' file.check_file_meta /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' base .. note:: Supported hash types include sha512, sha384, sha256, sha224, sha1, and md5. name Path to file destination sfn Template-processed source file contents source URL to file source source_sum File checksum information as a dictionary .. code-block:: yaml {hash_type: md5, hsum: <md5sum>} user Destination file user owner group Destination file group owner mode Destination file permissions mode attrs Destination file attributes .. versionadded:: 2018.3.0 saltenv Salt environment used to resolve source files contents File contents seuser selinux user attribute .. versionadded:: Neon serole selinux role attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon ''' changes = {} if not source_sum: source_sum = dict() try: lstats = stats(name, hash_type=source_sum.get('hash_type', None), follow_symlinks=False) except CommandExecutionError: lstats = {} if not lstats: changes['newfile'] = name return changes if 'hsum' in source_sum: if source_sum['hsum'] != lstats['sum']: if not sfn and source: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum['hsum']) if sfn: try: changes['diff'] = get_diff( name, sfn, template=True, show_filenames=False) except CommandExecutionError as exc: changes['diff'] = exc.strerror else: changes['sum'] = 'Checksum differs' if contents is not None: # Write a tempfile with the static contents tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'w') as tmp_: tmp_.write(salt.utils.stringutils.to_str(contents)) # Compare the static contents with the named file try: differences = get_diff(name, tmp, show_filenames=False) except CommandExecutionError as exc: log.error('Failed to diff files: %s', exc) differences = exc.strerror __clean_tmp(tmp) if differences: if __salt__['config.option']('obfuscate_templates'): changes['diff'] = '<Obfuscated Template>' else: changes['diff'] = differences if not salt.utils.platform.is_windows(): # Check owner if (user is not None and user != lstats['user'] and user != lstats['uid']): changes['user'] = user # Check group if (group is not None and group != lstats['group'] and group != lstats['gid']): changes['group'] = group # Normalize the file mode smode = salt.utils.files.normalize_mode(lstats['mode']) mode = salt.utils.files.normalize_mode(mode) if mode is not None and mode != smode: changes['mode'] = mode if attrs: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if attrs is not None \ and (diff_attrs[0] is not None or diff_attrs[1] is not None): changes['attrs'] = attrs # Check selinux if seuser or serole or setype or serange: try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError as exc: log.error('Unable to get current selinux attributes') changes['selinux'] = exc.strerror if seuser and seuser != current_seuser: changes['selinux'] = {"user": seuser} if serole and serole != current_serole: changes['selinux'] = {"role": serole} if setype and setype != current_setype: changes['selinux'] = {"type": setype} if serange and serange != current_serange: changes['selinux'] = {"range": serange} return changes def get_diff(file1, file2, saltenv='base', show_filenames=True, show_changes=True, template=False, source_hash_file1=None, source_hash_file2=None): ''' Return unified diff of two files file1 The first file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, thuis had to be a file local to the minion. file2 The second file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, this had to be a file on the salt fileserver (i.e. ``salt://somefile.txt``) show_filenames : True Set to ``False`` to hide the filenames in the top two lines of the diff. show_changes : True If set to ``False``, and there are differences, then instead of a diff a simple message stating that show_changes is set to ``False`` will be returned. template : False Set to ``True`` if two templates are being compared. This is not useful except for within states, with the ``obfuscate_templates`` option set to ``True``. .. versionadded:: 2018.3.0 source_hash_file1 If ``file1`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 source_hash_file2 If ``file2`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 CLI Examples: .. code-block:: bash salt '*' file.get_diff /home/fred/.vimrc salt://users/fred/.vimrc salt '*' file.get_diff /tmp/foo.txt /tmp/bar.txt ''' files = (file1, file2) source_hashes = (source_hash_file1, source_hash_file2) paths = [] errors = [] for filename, source_hash in zip(files, source_hashes): try: # Local file paths will just return the same path back when passed # to cp.cache_file. cached_path = __salt__['cp.cache_file'](filename, saltenv, source_hash=source_hash) if cached_path is False: errors.append( 'File {0} not found'.format( salt.utils.stringutils.to_unicode(filename) ) ) continue paths.append(cached_path) except MinionError as exc: errors.append(salt.utils.stringutils.to_unicode(exc.__str__())) continue if errors: raise CommandExecutionError( 'Failed to cache one or more files', info=errors ) args = [] for filename in paths: try: with salt.utils.files.fopen(filename, 'rb') as fp_: args.append(fp_.readlines()) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read {0}: {1}'.format( salt.utils.stringutils.to_unicode(filename), exc.strerror ) ) if args[0] != args[1]: if template and __salt__['config.option']('obfuscate_templates'): ret = '<Obfuscated Template>' elif not show_changes: ret = '<show_changes=False>' else: bdiff = _binary_replace(*paths) # pylint: disable=no-value-for-parameter if bdiff: ret = bdiff else: if show_filenames: args.extend(paths) ret = __utils__['stringutils.get_diff'](*args) return ret return '' def manage_file(name, sfn, ret, source, source_sum, user, group, mode, attrs, saltenv, backup, makedirs=False, template=None, # pylint: disable=W0613 show_changes=True, contents=None, dir_mode=None, follow_symlinks=True, skip_verify=False, keep_mode=False, encoding=None, encoding_errors='strict', seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Checks the destination against what was retrieved with get_managed and makes the appropriate modifications (if necessary). name location to place the file sfn location of cached file on the minion This is the path to the file stored on the minion. This file is placed on the minion using cp.cache_file. If the hash sum of that file matches the source_sum, we do not transfer the file to the minion again. This file is then grabbed and if it has template set, it renders the file to be placed into the correct place on the system using salt.files.utils.copyfile() ret The initial state return data structure. Pass in ``None`` to use the default structure. source file reference on the master source_sum sum hash for source user user owner group group owner backup backup_mode attrs attributes to be set on file: '' means remove all of them .. versionadded:: 2018.3.0 makedirs make directories if they do not exist template format of templating show_changes Include diff in state return contents: contents to be placed in the file dir_mode mode for directories created with makedirs skip_verify : False If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 keep_mode : False If ``True``, and the ``source`` is a file from the Salt fileserver (or a local file on the minion), the mode of the destination file will be set to the mode of the source file. .. note:: keep_mode does not work with salt-ssh. As a consequence of how the files are transferred to the minion, and the inability to connect back to the master with salt-ssh, salt is unable to stat the file as it exists on the fileserver and thus cannot mirror the mode on the salt-ssh minion encoding If specified, then the specified encoding will be used. Otherwise, the file will be encoded using the system locale (usually UTF-8). See https://docs.python.org/3/library/codecs.html#standard-encodings for the list of available encodings. .. versionadded:: 2017.7.0 encoding_errors : 'strict' Default is ```'strict'```. See https://docs.python.org/2/library/codecs.html#codec-base-classes for the error handling schemes. .. versionadded:: 2017.7.0 seuser selinux user attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon CLI Example: .. code-block:: bash salt '*' file.manage_file /etc/httpd/conf.d/httpd.conf '' '{}' salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' '' base '' .. versionchanged:: 2014.7.0 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if source: if not sfn: # File is not present, cache it sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) htype = source_sum.get('hash_type', __opts__['hash_type']) # Recalculate source sum now that file has been cached source_sum = { 'hash_type': htype, 'hsum': get_hash(sfn, form=htype) } if keep_mode: if _urlparse(source).scheme in ('salt', 'file', ''): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) # Check changes if the target file exists if os.path.isfile(name) or os.path.islink(name): if os.path.islink(name) and follow_symlinks: real_name = os.path.realpath(name) else: real_name = name # Only test the checksums on files with managed contents if source and not (not follow_symlinks and os.path.islink(real_name)): name_sum = get_hash(real_name, source_sum.get('hash_type', __opts__['hash_type'])) else: name_sum = None # Check if file needs to be replaced if source and (name_sum is None or source_sum.get('hsum', __opts__['hash_type']) != name_sum): if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server or local # source, and we are not skipping checksum verification, then # verify that it matches the specified checksum. if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3}). If the \'source_hash\' value ' 'refers to a remote file with multiple possible ' 'matches, then it may be necessary to set ' '\'source_hash_name\'.'.format( source_sum['hash_type'], source, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # Print a diff equivalent to diff -u old new if __salt__['config.option']('obfuscate_templates'): ret['changes']['diff'] = '<Obfuscated Template>' elif not show_changes: ret['changes']['diff'] = '<show_changes=False>' else: try: ret['changes']['diff'] = get_diff( real_name, sfn, show_filenames=False) except CommandExecutionError as exc: ret['changes']['diff'] = exc.strerror # Pre requisites are met, and the file needs to be replaced, do it try: salt.utils.files.copyfile(sfn, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) try: differences = get_diff( real_name, tmp, show_filenames=False, show_changes=show_changes, template=True) except CommandExecutionError as exc: ret.setdefault('warnings', []).append( 'Failed to detect changes to file: {0}'.format(exc.strerror) ) differences = '' if differences: ret['changes']['diff'] = differences # Pre requisites are met, the file needs to be replaced, do it try: salt.utils.files.copyfile(tmp, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(tmp) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) __clean_tmp(tmp) # Check for changing symlink to regular file here if os.path.islink(name) and not follow_symlinks: if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret try: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) ret['changes']['diff'] = \ 'Replace symbolic link with regular file' if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, follow_symlinks, seuser=seuser, serole=serole, setype=setype, serange=serange) if ret['changes']: ret['comment'] = 'File {0} updated'.format( salt.utils.data.decode(name) ) elif not ret['changes'] and ret['result']: ret['comment'] = 'File {0} is in the correct state'.format( salt.utils.data.decode(name) ) if sfn: __clean_tmp(sfn) return ret else: # target file does not exist contain_dir = os.path.dirname(name) def _set_mode_and_make_dirs(name, dir_mode, mode, user, group): # check for existence of windows drive letter if salt.utils.platform.is_windows(): drive, _ = os.path.splitdrive(name) if drive and not os.path.exists(drive): __clean_tmp(sfn) return _error(ret, '{0} drive not present'.format(drive)) if dir_mode is None and mode is not None: # Add execute bit to each nonzero digit in the mode, if # dir_mode was not specified. Otherwise, any # directories created with makedirs_() below can't be # listed via a shell. mode_list = [x for x in six.text_type(mode)][-3:] for idx in range(len(mode_list)): if mode_list[idx] != '0': mode_list[idx] = six.text_type(int(mode_list[idx]) | 1) dir_mode = ''.join(mode_list) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 makedirs_( path=name, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: makedirs_(name, user=user, group=group, mode=dir_mode) if source: # Apply the new file if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # It is a new file, set the diff accordingly ret['changes']['diff'] = 'New file' if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') else: # source != True if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') # Create the file, user rw-only if mode will be set to prevent # a small security race problem before the permissions are set with salt.utils.files.set_umask(0o077 if mode else None): # Create a new file when test is False and source is None if contents is None: if not __opts__['test']: if touch(name): ret['changes']['new'] = 'file {0} created'.format(name) ret['comment'] = 'Empty file' else: return _error( ret, 'Empty file {0} not created'.format(name) ) else: if not __opts__['test']: if touch(name): ret['changes']['diff'] = 'New file' else: return _error( ret, 'File {0} not created'.format(name) ) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) # Copy into place salt.utils.files.copyfile(tmp, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(tmp) # Now copy the file contents if there is a source file elif sfn: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(sfn) # This is a new file, if no mode specified, use the umask to figure # out what mode to use for the new file. if mode is None and not salt.utils.platform.is_windows(): # Get current umask mask = salt.utils.files.get_umask() # Calculate the mode value that results from the umask mode = oct((0o777 ^ mask) & 0o666) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, seuser=seuser, serole=serole, setype=setype, serange=serange) if not ret['comment']: ret['comment'] = 'File ' + name + ' updated' if __opts__['test']: ret['comment'] = 'File ' + name + ' not updated' elif not ret['changes'] and ret['result']: ret['comment'] = 'File ' + name + ' is in the correct state' if sfn: __clean_tmp(sfn) return ret def mkdir(dir_path, user=None, group=None, mode=None): ''' Ensure that a directory is available. CLI Example: .. code-block:: bash salt '*' file.mkdir /opt/jetty/context ''' dir_path = os.path.expanduser(dir_path) directory = os.path.normpath(dir_path) if not os.path.isdir(directory): # If a caller such as managed() is invoked with makedirs=True, make # sure that any created dirs are created with the same user and group # to follow the principal of least surprise method. makedirs_perms(directory, user, group, mode) return True def makedirs_(path, user=None, group=None, mode=None): ''' Ensure that the directory containing this path is available. .. note:: The path must end with a trailing slash otherwise the directory/directories will be created up to the parent directory. For example if path is ``/opt/code``, then it would be treated as ``/opt/`` but if the path ends with a trailing slash like ``/opt/code/``, then it would be treated as ``/opt/code/``. CLI Example: .. code-block:: bash salt '*' file.makedirs /opt/code/ ''' path = os.path.expanduser(path) if mode: mode = salt.utils.files.normalize_mode(mode) # walk up the directory structure until we find the first existing # directory dirname = os.path.normpath(os.path.dirname(path)) if os.path.isdir(dirname): # There's nothing for us to do msg = 'Directory \'{0}\' already exists'.format(dirname) log.debug(msg) return msg if os.path.exists(dirname): msg = 'The path \'{0}\' already exists and is not a directory'.format( dirname ) log.debug(msg) return msg directories_to_create = [] while True: if os.path.isdir(dirname): break directories_to_create.append(dirname) current_dirname = dirname dirname = os.path.dirname(dirname) if current_dirname == dirname: raise SaltInvocationError( 'Recursive creation for path \'{0}\' would result in an ' 'infinite loop. Please use an absolute path.'.format(dirname) ) # create parent directories from the topmost to the most deeply nested one directories_to_create.reverse() for directory_to_create in directories_to_create: # all directories have the user, group and mode set!! log.debug('Creating directory: %s', directory_to_create) mkdir(directory_to_create, user=user, group=group, mode=mode) def makedirs_perms(name, user=None, group=None, mode='0755'): ''' Taken and modified from os.makedirs to set user, group and mode for each directory created. CLI Example: .. code-block:: bash salt '*' file.makedirs_perms /opt/code ''' name = os.path.expanduser(name) path = os.path head, tail = path.split(name) if not tail: head, tail = path.split(head) if head and tail and not path.exists(head): try: makedirs_perms(head, user, group, mode) except OSError as exc: # be happy if someone already created the path if exc.errno != errno.EEXIST: raise if tail == os.curdir: # xxx/newdir/. exists if xxx/newdir exists return os.mkdir(name) check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) def get_devmm(name): ''' Get major/minor info from a device CLI Example: .. code-block:: bash salt '*' file.get_devmm /dev/chr ''' name = os.path.expanduser(name) if is_chrdev(name) or is_blkdev(name): stat_structure = os.stat(name) return ( os.major(stat_structure.st_rdev), os.minor(stat_structure.st_rdev)) else: return (0, 0) def is_chrdev(name): ''' Check if a file exists and is a character device. CLI Example: .. code-block:: bash salt '*' file.is_chrdev /dev/chr ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the character device does not exist in the first place return False else: raise return stat.S_ISCHR(stat_structure.st_mode) def mknod_chrdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a character device. CLI Example: .. code-block:: bash salt '*' file.mknod_chrdev /dev/chr 180 31 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating character device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFCHR, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created character device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_blkdev(name): ''' Check if a file exists and is a block device. CLI Example: .. code-block:: bash salt '*' file.is_blkdev /dev/blk ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the block device does not exist in the first place return False else: raise return stat.S_ISBLK(stat_structure.st_mode) def mknod_blkdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a block device. CLI Example: .. code-block:: bash salt '*' file.mknod_blkdev /dev/blk 8 999 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating block device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFBLK, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created block device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_fifo(name): ''' Check if a file exists and is a FIFO. CLI Example: .. code-block:: bash salt '*' file.is_fifo /dev/fifo ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the fifo does not exist in the first place return False else: raise return stat.S_ISFIFO(stat_structure.st_mode) def mknod_fifo(name, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a FIFO pipe. CLI Example: .. code-block:: bash salt '*' file.mknod_fifo /dev/fifo ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating FIFO name: %s', name) try: if __opts__['test']: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = None else: if os.mkfifo(name, int(six.text_type(mode).lstrip('0Oo'), 8)) is None: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created fifo check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def mknod(name, ntype, major=0, minor=0, user=None, group=None, mode='0600'): ''' .. versionadded:: 0.17.0 Create a block device, character device, or fifo pipe. Identical to the gnu mknod. CLI Examples: .. code-block:: bash salt '*' file.mknod /dev/chr c 180 31 salt '*' file.mknod /dev/blk b 8 999 salt '*' file.nknod /dev/fifo p ''' ret = False makedirs_(name, user, group) if ntype == 'c': ret = mknod_chrdev(name, major, minor, user, group, mode) elif ntype == 'b': ret = mknod_blkdev(name, major, minor, user, group, mode) elif ntype == 'p': ret = mknod_fifo(name, user, group, mode) else: raise SaltInvocationError( 'Node type unavailable: \'{0}\'. Available node types are ' 'character (\'c\'), block (\'b\'), and pipe (\'p\').'.format(ntype) ) return ret def list_backups(path, limit=None): ''' .. versionadded:: 0.17.0 Lists the previous versions of a file backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups /foo/bar/baz.txt ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows src_dir = parent_dir.replace(':', '_') else: src_dir = parent_dir[1:] # Figure out full path of location of backup file in minion cache bkdir = os.path.join(bkroot, src_dir) if not os.path.isdir(bkdir): return {} files = {} for fname in [x for x in os.listdir(bkdir) if os.path.isfile(os.path.join(bkdir, x))]: if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows strpfmt = '{0}_%a_%b_%d_%H-%M-%S_%f_%Y'.format(basename) else: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(fname, strpfmt) except ValueError: # File didn't match the strp format string, so it's not a backup # for this file. Move on to the next one. continue if salt.utils.platform.is_windows(): str_format = '%a %b %d %Y %H-%M-%S.%f' else: str_format = '%a %b %d %Y %H:%M:%S.%f' files.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime(str_format) location = os.path.join(bkdir, fname) files[timestamp]['Size'] = os.stat(location).st_size files[timestamp]['Location'] = location return dict(list(zip( list(range(len(files))), [files[x] for x in sorted(files, reverse=True)[:limit]] ))) list_backup = salt.utils.functools.alias_function(list_backups, 'list_backup') def list_backups_dir(path, limit=None): ''' Lists the previous versions of a directory backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The directory on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups_dir /foo/bar/baz/ ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups_dir: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) # Figure out full path of location of backup folder in minion cache bkdir = os.path.join(bkroot, parent_dir[1:]) if not os.path.isdir(bkdir): return {} files = {} f = dict([(i, len(list(n))) for i, n in itertools.groupby([x.split("_")[0] for x in sorted(os.listdir(bkdir))])]) ff = os.listdir(bkdir) for i, n in six.iteritems(f): ssfile = {} for x in sorted(ff): basename = x.split('_')[0] if i == basename: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(x, strpfmt) except ValueError: # Folder didn't match the strp format string, so it's not a backup # for this folder. Move on to the next one. continue ssfile.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime('%a %b %d %Y %H:%M:%S.%f') location = os.path.join(bkdir, x) ssfile[timestamp]['Size'] = os.stat(location).st_size ssfile[timestamp]['Location'] = location sfiles = dict(list(zip(list(range(n)), [ssfile[x] for x in sorted(ssfile, reverse=True)[:limit]]))) sefiles = {i: sfiles} files.update(sefiles) return files def restore_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Restore a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to restore, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.restore_backup /foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) # Note: This only supports minion backups, so this function will need to be # modified if/when master backups are implemented. ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret salt.utils.files.backup_minion(path, _get_bkroot()) try: shutil.copyfile(backup['Location'], path) except IOError as exc: ret['comment'] = \ 'Unable to restore {0} to {1}: ' \ '{2}'.format(backup['Location'], path, exc) return ret else: ret['result'] = True ret['comment'] = 'Successfully restored {0} to ' \ '{1}'.format(backup['Location'], path) # Try to set proper ownership if not salt.utils.platform.is_windows(): try: fstat = os.stat(path) except (OSError, IOError): ret['comment'] += ', but was unable to set ownership' else: os.chown(path, fstat.st_uid, fstat.st_gid) return ret def delete_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Delete a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to delete, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.delete_backup /var/cache/salt/minion/file_backup/home/foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret try: os.remove(backup['Location']) except IOError as exc: ret['comment'] = 'Unable to remove {0}: {1}'.format(backup['Location'], exc) else: ret['result'] = True ret['comment'] = 'Successfully removed {0}'.format(backup['Location']) return ret remove_backup = salt.utils.functools.alias_function(delete_backup, 'remove_backup') def grep(path, pattern, *opts): ''' Grep for a string in the specified file .. note:: This function's return value is slated for refinement in future versions of Salt path Path to the file to be searched .. note:: Globbing is supported (i.e. ``/var/log/foo/*.log``, but if globbing is being used then the path should be quoted to keep the shell from attempting to expand the glob expression. pattern Pattern to match. For example: ``test``, or ``a[0-5]`` opts Additional command-line flags to pass to the grep command. For example: ``-v``, or ``-i -B2`` .. note:: The options should come after a double-dash (as shown in the examples below) to keep Salt's own argument parser from interpreting them. CLI Example: .. code-block:: bash salt '*' file.grep /etc/passwd nobody salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i -B2 salt '*' file.grep "/etc/sysconfig/network-scripts/*" ipaddr -- -i -l ''' path = os.path.expanduser(path) # Backup the path in case the glob returns nothing _path = path path = glob.glob(path) # If the list is empty no files exist # so we revert back to the original path # so the result is an error. if not path: path = _path split_opts = [] for opt in opts: try: split = salt.utils.args.shlex_split(opt) except AttributeError: split = salt.utils.args.shlex_split(six.text_type(opt)) if len(split) > 1: raise SaltInvocationError( 'Passing multiple command line arguments in a single string ' 'is not supported, please pass the following arguments ' 'separately: {0}'.format(opt) ) split_opts.extend(split) if isinstance(path, list): cmd = ['grep'] + split_opts + [pattern] + path else: cmd = ['grep'] + split_opts + [pattern, path] try: ret = __salt__['cmd.run_all'](cmd, python_shell=False) except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return ret def open_files(by_pid=False): ''' Return a list of all physical open files on the system. CLI Examples: .. code-block:: bash salt '*' file.open_files salt '*' file.open_files by_pid=True ''' # First we collect valid PIDs pids = {} procfs = os.listdir('/proc/') for pfile in procfs: try: pids[int(pfile)] = [] except ValueError: # Not a valid PID, move on pass # Then we look at the open files for each PID files = {} for pid in pids: ppath = '/proc/{0}'.format(pid) try: tids = os.listdir('{0}/task'.format(ppath)) except OSError: continue # Collect the names of all of the file descriptors fd_ = [] #try: # fd_.append(os.path.realpath('{0}/task/{1}exe'.format(ppath, tid))) #except Exception: # pass for fpath in os.listdir('{0}/fd'.format(ppath)): fd_.append('{0}/fd/{1}'.format(ppath, fpath)) for tid in tids: try: fd_.append( os.path.realpath('{0}/task/{1}/exe'.format(ppath, tid)) ) except OSError: continue for tpath in os.listdir('{0}/task/{1}/fd'.format(ppath, tid)): fd_.append('{0}/task/{1}/fd/{2}'.format(ppath, tid, tpath)) fd_ = sorted(set(fd_)) # Loop through file descriptors and return useful data for each file for fdpath in fd_: # Sometimes PIDs and TIDs disappear before we can query them try: name = os.path.realpath(fdpath) # Running stat on the file cuts out all of the sockets and # deleted files from the list os.stat(name) except OSError: continue if name not in files: files[name] = [pid] else: # We still want to know which PIDs are using each file files[name].append(pid) files[name] = sorted(set(files[name])) pids[pid].append(name) pids[pid] = sorted(set(pids[pid])) if by_pid: return pids return files def pardir(): ''' Return the relative parent directory path symbol for underlying OS .. versionadded:: 2014.7.0 This can be useful when constructing Salt Formulas. .. code-block:: jinja {% set pardir = salt['file.pardir']() %} {% set final_path = salt['file.join']('subdir', pardir, 'confdir') %} CLI Example: .. code-block:: bash salt '*' file.pardir ''' return os.path.pardir def normpath(path): ''' Returns Normalize path, eliminating double slashes, etc. .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.normpath'](tpldir + '/../vars.jinja') import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.normpath 'a/b/c/..' ''' return os.path.normpath(path) def basename(path): ''' Returns the final component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- set filename = salt['file.basename'](source_file) %} CLI Example: .. code-block:: bash salt '*' file.basename 'test/test.config' ''' return os.path.basename(path) def dirname(path): ''' Returns the directory component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.dirname'](tpldir) + '/vars.jinja' import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.dirname 'test/path/filename.config' ''' return os.path.dirname(path) def join(*args): ''' Return a normalized file system path for the underlying OS .. versionadded:: 2014.7.0 This can be useful at the CLI but is frequently useful when scripting combining path variables: .. code-block:: jinja {% set www_root = '/var' %} {% set app_dir = 'myapp' %} myapp_config: file: - managed - name: {{ salt['file.join'](www_root, app_dir, 'config.yaml') }} CLI Example: .. code-block:: bash salt '*' file.join '/' 'usr' 'local' 'bin' ''' return os.path.join(*args) def move(src, dst): ''' Move a file or directory CLI Example: .. code-block:: bash salt '*' file.move /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('Source path must be absolute.') if not os.path.isabs(dst): raise SaltInvocationError('Destination path must be absolute.') ret = { 'result': True, 'comment': "'{0}' moved to '{1}'".format(src, dst), } try: shutil.move(src, dst) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move '{0}' to '{1}': {2}".format(src, dst, exc) ) return ret def diskusage(path): ''' Recursively calculate disk usage of path and return it in bytes CLI Example: .. code-block:: bash salt '*' file.diskusage /path/to/check ''' total_size = 0 seen = set() if os.path.isfile(path): stat_structure = os.stat(path) ret = stat_structure.st_size return ret for dirpath, dirnames, filenames in salt.utils.path.os_walk(path): for f in filenames: fp = os.path.join(dirpath, f) try: stat_structure = os.stat(fp) except OSError: continue if stat_structure.st_ino in seen: continue seen.add(stat_structure.st_ino) total_size += stat_structure.st_size ret = total_size return ret
saltstack/salt
salt/modules/file.py
get_gid
python
def get_gid(path, follow_symlinks=True): ''' Return the id of the group that owns a given file path file or directory of which to get the gid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_gid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('gid', -1)
Return the id of the group that owns a given file path file or directory of which to get the gid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_gid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L215-L235
[ "def stats(path, hash_type=None, follow_symlinks=True):\n '''\n Return a dict containing the stats for a given file\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' file.stats /etc/passwd\n '''\n path = os.path.expanduser(path)\n\n ret = {}\n if not os.path.exists(path):\n try:\n # Broken symlinks will return False for os.path.exists(), but still\n # have a uid and gid\n pstat = os.lstat(path)\n except OSError:\n # Not a broken symlink, just a nonexistent path\n # NOTE: The file.directory state checks the content of the error\n # message in this exception. Any changes made to the message for this\n # exception will reflect the file.directory state as well, and will\n # likely require changes there.\n raise CommandExecutionError('Path not found: {0}'.format(path))\n else:\n if follow_symlinks:\n pstat = os.stat(path)\n else:\n pstat = os.lstat(path)\n ret['inode'] = pstat.st_ino\n ret['uid'] = pstat.st_uid\n ret['gid'] = pstat.st_gid\n ret['group'] = gid_to_group(pstat.st_gid)\n ret['user'] = uid_to_user(pstat.st_uid)\n ret['atime'] = pstat.st_atime\n ret['mtime'] = pstat.st_mtime\n ret['ctime'] = pstat.st_ctime\n ret['size'] = pstat.st_size\n ret['mode'] = six.text_type(oct(stat.S_IMODE(pstat.st_mode)))\n if hash_type:\n ret['sum'] = get_hash(path, hash_type)\n ret['type'] = 'file'\n if stat.S_ISDIR(pstat.st_mode):\n ret['type'] = 'dir'\n if stat.S_ISCHR(pstat.st_mode):\n ret['type'] = 'char'\n if stat.S_ISBLK(pstat.st_mode):\n ret['type'] = 'block'\n if stat.S_ISREG(pstat.st_mode):\n ret['type'] = 'file'\n if stat.S_ISLNK(pstat.st_mode):\n ret['type'] = 'link'\n if stat.S_ISFIFO(pstat.st_mode):\n ret['type'] = 'pipe'\n if stat.S_ISSOCK(pstat.st_mode):\n ret['type'] = 'socket'\n ret['target'] = os.path.realpath(path)\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage information about regular files, directories, and special files on the minion, set/read user, group, mode, and data ''' # TODO: We should add the capability to do u+r type operations here # some time in the future from __future__ import absolute_import, print_function, unicode_literals # Import python libs import datetime import errno import fnmatch import io import itertools import logging import operator import os import re import shutil import stat import string import sys import tempfile import time import glob import hashlib import mmap from collections import Iterable, Mapping from functools import reduce # pylint: disable=redefined-builtin # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range, zip from salt.ext.six.moves.urllib.parse import urlparse as _urlparse # pylint: enable=import-error,no-name-in-module,redefined-builtin try: import grp import pwd except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.atomicfile import salt.utils.data import salt.utils.dictupdate import salt.utils.filebuffer import salt.utils.files import salt.utils.find import salt.utils.functools import salt.utils.hashutils import salt.utils.itertools import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.templates import salt.utils.url import salt.utils.user from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError, get_error_message as _get_error_message from salt.utils.files import HASHES, HASHES_REVMAP log = logging.getLogger(__name__) __func_alias__ = { 'makedirs_': 'makedirs' } def __virtual__(): ''' Only work on POSIX-like systems ''' # win_file takes care of windows if salt.utils.platform.is_windows(): return ( False, 'The file execution module cannot be loaded: only available on ' 'non-Windows systems - use win_file instead.' ) return True def __clean_tmp(sfn): ''' Clean out a template temp file ''' if sfn.startswith(os.path.join(tempfile.gettempdir(), salt.utils.files.TEMPFILE_PREFIX)): # Don't remove if it exists in file_roots (any saltenv) all_roots = itertools.chain.from_iterable( six.itervalues(__opts__['file_roots'])) in_roots = any(sfn.startswith(root) for root in all_roots) # Only clean up files that exist if os.path.exists(sfn) and not in_roots: os.remove(sfn) def _error(ret, err_msg): ''' Common function for setting error information for return dicts ''' ret['result'] = False ret['comment'] = err_msg return ret def _binary_replace(old, new): ''' This function does NOT do any diffing, it just checks the old and new files to see if either is binary, and provides an appropriate string noting the difference between the two files. If neither file is binary, an empty string is returned. This function should only be run AFTER it has been determined that the files differ. ''' old_isbin = not __utils__['files.is_text'](old) new_isbin = not __utils__['files.is_text'](new) if any((old_isbin, new_isbin)): if all((old_isbin, new_isbin)): return 'Replace binary file' elif old_isbin: return 'Replace binary file with text file' elif new_isbin: return 'Replace text file with binary file' return '' def _get_bkroot(): ''' Get the location of the backup dir in the minion cache ''' # Get the cachedir from the minion config return os.path.join(__salt__['config.get']('cachedir'), 'file_backup') def _splitlines_preserving_trailing_newline(str): ''' Returns a list of the lines in the string, breaking at line boundaries and preserving a trailing newline (if present). Essentially, this works like ``str.striplines(False)`` but preserves an empty line at the end. This is equivalent to the following code: .. code-block:: python lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') ''' lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') return lines def gid_to_group(gid): ''' Convert the group id to the group name on this system gid gid to convert to a group name CLI Example: .. code-block:: bash salt '*' file.gid_to_group 0 ''' try: gid = int(gid) except ValueError: # This is not an integer, maybe it's already the group name? gid = group_to_gid(gid) if gid == '': # Don't even bother to feed it to grp return '' try: return grp.getgrgid(gid).gr_name except (KeyError, NameError): # If group is not present, fall back to the gid. return gid def group_to_gid(group): ''' Convert the group to the gid on this system group group to convert to its gid CLI Example: .. code-block:: bash salt '*' file.group_to_gid root ''' if group is None: return '' try: if isinstance(group, int): return group return grp.getgrnam(group).gr_gid except KeyError: return '' def get_group(path, follow_symlinks=True): ''' Return the group that owns a given file path file or directory of which to get the group follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_group /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('group', False) def uid_to_user(uid): ''' Convert a uid to a user name uid uid to convert to a username CLI Example: .. code-block:: bash salt '*' file.uid_to_user 0 ''' try: return pwd.getpwuid(uid).pw_name except (KeyError, NameError): # If user is not present, fall back to the uid. return uid def user_to_uid(user): ''' Convert user name to a uid user user name to convert to its uid CLI Example: .. code-block:: bash salt '*' file.user_to_uid root ''' if user is None: user = salt.utils.user.get_user() try: if isinstance(user, int): return user return pwd.getpwnam(user).pw_uid except KeyError: return '' def get_uid(path, follow_symlinks=True): ''' Return the id of the user that owns a given file path file or directory of which to get the uid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_uid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('uid', -1) def get_user(path, follow_symlinks=True): ''' Return the user that owns a given file path file or directory of which to get the user follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_user /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('user', False) def get_mode(path, follow_symlinks=True): ''' Return the mode of a file path file or directory of which to get the mode follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_mode /etc/passwd .. versionchanged:: 2014.1.0 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('mode', '') def set_mode(path, mode): ''' Set the mode of a file path file or directory of which to set the mode mode mode to set the path to CLI Example: .. code-block:: bash salt '*' file.set_mode /etc/passwd 0644 ''' path = os.path.expanduser(path) mode = six.text_type(mode).lstrip('0Oo') if not mode: mode = '0' if not os.path.exists(path): raise CommandExecutionError('{0}: File not found'.format(path)) try: os.chmod(path, int(mode, 8)) except Exception: return 'Invalid Mode ' + mode return get_mode(path) def lchown(path, user, group): ''' Chown a file, pass the file the desired user and group without following symlinks. path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 return os.lchown(path, uid, gid) def chown(path, user, group): ''' Chown a file, pass the file the desired user and group path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 if not os.path.exists(path): try: # Broken symlinks will return false, but still need to be chowned return os.lchown(path, uid, gid) except OSError: pass err += 'File not found' if err: return err return os.chown(path, uid, gid) def chgrp(path, group): ''' Change the group of a file path path to the file or directory group group owner CLI Example: .. code-block:: bash salt '*' file.chgrp /etc/passwd root ''' path = os.path.expanduser(path) user = get_user(path) return chown(path, user, group) def _cmp_attrs(path, attrs): ''' .. versionadded:: 2018.3.0 Compare attributes of a given file to given attributes. Returns a pair (list) where first item are attributes to add and second item are to be removed. Please take into account when using this function that some minions will not have lsattr installed. path path to file to compare attributes with. attrs string of attributes to compare against a given file ''' diff = [None, None] # lsattr for AIX is not the same thing as lsattr for linux. if salt.utils.platform.is_aix(): return None try: lattrs = lsattr(path).get(path, '') except AttributeError: # lsattr not installed return None old = [chr for chr in lattrs if chr not in attrs] if old: diff[1] = ''.join(old) new = [chr for chr in attrs if chr not in lattrs] if new: diff[0] = ''.join(new) return diff def lsattr(path): ''' .. versionadded:: 2018.3.0 .. versionchanged:: 2018.3.1 If ``lsattr`` is not installed on the system, ``None`` is returned. .. versionchanged:: 2018.3.4 If on ``AIX``, ``None`` is returned even if in filesystem as lsattr on ``AIX`` is not the same thing as the linux version. Obtain the modifiable attributes of the given file. If path is to a directory, an empty list is returned. path path to file to obtain attributes of. File/directory must exist. CLI Example: .. code-block:: bash salt '*' file.lsattr foo1.txt ''' if not salt.utils.path.which('lsattr') or salt.utils.platform.is_aix(): return None if not os.path.exists(path): raise SaltInvocationError("File or directory does not exist: " + path) cmd = ['lsattr', path] result = __salt__['cmd.run'](cmd, ignore_retcode=True, python_shell=False) results = {} for line in result.splitlines(): if not line.startswith('lsattr: '): vals = line.split(None, 1) results[vals[1]] = re.findall(r"[aAcCdDeijPsStTu]", vals[0]) return results def chattr(*files, **kwargs): ''' .. versionadded:: 2018.3.0 Change the attributes of files. This function accepts one or more files and the following options: operator Can be wither ``add`` or ``remove``. Determines whether attributes should be added or removed from files attributes One or more of the following characters: ``aAcCdDeijPsStTu``, representing attributes to add to/remove from files version a version number to assign to the file(s) flags One or more of the following characters: ``RVf``, representing flags to assign to chattr (recurse, verbose, suppress most errors) CLI Example: .. code-block:: bash salt '*' file.chattr foo1.txt foo2.txt operator=add attributes=ai salt '*' file.chattr foo3.txt operator=remove attributes=i version=2 ''' operator = kwargs.pop('operator', None) attributes = kwargs.pop('attributes', None) flags = kwargs.pop('flags', None) version = kwargs.pop('version', None) if (operator is None) or (operator not in ('add', 'remove')): raise SaltInvocationError( "Need an operator: 'add' or 'remove' to modify attributes.") if attributes is None: raise SaltInvocationError("Need attributes: [aAcCdDeijPsStTu]") cmd = ['chattr'] if operator == "add": attrs = '+{0}'.format(attributes) elif operator == "remove": attrs = '-{0}'.format(attributes) cmd.append(attrs) if flags is not None: cmd.append('-{0}'.format(flags)) if version is not None: cmd.extend(['-v', version]) cmd.extend(files) result = __salt__['cmd.run'](cmd, python_shell=False) if bool(result): raise CommandExecutionError( "chattr failed to run, possibly due to bad parameters.") return True def get_sum(path, form='sha256'): ''' Return the checksum for the given file. The following checksum algorithms are supported: * md5 * sha1 * sha224 * sha256 **(default)** * sha384 * sha512 path path to the file or directory form desired sum format CLI Example: .. code-block:: bash salt '*' file.get_sum /etc/passwd sha512 ''' path = os.path.expanduser(path) if not os.path.isfile(path): return 'File not found' return salt.utils.hashutils.get_hash(path, form, 4096) def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` path path to the file or directory form desired sum format chunk_size amount to sum at once CLI Example: .. code-block:: bash salt '*' file.get_hash /etc/shadow ''' return salt.utils.hashutils.get_hash(os.path.expanduser(path), form, chunk_size) def get_source_sum(file_name='', source='', source_hash=None, source_hash_name=None, saltenv='base'): ''' .. versionadded:: 2016.11.0 Used by :py:func:`file.get_managed <salt.modules.file.get_managed>` to obtain the hash and hash type from the parameters specified below. file_name Optional file name being managed, for matching with :py:func:`file.extract_hash <salt.modules.file.extract_hash>`. source Source file, as used in :py:mod:`file <salt.states.file>` and other states. If ``source_hash`` refers to a file containing hashes, then this filename will be used to match a filename in that file. If the ``source_hash`` is a hash expression, then this argument will be ignored. source_hash Hash file/expression, as used in :py:mod:`file <salt.states.file>` and other states. If this value refers to a remote URL or absolute path to a local file, it will be cached and :py:func:`file.extract_hash <salt.modules.file.extract_hash>` will be used to obtain a hash from it. source_hash_name Specific file name to look for when ``source_hash`` refers to a remote file, used to disambiguate ambiguous matches. saltenv : base Salt fileserver environment from which to retrieve the source_hash. This value will only be used when ``source_hash`` refers to a file on the Salt fileserver (i.e. one beginning with ``salt://``). CLI Example: .. code-block:: bash salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=499ae16dcae71eeb7c3a30c75ea7a1a6 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 source_hash_name=./dir2/foo.tar.gz ''' def _invalid_source_hash_format(): ''' DRY helper for reporting invalid source_hash input ''' raise CommandExecutionError( 'Source hash {0} format is invalid. The supported formats are: ' '1) a hash, 2) an expression in the format <hash_type>=<hash>, or ' '3) either a path to a local file containing hashes, or a URI of ' 'a remote hash file. Supported protocols for remote hash files ' 'are: {1}. The hash may also not be of a valid length, the ' 'following are supported hash types and lengths: {2}.'.format( source_hash, ', '.join(salt.utils.files.VALID_PROTOS), ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) hash_fn = None if os.path.isabs(source_hash): hash_fn = source_hash else: try: proto = _urlparse(source_hash).scheme if proto in salt.utils.files.VALID_PROTOS: hash_fn = __salt__['cp.cache_file'](source_hash, saltenv) if not hash_fn: raise CommandExecutionError( 'Source hash file {0} not found'.format(source_hash) ) else: if proto != '': # Some unsupported protocol (e.g. foo://) is being used. # We'll get into this else block if a hash expression # (like md5=<md5 checksum here>), but in those cases, the # protocol will be an empty string, in which case we avoid # this error condition. _invalid_source_hash_format() except (AttributeError, TypeError): _invalid_source_hash_format() if hash_fn is not None: ret = extract_hash(hash_fn, '', file_name, source, source_hash_name) if ret is None: _invalid_source_hash_format() ret['hsum'] = ret['hsum'].lower() return ret else: # The source_hash is a hash expression ret = {} try: ret['hash_type'], ret['hsum'] = \ [x.strip() for x in source_hash.split('=', 1)] except AttributeError: _invalid_source_hash_format() except ValueError: # No hash type, try to figure out by hash length if not re.match('^[{0}]+$'.format(string.hexdigits), source_hash): _invalid_source_hash_format() ret['hsum'] = source_hash source_hash_len = len(source_hash) if source_hash_len in HASHES_REVMAP: ret['hash_type'] = HASHES_REVMAP[source_hash_len] else: _invalid_source_hash_format() if ret['hash_type'] not in HASHES: raise CommandExecutionError( 'Invalid hash type \'{0}\'. Supported hash types are: {1}. ' 'Either remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to a supported type.' .format(ret['hash_type'], ', '.join(HASHES), ret['hsum']) ) else: hsum_len = len(ret['hsum']) if hsum_len not in HASHES_REVMAP: _invalid_source_hash_format() elif hsum_len != HASHES[ret['hash_type']]: raise CommandExecutionError( 'Invalid length ({0}) for hash type \'{1}\'. Either ' 'remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to \'{3}\''.format( hsum_len, ret['hash_type'], ret['hsum'], HASHES_REVMAP[hsum_len], ) ) ret['hsum'] = ret['hsum'].lower() return ret def check_hash(path, file_hash): ''' Check if a file matches the given hash string Returns ``True`` if the hash matches, otherwise ``False``. path Path to a file local to the minion. hash The hash to check against the file specified in the ``path`` argument. .. versionchanged:: 2016.11.4 For this and newer versions the hash can be specified without an accompanying hash type (e.g. ``e138491e9d5b97023cea823fe17bac22``), but for earlier releases it is necessary to also specify the hash type in the format ``<hash_type>=<hash_value>`` (e.g. ``md5=e138491e9d5b97023cea823fe17bac22``). CLI Example: .. code-block:: bash salt '*' file.check_hash /etc/fstab e138491e9d5b97023cea823fe17bac22 salt '*' file.check_hash /etc/fstab md5=e138491e9d5b97023cea823fe17bac22 ''' path = os.path.expanduser(path) if not isinstance(file_hash, six.string_types): raise SaltInvocationError('hash must be a string') for sep in (':', '='): if sep in file_hash: hash_type, hash_value = file_hash.split(sep, 1) break else: hash_value = file_hash hash_len = len(file_hash) hash_type = HASHES_REVMAP.get(hash_len) if hash_type is None: raise SaltInvocationError( 'Hash {0} (length: {1}) could not be matched to a supported ' 'hash type. The supported hash types and lengths are: ' '{2}'.format( file_hash, hash_len, ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) return get_hash(path, hash_type) == hash_value def find(path, *args, **kwargs): ''' Approximate the Unix ``find(1)`` command and return a list of paths that meet the specified criteria. The options include match criteria: .. code-block:: text name = path-glob # case sensitive iname = path-glob # case insensitive regex = path-regex # case sensitive iregex = path-regex # case insensitive type = file-types # match any listed type user = users # match any listed user group = groups # match any listed group size = [+-]number[size-unit] # default unit = byte mtime = interval # modified since date grep = regex # search file contents and/or actions: .. code-block:: text delete [= file-types] # default type = 'f' exec = command [arg ...] # where {} is replaced by pathname print [= print-opts] and/or depth criteria: .. code-block:: text maxdepth = maximum depth to transverse in path mindepth = minimum depth to transverse before checking files or directories The default action is ``print=path`` ``path-glob``: .. code-block:: text * = match zero or more chars ? = match any char [abc] = match a, b, or c [!abc] or [^abc] = match anything except a, b, and c [x-y] = match chars x through y [!x-y] or [^x-y] = match anything except chars x through y {a,b,c} = match a or b or c ``path-regex``: a Python Regex (regular expression) pattern to match pathnames ``file-types``: a string of one or more of the following: .. code-block:: text a: all file types b: block device c: character device d: directory p: FIFO (named pipe) f: plain file l: symlink s: socket ``users``: a space and/or comma separated list of user names and/or uids ``groups``: a space and/or comma separated list of group names and/or gids ``size-unit``: .. code-block:: text b: bytes k: kilobytes m: megabytes g: gigabytes t: terabytes interval: .. code-block:: text [<num>w] [<num>d] [<num>h] [<num>m] [<num>s] where: w: week d: day h: hour m: minute s: second print-opts: a comma and/or space separated list of one or more of the following: .. code-block:: text group: group name md5: MD5 digest of file contents mode: file permissions (as integer) mtime: last modification time (as time_t) name: file basename path: file absolute path size: file size in bytes type: file type user: user name CLI Examples: .. code-block:: bash salt '*' file.find / type=f name=\\*.bak size=+10m salt '*' file.find /var mtime=+30d size=+10m print=path,size,mtime salt '*' file.find /var/log name=\\*.[0-9] mtime=+30d size=+10m delete ''' if 'delete' in args: kwargs['delete'] = 'f' elif 'print' in args: kwargs['print'] = 'path' try: finder = salt.utils.find.Finder(kwargs) except ValueError as ex: return 'error: {0}'.format(ex) ret = [item for i in [finder.find(p) for p in glob.glob(os.path.expanduser(path))] for item in i] ret.sort() return ret def _sed_esc(string, escape_all=False): ''' Escape single quotes and forward slashes ''' special_chars = "^.[$()|*+?{" string = string.replace("'", "'\"'\"'").replace("/", "\\/") if escape_all is True: for char in special_chars: string = string.replace(char, "\\" + char) return string def sed(path, before, after, limit='', backup='.bak', options='-r -e', flags='g', escape_all=False, negate_match=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup options : ``-r -e`` Options to pass to sed flags : ``g`` Flags to modify the sed search; e.g., ``i`` for case-insensitive pattern matching negate_match : False Negate the search command (``!``) .. versionadded:: 0.17.0 Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # path = os.path.expanduser(path) if not os.path.exists(path): return False # Mandate that before and after are strings before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.append('-i{0}'.format(backup) if backup else '-i') cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}{negate_match}s/{before}/{after}/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', negate_match='!' if negate_match else '', before=before, after=after, flags=flags ) ) cmd.append(path) return __salt__['cmd.run_all'](cmd, python_shell=False) def sed_contains(path, text, limit='', flags='g'): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the file at ``path`` contains ``text``. Utilizes sed to perform the search (line-wise search). Note: the ``p`` flag will be added to any flags you pass in. CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' # Largely inspired by Fabric's contrib.files.contains() path = os.path.expanduser(path) if not os.path.exists(path): return False before = _sed_esc(six.text_type(text), False) limit = _sed_esc(six.text_type(limit), False) options = '-n -r -e' if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}s/{before}/$/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', before=before, flags='p{0}'.format(flags) ) ) cmd.append(path) result = __salt__['cmd.run'](cmd, python_shell=False) return bool(result) def psed(path, before, after, limit='', backup='.bak', flags='gMS', escape_all=False, multi=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file (pure Python version) Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup flags : ``gMS`` Flags to modify the search. Valid values are: - ``g``: Replace all occurrences of the pattern, not just the first. - ``I``: Ignore case. - ``L``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\s`` and ``\\S`` dependent on the locale. - ``M``: Treat multiple lines as a single line. - ``S``: Make `.` match all characters, including newlines. - ``U``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\d``, ``\\D``, ``\\s`` and ``\\S`` dependent on Unicode. - ``X``: Verbose (whitespace is ignored). multi: ``False`` If True, treat the entire file as a single line Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # # Mandate that before and after are strings path = os.path.expanduser(path) multi = bool(multi) before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) # The pattern to replace with does not need to be escaped!!! # after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) shutil.copy2(path, '{0}{1}'.format(path, backup)) with salt.utils.files.fopen(path, 'w') as ofile: with salt.utils.files.fopen('{0}{1}'.format(path, backup), 'r') as ifile: if multi is True: for line in ifile.readline(): ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(line), before, after, limit, flags ) ) ) else: ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(ifile.read()), before, after, limit, flags ) ) ) RE_FLAG_TABLE = {'I': re.I, 'L': re.L, 'M': re.M, 'S': re.S, 'U': re.U, 'X': re.X} def _psed(text, before, after, limit, flags): ''' Does the actual work for file.psed, so that single lines can be passed in ''' atext = text if limit: limit = re.compile(limit) comps = text.split(limit) atext = ''.join(comps[1:]) count = 1 if 'g' in flags: count = 0 flags = flags.replace('g', '') aflags = 0 for flag in flags: aflags |= RE_FLAG_TABLE[flag] before = re.compile(before, flags=aflags) text = re.sub(before, after, atext, count=count) return text def uncomment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Uncomment specified commented lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be uncommented. This regex should not include the comment character. A leading ``^`` character will be stripped for convenience (for easily switching between comment() and uncomment()). char : ``#`` The character to remove in order to uncomment a line backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup CLI Example: .. code-block:: bash salt '*' file.uncomment /etc/hosts.deny 'ALL: PARANOID' ''' return comment_line(path=path, regex=regex, char=char, cmnt=False, backup=backup) def comment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Comment out specified lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be commented; this pattern will be wrapped in parenthesis and will move any preceding/trailing ``^`` or ``$`` characters outside the parenthesis (e.g., the pattern ``^foo$`` will be rewritten as ``^(foo)$``) char : ``#`` The character to be inserted at the beginning of a line in order to comment it out backup : ``.bak`` The file will be backed up before edit with this file extension .. warning:: This backup will be overwritten each time ``sed`` / ``comment`` / ``uncomment`` is called. Meaning the backup will only be useful after the first invocation. CLI Example: .. code-block:: bash salt '*' file.comment /etc/modules pcspkr ''' return comment_line(path=path, regex=regex, char=char, cmnt=True, backup=backup) def comment_line(path, regex, char='#', cmnt=True, backup='.bak'): r''' Comment or Uncomment a line in a text file. :param path: string The full path to the text file. :param regex: string A regex expression that begins with ``^`` that will find the line you wish to comment. Can be as simple as ``^color =`` :param char: string The character used to comment a line in the type of file you're referencing. Default is ``#`` :param cmnt: boolean True to comment the line. False to uncomment the line. Default is True. :param backup: string The file extension to give the backup file. Default is ``.bak`` Set to False/None to not keep a backup. :return: boolean Returns True if successful, False if not CLI Example: The following example will comment out the ``pcspkr`` line in the ``/etc/modules`` file using the default ``#`` character and create a backup file named ``modules.bak`` .. code-block:: bash salt '*' file.comment_line '/etc/modules' '^pcspkr' CLI Example: The following example will uncomment the ``log_level`` setting in ``minion`` config file if it is set to either ``warning``, ``info``, or ``debug`` using the ``#`` character and create a backup file named ``minion.bk`` .. code-block:: bash salt '*' file.comment_line 'C:\salt\conf\minion' '^log_level: (warning|info|debug)' '#' False '.bk' ''' # Get the regex for comment or uncomment if cmnt: regex = '{0}({1}){2}'.format( '^' if regex.startswith('^') else '', regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') else: regex = r'^{0}\s*({1}){2}'.format( char, regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') # Load the real path to the file path = os.path.realpath(os.path.expanduser(path)) # Make sure the file exists if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) # Make sure it is a text file if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}'.format(path)) # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes found = False # Dictionaries for comparing changes orig_file = [] new_file = [] # Buffer size for fopen bufsize = os.path.getsize(path) try: # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: # Is it in this line line = salt.utils.stringutils.to_unicode(line) if re.match(regex, line): # Load lines into dictionaries, set found to True orig_file.append(line) if cmnt: new_file.append('{0}{1}'.format(char, line)) else: new_file.append(line.lstrip(char)) found = True except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) # We've searched the whole file. If we didn't find anything, return False if not found: return False if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Create a copy to read from and to use as a backup later try: temp_file = _mkstemp_copy(path=path, preserve_inode=False) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) try: # Open the file in write mode mode = 'wb' if six.PY2 and salt.utils.platform.is_windows() else 'w' with salt.utils.files.fopen(path, mode=mode, buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: line = salt.utils.stringutils.to_unicode(line) try: # Is it in this line if re.match(regex, line): # Write the new line if cmnt: wline = '{0}{1}'.format(char, line) else: wline = line.lstrip(char) else: # Write the existing line (no change) wline = line wline = salt.utils.stringutils.to_bytes(wline) \ if six.PY2 and salt.utils.platform.is_windows() \ else salt.utils.stringutils.to_str(wline) w_file.write(wline) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if backup: # Move the backup file to the original directory backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: os.remove(temp_file) if not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) # Return a diff using the two dictionaries return __utils__['stringutils.get_diff'](orig_file, new_file) def _get_flags(flags): ''' Return an integer appropriate for use as a flag for the re module from a list of human-readable strings .. code-block:: python >>> _get_flags(['MULTILINE', 'IGNORECASE']) 10 >>> _get_flags('MULTILINE') 8 >>> _get_flags(2) 2 ''' if isinstance(flags, six.string_types): flags = [flags] if isinstance(flags, Iterable) and not isinstance(flags, Mapping): _flags_acc = [] for flag in flags: _flag = getattr(re, six.text_type(flag).upper()) if not isinstance(_flag, six.integer_types): raise SaltInvocationError( 'Invalid re flag given: {0}'.format(flag) ) _flags_acc.append(_flag) return reduce(operator.__or__, _flags_acc) elif isinstance(flags, six.integer_types): return flags else: raise SaltInvocationError( 'Invalid re flags: "{0}", must be given either as a single flag ' 'string, a list of strings, or as an integer'.format(flags) ) def _add_flags(flags, new_flags): ''' Combine ``flags`` and ``new_flags`` ''' flags = _get_flags(flags) new_flags = _get_flags(new_flags) return flags | new_flags def _mkstemp_copy(path, preserve_inode=True): ''' Create a temp file and move/copy the contents of ``path`` to the temp file. Return the path to the temp file. path The full path to the file whose contents will be moved/copied to a temp file. Whether it's moved or copied depends on the value of ``preserve_inode``. preserve_inode Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). Default is ``True``. ''' temp_file = None # Create the temp file try: temp_file = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to create temp file. " "Exception: {0}".format(exc) ) # use `copy` to preserve the inode of the # original file, and thus preserve hardlinks # to the inode. otherwise, use `move` to # preserve prior behavior, which results in # writing the file to a new inode. if preserve_inode: try: shutil.copy2(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to copy file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: try: shutil.move(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) return temp_file def _starts_till(src, probe, strip_comments=True): ''' Returns True if src and probe at least matches at the beginning till some point. ''' def _strip_comments(txt): ''' Strip possible comments. Usually comments are one or two symbols at the beginning of the line, separated with space ''' buff = txt.split(" ", 1) return len(buff) == 2 and len(buff[0]) < 2 and buff[1] or txt def _to_words(txt): ''' Split by words ''' return txt and [w for w in txt.strip().split(" ") if w.strip()] or txt no_match = -1 equal = 0 if not src or not probe: return no_match src = src.rstrip('\n\r') probe = probe.rstrip('\n\r') if src == probe: return equal src = _to_words(strip_comments and _strip_comments(src) or src) probe = _to_words(strip_comments and _strip_comments(probe) or probe) a_buff, b_buff = len(src) < len(probe) and (src, probe) or (probe, src) b_buff = ' '.join(b_buff) for idx in range(len(a_buff)): prb = ' '.join(a_buff[:-(idx + 1)]) if prb and b_buff.startswith(prb): return idx return no_match def _regex_to_static(src, regex): ''' Expand regular expression to static match. ''' if not src or not regex: return None try: compiled = re.compile(regex, re.DOTALL) src = [line for line in src if compiled.search(line) or line.count(regex)] except Exception as ex: raise CommandExecutionError("{0}: '{1}'".format(_get_error_message(ex), regex)) return src and src or [] def _assert_occurrence(probe, target, amount=1): ''' Raise an exception, if there are different amount of specified occurrences in src. ''' occ = len(probe) if occ > amount: msg = 'more than' elif occ < amount: msg = 'less than' elif not occ: msg = 'no' else: msg = None if msg: raise CommandExecutionError('Found {0} expected occurrences in "{1}" expression'.format(msg, target)) return occ def _set_line_indent(src, line, indent): ''' Indent the line with the source line. ''' if not indent: return line idt = [] for c in src: if c not in ['\t', ' ']: break idt.append(c) return ''.join(idt) + line.lstrip() def _get_eol(line): match = re.search('((?<!\r)\n|\r(?!\n)|\r\n)$', line) return match and match.group() or '' def _set_line_eol(src, line): ''' Add line ending ''' line_ending = _get_eol(src) or os.linesep return line.rstrip() + line_ending def _insert_line_before(idx, body, content, indent): if not idx or (idx and _starts_till(body[idx - 1], content) < 0): cnd = _set_line_indent(body[idx], content, indent) body.insert(idx, cnd) return body def _insert_line_after(idx, body, content, indent): # No duplicates or append, if "after" is the last line next_line = idx + 1 < len(body) and body[idx + 1] or None if next_line is None or _starts_till(next_line, content) < 0: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) return body def line(path, content=None, match=None, mode=None, location=None, before=None, after=None, show_changes=True, backup=False, quiet=False, indent=True): ''' .. versionadded:: 2015.8.0 Edit a line in the configuration file. The ``path`` and ``content`` arguments are required, as well as passing in one of the ``mode`` options. path Filesystem path to the file to be edited. content Content of the line. Allowed to be empty if mode=delete. match Match the target line for an action by a fragment of a string or regular expression. If neither ``before`` nor ``after`` are provided, and ``match`` is also ``None``, match becomes the ``content`` value. mode Defines how to edit a line. One of the following options is required: - ensure If line does not exist, it will be added. This is based on the ``content`` argument. - replace If line already exists, it will be replaced. - delete Delete the line, once found. - insert Insert a line. .. note:: If ``mode=insert`` is used, at least one of the following options must also be defined: ``location``, ``before``, or ``after``. If ``location`` is used, it takes precedence over the other two options. location Defines where to place content in the line. Note this option is only used when ``mode=insert`` is specified. If a location is passed in, it takes precedence over both the ``before`` and ``after`` kwargs. Valid locations are: - start Place the content at the beginning of the file. - end Place the content at the end of the file. before Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. after Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. show_changes Output a unified diff of the old file and the new file. If ``False`` return a boolean if any changes were made. Default is ``True`` .. note:: Using this option will store two copies of the file in-memory (the original version and the edited version) in order to generate the diff. backup Create a backup of the original file with the extension: "Year-Month-Day-Hour-Minutes-Seconds". quiet Do not raise any exceptions. E.g. ignore the fact that the file that is tried to be edited does not exist and nothing really happened. indent Keep indentation with the previous line. This option is not considered when the ``delete`` mode is specified. CLI Example: .. code-block:: bash salt '*' file.line /etc/nsswitch.conf "networks:\tfiles dns" after="hosts:.*?" mode='ensure' .. note:: If an equal sign (``=``) appears in an argument to a Salt command, it is interpreted as a keyword argument in the format of ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.line /path/to/file content="CREATEMAIL_SPOOL=no" match="CREATE_MAIL_SPOOL=yes" mode="replace" ''' path = os.path.realpath(os.path.expanduser(path)) if not os.path.isfile(path): if not quiet: raise CommandExecutionError('File "{0}" does not exists or is not a file.'.format(path)) return False # No changes had happened mode = mode and mode.lower() or mode if mode not in ['insert', 'ensure', 'delete', 'replace']: if mode is None: raise CommandExecutionError('Mode was not defined. How to process the file?') else: raise CommandExecutionError('Unknown mode: "{0}"'.format(mode)) # We've set the content to be empty in the function params but we want to make sure # it gets passed when needed. Feature #37092 empty_content_modes = ['delete'] if mode not in empty_content_modes and content is None: raise CommandExecutionError('Content can only be empty if mode is "{0}"'.format(', '.join(empty_content_modes))) del empty_content_modes # Before/after has privilege. If nothing defined, match is used by content. if before is None and after is None and not match: match = content with salt.utils.files.fopen(path, mode='r') as fp_: body = salt.utils.data.decode_list(fp_.readlines()) body_before = hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() # Add empty line at the end if last line ends with eol. # Allows simpler code if body and _get_eol(body[-1]): body.append('') after = _regex_to_static(body, after) before = _regex_to_static(body, before) match = _regex_to_static(body, match) if os.stat(path).st_size == 0 and mode in ('delete', 'replace'): log.warning('Cannot find text to %s. File \'%s\' is empty.', mode, path) body = [] elif mode == 'delete' and match: body = [line for line in body if line != match[0]] elif mode == 'replace' and match: idx = body.index(match[0]) file_line = body.pop(idx) body.insert(idx, _set_line_indent(file_line, content, indent)) elif mode == 'insert': if not location and not before and not after: raise CommandExecutionError('On insert must be defined either "location" or "before/after" conditions.') if not location: if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') out = [] in_range = False for line in body: if line == after[0]: in_range = True elif line == before[0] and in_range: cnd = _set_line_indent(line, content, indent) out.append(cnd) out.append(line) body = out if before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif after and not before: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: if location == 'start': if body: body.insert(0, _set_line_eol(body[0], content)) else: body.append(content + os.linesep) elif location == 'end': body.append(_set_line_indent(body[-1], content, indent) if body else content) elif mode == 'ensure': if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') is_there = bool([l for l in body if l.count(content)]) if not is_there: idx = body.index(after[0]) if idx < (len(body) - 1) and body[idx + 1] == before[0]: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) else: raise CommandExecutionError('Found more than one line between ' 'boundaries "before" and "after".') elif before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif not before and after: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: raise CommandExecutionError("Wrong conditions? " "Unable to ensure line without knowing " "where to put it before and/or after.") if body: for idx, line in enumerate(body): if not _get_eol(line) and idx+1 < len(body): prev = idx and idx-1 or 1 body[idx] = _set_line_eol(body[prev], line) # We do not need empty line at the end anymore if '' == body[-1]: body.pop() changed = body_before != hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() if backup and changed and __opts__['test'] is False: try: temp_file = _mkstemp_copy(path=path, preserve_inode=True) shutil.move(temp_file, '{0}.{1}'.format(path, time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime()))) except (OSError, IOError) as exc: raise CommandExecutionError("Unable to create the backup file of {0}. Exception: {1}".format(path, exc)) changes_diff = None if changed: if show_changes: with salt.utils.files.fopen(path, 'r') as fp_: path_content = salt.utils.data.decode_list(fp_.read().splitlines(True)) changes_diff = __utils__['stringutils.get_diff'](path_content, body) if __opts__['test'] is False: fh_ = None try: # Make sure we match the file mode from salt.utils.files.fopen if six.PY2 and salt.utils.platform.is_windows(): mode = 'wb' body = salt.utils.data.encode_list(body) else: mode = 'w' body = salt.utils.data.decode_list(body, to_str=True) fh_ = salt.utils.atomicfile.atomic_open(path, mode) fh_.writelines(body) finally: if fh_: fh_.close() return show_changes and changes_diff or changed def replace(path, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, backup='.bak', dry_run=False, search_only=False, show_changes=True, ignore_if_missing=False, preserve_inode=True, backslash_literal=False, ): ''' .. versionadded:: 0.17.0 Replace occurrences of a pattern in a file. If ``show_changes`` is ``True``, then a diff of what changed will be returned, otherwise a ``True`` will be returned when changes are made, and ``False`` when no changes are made. This is a pure Python implementation that wraps Python's :py:func:`~re.sub`. path Filesystem path to the file to be edited. If a symlink is specified, it will be resolved to its target. pattern A regular expression, to be matched using Python's :py:func:`~re.search`. repl The replacement text count : 0 Maximum number of pattern occurrences to be replaced. If count is a positive integer ``n``, only ``n`` occurrences will be replaced, otherwise all occurrences will be replaced. flags (list or int) A list of flags defined in the ``re`` module documentation from the Python standard library. Each list item should be a string that will correlate to the human-friendly flag name. E.g., ``['IGNORECASE', 'MULTILINE']``. Optionally, ``flags`` may be an int, with a value corresponding to the XOR (``|``) of all the desired flags. Defaults to 8 (which supports 'MULTILINE'). bufsize (int or str) How much of the file to buffer into memory at once. The default value ``1`` processes one line at a time. The special value ``file`` may be specified which will read the entire file into memory before processing. append_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True``, and pattern is not found, then the content will be appended to the file. prepend_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True`` and pattern is not found, then the content will be prepended to the file. not_found_content .. versionadded:: 2014.7.0 Content to use for append/prepend if not found. If None (default), uses ``repl``. Useful when ``repl`` uses references to group in pattern. backup : .bak The file extension to use for a backup of the file before editing. Set to ``False`` to skip making a backup. dry_run : False If set to ``True``, no changes will be made to the file, the function will just return the changes that would have been made (or a ``True``/``False`` value if ``show_changes`` is set to ``False``). search_only : False If set to true, this no changes will be performed on the file, and this function will simply return ``True`` if the pattern was matched, and ``False`` if not. show_changes : True If ``True``, return a diff of changes made. Otherwise, return ``True`` if changes were made, and ``False`` if not. .. note:: Using this option will store two copies of the file in memory (the original version and the edited version) in order to generate the diff. This may not normally be a concern, but could impact performance if used with large files. ignore_if_missing : False .. versionadded:: 2015.8.0 If set to ``True``, this function will simply return ``False`` if the file doesn't exist. Otherwise, an error will be thrown. preserve_inode : True .. versionadded:: 2015.8.0 Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). backslash_literal : False .. versionadded:: 2016.11.7 Interpret backslashes as literal backslashes for the repl and not escape characters. This will help when using append/prepend so that the backslashes are not interpreted for the repl on the second run of the state. If an equal sign (``=``) appears in an argument to a Salt command it is interpreted as a keyword argument in the format ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.replace /path/to/file pattern='=' repl=':' salt '*' file.replace /path/to/file pattern="bind-address\\s*=" repl='bind-address:' CLI Examples: .. code-block:: bash salt '*' file.replace /etc/httpd/httpd.conf pattern='LogLevel warn' repl='LogLevel info' salt '*' file.replace /some/file pattern='before' repl='after' flags='[MULTILINE, IGNORECASE]' ''' symlink = False if is_link(path): symlink = True target_path = os.readlink(path) given_path = os.path.expanduser(path) path = os.path.realpath(os.path.expanduser(path)) if not os.path.exists(path): if ignore_if_missing: return False else: raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if search_only and (append_if_not_found or prepend_if_not_found): raise SaltInvocationError( 'search_only cannot be used with append/prepend_if_not_found' ) if append_if_not_found and prepend_if_not_found: raise SaltInvocationError( 'Only one of append and prepend_if_not_found is permitted' ) flags_num = _get_flags(flags) cpattern = re.compile(salt.utils.stringutils.to_bytes(pattern), flags_num) filesize = os.path.getsize(path) if bufsize == 'file': bufsize = filesize # Search the file; track if any changes have been made for the return val has_changes = False orig_file = [] # used for show_changes and change detection new_file = [] # used for show_changes and change detection if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Avoid TypeErrors by forcing repl to be bytearray related to mmap # Replacement text may contains integer: 123 for example repl = salt.utils.stringutils.to_bytes(six.text_type(repl)) if not_found_content: not_found_content = salt.utils.stringutils.to_bytes(not_found_content) found = False temp_file = None content = salt.utils.stringutils.to_unicode(not_found_content) \ if not_found_content and (prepend_if_not_found or append_if_not_found) \ else salt.utils.stringutils.to_unicode(repl) try: # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes r_data = None # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: try: # mmap throws a ValueError if the file is empty. r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) except (ValueError, mmap.error): # size of file in /proc is 0, but contains data r_data = salt.utils.stringutils.to_bytes("".join(r_file)) if search_only: # Just search; bail as early as a match is found if re.search(cpattern, r_data): return True # `with` block handles file closure else: return False else: result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) # found anything? (even if no change) if nrepl > 0: found = True # Identity check the potential change has_changes = True if pattern != repl else has_changes if prepend_if_not_found or append_if_not_found: # Search for content, to avoid pre/appending the # content if it was pre/appended in a previous run. if re.search(salt.utils.stringutils.to_bytes('^{0}($|(?=\r\n))'.format(re.escape(content))), r_data, flags=flags_num): # Content was found, so set found. found = True orig_file = r_data.read(filesize).splitlines(True) \ if isinstance(r_data, mmap.mmap) \ else r_data.splitlines(True) new_file = result.splitlines(True) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() if has_changes and not dry_run: # Write the replacement text in this block. try: # Create a copy to read from and to use as a backup later temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) r_data = None try: # Open the file in write mode with salt.utils.files.fopen(path, mode='w', buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='r', buffering=bufsize) as r_file: r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) try: w_file.write(salt.utils.stringutils.to_str(result)) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if not found and (append_if_not_found or prepend_if_not_found): if not_found_content is None: not_found_content = repl if prepend_if_not_found: new_file.insert(0, not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) else: # append_if_not_found # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(salt.utils.stringutils.to_bytes(os.linesep)): new_file[-1] += salt.utils.stringutils.to_bytes(os.linesep) new_file.append(not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) has_changes = True if not dry_run: try: # Create a copy to read from and for later use as a backup temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line)) finally: fh_.close() if backup and has_changes and not dry_run: # keep the backup only if it was requested # and only if there were any changes backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) if symlink: symlink_backup = '{0}{1}'.format(given_path, backup) target_backup = '{0}{1}'.format(target_path, backup) # Always clobber any existing symlink backup # to match the behaviour of the 'backup' option try: os.symlink(target_backup, symlink_backup) except OSError: os.remove(symlink_backup) os.symlink(target_backup, symlink_backup) except Exception: raise CommandExecutionError( "Unable create backup symlink '{0}'. " "Target was '{1}'. " "Exception: {2}".format(symlink_backup, target_backup, exc) ) elif temp_file: try: os.remove(temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to delete temp file '{0}'. " "Exception: {1}".format(temp_file, exc) ) if not dry_run and not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) differences = __utils__['stringutils.get_diff'](orig_file, new_file) if show_changes: return differences # We may have found a regex line match but don't need to change the line # (for situations where the pattern also matches the repl). Revert the # has_changes flag to False if the final result is unchanged. if not differences: has_changes = False return has_changes def blockreplace(path, marker_start='#-- start managed zone --', marker_end='#-- end managed zone --', content='', append_if_not_found=False, prepend_if_not_found=False, backup='.bak', dry_run=False, show_changes=True, append_newline=False, insert_before_match=None, insert_after_match=None): ''' .. versionadded:: 2014.1.0 Replace content of a text block in a file, delimited by line markers A block of content delimited by comments can help you manage several lines entries without worrying about old entries removal. .. note:: This function will store two copies of the file in-memory (the original version and the edited version) in order to detect changes and only edit the targeted file if necessary. path Filesystem path to the file to be edited marker_start The line content identifying a line as the start of the content block. Note that the whole line containing this marker will be considered, so whitespace or extra content before or after the marker is included in final output marker_end The line content identifying the end of the content block. As of versions 2017.7.5 and 2018.3.1, everything up to the text matching the marker will be replaced, so it's important to ensure that your marker includes the beginning of the text you wish to replace. content The content to be used between the two lines identified by marker_start and marker_stop. append_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be appended to the file. prepend_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be prepended to the file. insert_before_match If markers are not found, this parameter can be set to a regex which will insert the block before the first found occurrence in the file. .. versionadded:: Neon insert_after_match If markers are not found, this parameter can be set to a regex which will insert the block after the first found occurrence in the file. .. versionadded:: Neon backup The file extension to use for a backup of the file if any edit is made. Set to ``False`` to skip making a backup. dry_run : False If ``True``, do not make any edits to the file and simply return the changes that *would* be made. show_changes : True Controls how changes are presented. If ``True``, this function will return a unified diff of the changes made. If False, then it will return a boolean (``True`` if any changes were made, otherwise ``False``). append_newline : False Controls whether or not a newline is appended to the content block. If the value of this argument is ``True`` then a newline will be added to the content block. If it is ``False``, then a newline will *not* be added to the content block. If it is ``None`` then a newline will only be added to the content block if it does not already end in a newline. .. versionadded:: 2016.3.4 .. versionchanged:: 2017.7.5,2018.3.1 New behavior added when value is ``None``. .. versionchanged:: 2019.2.0 The default value of this argument will change to ``None`` to match the behavior of the :py:func:`file.blockreplace state <salt.states.file.blockreplace>` CLI Example: .. code-block:: bash salt '*' file.blockreplace /etc/hosts '#-- start managed zone foobar : DO NOT EDIT --' \\ '#-- end managed zone foobar --' $'10.0.1.1 foo.foobar\\n10.0.1.2 bar.foobar' True ''' exclusive_params = [append_if_not_found, prepend_if_not_found, bool(insert_before_match), bool(insert_after_match)] if sum(exclusive_params) > 1: raise SaltInvocationError( 'Only one of append_if_not_found, prepend_if_not_found,' ' insert_before_match, and insert_after_match is permitted' ) path = os.path.expanduser(path) if not os.path.exists(path): raise SaltInvocationError('File not found: {0}'.format(path)) try: file_encoding = __utils__['files.get_encoding'](path) except CommandExecutionError: file_encoding = None if __utils__['files.is_binary'](path): if not file_encoding: raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if insert_before_match or insert_after_match: if insert_before_match: if not isinstance(insert_before_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_before_match parameter.' ) elif insert_after_match: if not isinstance(insert_after_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_after_match parameter.' ) if append_newline is None and not content.endswith((os.linesep, '\n')): append_newline = True # Split the content into a list of lines, removing newline characters. To # ensure that we handle both Windows and POSIX newlines, first split on # Windows newlines, and then split on POSIX newlines. split_content = [] for win_line in content.split('\r\n'): for content_line in win_line.split('\n'): split_content.append(content_line) line_count = len(split_content) has_changes = False orig_file = [] new_file = [] in_block = False block_found = False linesep = None def _add_content(linesep, lines=None, include_marker_start=True, end_line=None): if lines is None: lines = [] include_marker_start = True if end_line is None: end_line = marker_end end_line = end_line.rstrip('\r\n') + linesep if include_marker_start: lines.append(marker_start + linesep) if split_content: for index, content_line in enumerate(split_content, 1): if index != line_count: lines.append(content_line + linesep) else: # We're on the last line of the content block if append_newline: lines.append(content_line + linesep) lines.append(end_line) else: lines.append(content_line + end_line) else: lines.append(end_line) return lines # We do not use in-place editing to avoid file attrs modifications when # no changes are required and to avoid any file access on a partially # written file. try: fi_file = io.open(path, mode='r', encoding=file_encoding, newline='') for line in fi_file: write_line_to_new_file = True if linesep is None: # Auto-detect line separator if line.endswith('\r\n'): linesep = '\r\n' elif line.endswith('\n'): linesep = '\n' else: # No newline(s) in file, fall back to system's linesep linesep = os.linesep if marker_start in line: # We've entered the content block in_block = True else: if in_block: # We're not going to write the lines from the old file to # the new file until we have exited the block. write_line_to_new_file = False marker_end_pos = line.find(marker_end) if marker_end_pos != -1: # End of block detected in_block = False # We've found and exited the block block_found = True _add_content(linesep, lines=new_file, include_marker_start=False, end_line=line[marker_end_pos:]) # Save the line from the original file orig_file.append(line) if write_line_to_new_file: new_file.append(line) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read from {0}: {1}'.format(path, exc) ) finally: if linesep is None: # If the file was empty, we will not have set linesep yet. Assume # the system's line separator. This is needed for when we # prepend/append later on. linesep = os.linesep try: fi_file.close() except Exception: pass if in_block: # unterminated block => bad, always fail raise CommandExecutionError( 'Unterminated marked block. End of file reached before marker_end.' ) if not block_found: if prepend_if_not_found: # add the markers and content at the beginning of file prepended_content = _add_content(linesep) prepended_content.extend(new_file) new_file = prepended_content block_found = True elif append_if_not_found: # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(linesep): new_file[-1] += linesep # add the markers and content at the end of file _add_content(linesep, lines=new_file) block_found = True elif insert_before_match or insert_after_match: match_regex = insert_before_match or insert_after_match match_idx = [i for i, item in enumerate(orig_file) if re.search(match_regex, item)] if match_idx: match_idx = match_idx[0] for line in _add_content(linesep): if insert_after_match: match_idx += 1 new_file.insert(match_idx, line) if insert_before_match: match_idx += 1 block_found = True if not block_found: raise CommandExecutionError( 'Cannot edit marked block. Markers were not found in file.' ) diff = __utils__['stringutils.get_diff'](orig_file, new_file) has_changes = diff is not '' if has_changes and not dry_run: # changes detected # backup file attrs perms = {} perms['user'] = get_user(path) perms['group'] = get_group(path) perms['mode'] = salt.utils.files.normalize_mode(get_mode(path)) # backup old content if backup is not False: backup_path = '{0}{1}'.format(path, backup) shutil.copy2(path, backup_path) # copy2 does not preserve ownership check_perms(backup_path, None, perms['user'], perms['group'], perms['mode']) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line, encoding=file_encoding)) finally: fh_.close() # this may have overwritten file attrs check_perms(path, None, perms['user'], perms['group'], perms['mode']) if show_changes: return diff return has_changes def search(path, pattern, flags=8, bufsize=1, ignore_if_missing=False, multiline=False ): ''' .. versionadded:: 0.17.0 Search for occurrences of a pattern in a file Except for multiline, params are identical to :py:func:`~salt.modules.file.replace`. multiline If true, inserts 'MULTILINE' into ``flags`` and sets ``bufsize`` to 'file'. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' file.search /etc/crontab 'mymaintenance.sh' ''' if multiline: flags = _add_flags(flags, 'MULTILINE') bufsize = 'file' # This function wraps file.replace on purpose in order to enforce # consistent usage, compatible regex's, expected behavior, *and* bugs. :) # Any enhancements or fixes to one should affect the other. return replace(path, pattern, '', flags=flags, bufsize=bufsize, dry_run=True, search_only=True, show_changes=False, ignore_if_missing=ignore_if_missing) def patch(originalfile, patchfile, options='', dry_run=False): ''' .. versionadded:: 0.10.4 Apply a patch to a file or directory. Equivalent to: .. code-block:: bash patch <options> -i <patchfile> <originalfile> Or, when a directory is patched: .. code-block:: bash patch <options> -i <patchfile> -d <originalfile> -p0 originalfile The full path to the file or directory to be patched patchfile A patch file to apply to ``originalfile`` options Options to pass to patch. CLI Example: .. code-block:: bash salt '*' file.patch /opt/file.txt /tmp/file.txt.patch ''' patchpath = salt.utils.path.which('patch') if not patchpath: raise CommandExecutionError( 'patch executable not found. Is the distribution\'s patch ' 'package installed?' ) cmd = [patchpath] cmd.extend(salt.utils.args.shlex_split(options)) if dry_run: if __grains__['kernel'] in ('FreeBSD', 'OpenBSD'): cmd.append('-C') else: cmd.append('--dry-run') # this argument prevents interactive prompts when the patch fails to apply. # the exit code will still be greater than 0 if that is the case. if '-N' not in cmd and '--forward' not in cmd: cmd.append('--forward') has_rejectfile_option = False for option in cmd: if option == '-r' or option.startswith('-r ') \ or option.startswith('--reject-file'): has_rejectfile_option = True break # by default, patch will write rejected patch files to <filename>.rej. # this option prevents that. if not has_rejectfile_option: cmd.append('--reject-file=-') cmd.extend(['-i', patchfile]) if os.path.isdir(originalfile): cmd.extend(['-d', originalfile]) has_strip_option = False for option in cmd: if option.startswith('-p') or option.startswith('--strip='): has_strip_option = True break if not has_strip_option: cmd.append('--strip=0') else: cmd.append(originalfile) return __salt__['cmd.run_all'](cmd, python_shell=False) def contains(path, text): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the file at ``path`` contains ``text`` CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False stripped_text = six.text_type(text).strip() try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if stripped_text in chunk: return True return False except (IOError, OSError): return False def contains_regex(path, regex, lchar=''): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the given regular expression matches on any line in the text of a given file. If the lchar argument (leading char) is specified, it will strip `lchar` from the left side of each line before trying to match CLI Example: .. code-block:: bash salt '*' file.contains_regex /etc/crontab ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.files.fopen(path, 'r') as target: for line in target: line = salt.utils.stringutils.to_unicode(line) if lchar: line = line.lstrip(lchar) if re.search(regex, line): return True return False except (IOError, OSError): return False def contains_glob(path, glob_expr): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the given glob matches a string in the named file CLI Example: .. code-block:: bash salt '*' file.contains_glob /etc/foobar '*cheese*' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if fnmatch.fnmatch(chunk, glob_expr): return True return False except (IOError, OSError): return False def append(path, *args, **kwargs): ''' .. versionadded:: 0.9.5 Append text to the end of a file path path to file `*args` strings to append to file CLI Example: .. code-block:: bash salt '*' file.append /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.append /etc/motd args='cheese=spam' salt '*' file.append /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) # Largely inspired by Fabric's contrib.files.append() if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] # Make sure we have a newline at the end of the file. Do this in binary # mode so SEEK_END with nonzero offset will work. with salt.utils.files.fopen(path, 'rb+') as ofile: linesep = salt.utils.stringutils.to_bytes(os.linesep) try: ofile.seek(-len(linesep), os.SEEK_END) except IOError as exc: if exc.errno in (errno.EINVAL, errno.ESPIPE): # Empty file, simply append lines at the beginning of the file pass else: raise else: if ofile.read(len(linesep)) != linesep: ofile.seek(0, os.SEEK_END) ofile.write(linesep) # Append lines in text mode with salt.utils.files.fopen(path, 'a') as ofile: for new_line in args: ofile.write( salt.utils.stringutils.to_str( '{0}{1}'.format(new_line, os.linesep) ) ) return 'Wrote {0} lines to "{1}"'.format(len(args), path) def prepend(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Prepend text to the beginning of a file path path to file `*args` strings to prepend to the file CLI Example: .. code-block:: bash salt '*' file.prepend /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.prepend /etc/motd args='cheese=spam' salt '*' file.prepend /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] try: with salt.utils.files.fopen(path) as fhr: contents = [salt.utils.stringutils.to_unicode(line) for line in fhr.readlines()] except IOError: contents = [] preface = [] for line in args: preface.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, 'w') as ofile: contents = preface + contents ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Prepended {0} lines to "{1}"'.format(len(args), path) def write(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Write text to a file, overwriting any existing contents. path path to file `*args` strings to write to the file CLI Example: .. code-block:: bash salt '*' file.write /etc/motd \\ "With all thine offerings thou shalt offer salt." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.write /etc/motd args='cheese=spam' salt '*' file.write /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] contents = [] for line in args: contents.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, "w") as ofile: ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Wrote {0} lines to "{1}"'.format(len(contents), path) def touch(name, atime=None, mtime=None): ''' .. versionadded:: 0.9.5 Just like the ``touch`` command, create a file if it doesn't exist or simply update the atime and mtime if it already does. atime: Access time in Unix epoch time. Set it to 0 to set atime of the file with Unix date of birth. If this parameter isn't set, atime will be set with current time. mtime: Last modification in Unix epoch time. Set it to 0 to set mtime of the file with Unix date of birth. If this parameter isn't set, mtime will be set with current time. CLI Example: .. code-block:: bash salt '*' file.touch /var/log/emptyfile ''' name = os.path.expanduser(name) if atime and atime.isdigit(): atime = int(atime) if mtime and mtime.isdigit(): mtime = int(mtime) try: if not os.path.exists(name): with salt.utils.files.fopen(name, 'a'): pass if atime is None and mtime is None: times = None elif mtime is None and atime is not None: times = (atime, time.time()) elif atime is None and mtime is not None: times = (time.time(), mtime) else: times = (atime, mtime) os.utime(name, times) except TypeError: raise SaltInvocationError('atime and mtime must be integers') except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return os.path.exists(name) def tail(path, lines): ''' .. versionadded:: Neon Read the last n lines from a file path path to file lines number of lines to read CLI Example: .. code-block:: bash salt '*' file.tail /path/to/file 10 ''' path = os.path.expanduser(path) lines_found = [] buffer_size = 4098 if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot tail a binary file: {0}'.format(path)) try: lines = int(lines) except ValueError: raise SaltInvocationError('file.tail: \'lines\' value must be an integer') try: with salt.utils.fopen(path) as tail_fh: blk_cnt = 1 size = os.stat(path).st_size if size > buffer_size: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size), os.linesep) for i in range(lines): while len(data) == 1 and ((blk_cnt * buffer_size) < size): blk_cnt += 1 line = data[0] try: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size) + line, os.linesep) except IOError: tail_fh.seek(0) data = string.split(tail_fh.read(size - (buffer_size * (blk_cnt - 1))) + line, os.linesep) line = data[-1] data.pop() lines_found.append(line) return lines_found[-lines:] except (OSError, IOError): raise CommandExecutionError('Could not tail \'{0}\''.format(path)) def seek_read(path, size, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and read it path path to file seek amount to read at once offset offset to start into the file CLI Example: .. code-block:: bash salt '*' file.seek_read /path/to/file 4096 0 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_RDONLY) try: os.lseek(seek_fh, int(offset), 0) data = os.read(seek_fh, int(size)) finally: os.close(seek_fh) return data def seek_write(path, data, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and write to it path path to file data data to write to file offset position in file to start writing CLI Example: .. code-block:: bash salt '*' file.seek_write /path/to/file 'some data' 4096 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_WRONLY) try: os.lseek(seek_fh, int(offset), 0) ret = os.write(seek_fh, data) os.fsync(seek_fh) finally: os.close(seek_fh) return ret def truncate(path, length): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and delete everything after that point path path to file length offset into file to truncate CLI Example: .. code-block:: bash salt '*' file.truncate /path/to/file 512 ''' path = os.path.expanduser(path) with salt.utils.files.fopen(path, 'rb+') as seek_fh: seek_fh.truncate(int(length)) def link(src, path): ''' .. versionadded:: 2014.1.0 Create a hard link to a file CLI Example: .. code-block:: bash salt '*' file.link /path/to/file /path/to/link ''' src = os.path.expanduser(src) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.link(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def is_link(path): ''' Check if the path is a symbolic link CLI Example: .. code-block:: bash salt '*' file.is_link /path/to/link ''' # This function exists because os.path.islink does not support Windows, # therefore a custom function will need to be called. This function # therefore helps API consistency by providing a single function to call for # both operating systems. return os.path.islink(os.path.expanduser(path)) def symlink(src, path): ''' Create a symbolic link (symlink, soft link) to a file CLI Example: .. code-block:: bash salt '*' file.symlink /path/to/file /path/to/link ''' path = os.path.expanduser(path) try: if os.path.normpath(os.readlink(path)) == os.path.normpath(src): log.debug('link already in correct state: %s -> %s', path, src) return True except OSError: pass if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: os.symlink(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def rename(src, dst): ''' Rename a file or directory CLI Example: .. code-block:: bash salt '*' file.rename /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.rename(src, dst) return True except OSError: raise CommandExecutionError( 'Could not rename \'{0}\' to \'{1}\''.format(src, dst) ) return False def copy(src, dst, recurse=False, remove_existing=False): ''' Copy a file or directory from source to dst In order to copy a directory, the recurse flag is required, and will by default overwrite files in the destination with the same path, and retain all other existing files. (similar to cp -r on unix) remove_existing will remove all files in the target directory, and then copy files from the source. .. note:: The copy function accepts paths that are local to the Salt minion. This function does not support salt://, http://, or the other additional file paths that are supported by :mod:`states.file.managed <salt.states.file.managed>` and :mod:`states.file.recurse <salt.states.file.recurse>`. CLI Example: .. code-block:: bash salt '*' file.copy /path/to/src /path/to/dst salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True remove_existing=True ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') if not os.path.exists(src): raise CommandExecutionError('No such file or directory \'{0}\''.format(src)) if not salt.utils.platform.is_windows(): pre_user = get_user(src) pre_group = get_group(src) pre_mode = salt.utils.files.normalize_mode(get_mode(src)) try: if (os.path.exists(dst) and os.path.isdir(dst)) or os.path.isdir(src): if not recurse: raise SaltInvocationError( "Cannot copy overwriting a directory without recurse flag set to true!") if remove_existing: if os.path.exists(dst): shutil.rmtree(dst) shutil.copytree(src, dst) else: salt.utils.files.recursive_copy(src, dst) else: shutil.copyfile(src, dst) except OSError: raise CommandExecutionError( 'Could not copy \'{0}\' to \'{1}\''.format(src, dst) ) if not salt.utils.platform.is_windows(): check_perms(dst, None, pre_user, pre_group, pre_mode) return True def lstat(path): ''' .. versionadded:: 2014.1.0 Returns the lstat attributes for the given file or dir. Does not support symbolic links. CLI Example: .. code-block:: bash salt '*' file.lstat /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to file must be absolute.') try: lst = os.lstat(path) return dict((key, getattr(lst, key)) for key in ('st_atime', 'st_ctime', 'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid')) except Exception: return {} def access(path, mode): ''' .. versionadded:: 2014.1.0 Test whether the Salt process has the specified access to the file. One of the following modes must be specified: .. code-block::text f: Test the existence of the path r: Test the readability of the path w: Test the writability of the path x: Test whether the path can be executed CLI Example: .. code-block:: bash salt '*' file.access /path/to/file f salt '*' file.access /path/to/file x ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') modes = {'f': os.F_OK, 'r': os.R_OK, 'w': os.W_OK, 'x': os.X_OK} if mode in modes: return os.access(path, modes[mode]) elif mode in six.itervalues(modes): return os.access(path, mode) else: raise SaltInvocationError('Invalid mode specified.') def read(path, binary=False): ''' .. versionadded:: 2017.7.0 Return the content of the file. CLI Example: .. code-block:: bash salt '*' file.read /path/to/file ''' access_mode = 'r' if binary is True: access_mode += 'b' with salt.utils.files.fopen(path, access_mode) as file_obj: return salt.utils.stringutils.to_unicode(file_obj.read()) def readlink(path, canonicalize=False): ''' .. versionadded:: 2014.1.0 Return the path that a symlink points to If canonicalize is set to True, then it return the final target CLI Example: .. code-block:: bash salt '*' file.readlink /path/to/link ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') if not os.path.islink(path): raise SaltInvocationError('A valid link was not specified.') if canonicalize: return os.path.realpath(path) else: return os.readlink(path) def readdir(path): ''' .. versionadded:: 2014.1.0 Return a list containing the contents of a directory CLI Example: .. code-block:: bash salt '*' file.readdir /path/to/dir/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Dir path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') dirents = ['.', '..'] dirents.extend(os.listdir(path)) return dirents def statvfs(path): ''' .. versionadded:: 2014.1.0 Perform a statvfs call against the filesystem that the file resides on CLI Example: .. code-block:: bash salt '*' file.statvfs /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: stv = os.statvfs(path) return dict((key, getattr(stv, key)) for key in ('f_bavail', 'f_bfree', 'f_blocks', 'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag', 'f_frsize', 'f_namemax')) except (OSError, IOError): raise CommandExecutionError('Could not statvfs \'{0}\''.format(path)) return False def stats(path, hash_type=None, follow_symlinks=True): ''' Return a dict containing the stats for a given file CLI Example: .. code-block:: bash salt '*' file.stats /etc/passwd ''' path = os.path.expanduser(path) ret = {} if not os.path.exists(path): try: # Broken symlinks will return False for os.path.exists(), but still # have a uid and gid pstat = os.lstat(path) except OSError: # Not a broken symlink, just a nonexistent path # NOTE: The file.directory state checks the content of the error # message in this exception. Any changes made to the message for this # exception will reflect the file.directory state as well, and will # likely require changes there. raise CommandExecutionError('Path not found: {0}'.format(path)) else: if follow_symlinks: pstat = os.stat(path) else: pstat = os.lstat(path) ret['inode'] = pstat.st_ino ret['uid'] = pstat.st_uid ret['gid'] = pstat.st_gid ret['group'] = gid_to_group(pstat.st_gid) ret['user'] = uid_to_user(pstat.st_uid) ret['atime'] = pstat.st_atime ret['mtime'] = pstat.st_mtime ret['ctime'] = pstat.st_ctime ret['size'] = pstat.st_size ret['mode'] = six.text_type(oct(stat.S_IMODE(pstat.st_mode))) if hash_type: ret['sum'] = get_hash(path, hash_type) ret['type'] = 'file' if stat.S_ISDIR(pstat.st_mode): ret['type'] = 'dir' if stat.S_ISCHR(pstat.st_mode): ret['type'] = 'char' if stat.S_ISBLK(pstat.st_mode): ret['type'] = 'block' if stat.S_ISREG(pstat.st_mode): ret['type'] = 'file' if stat.S_ISLNK(pstat.st_mode): ret['type'] = 'link' if stat.S_ISFIFO(pstat.st_mode): ret['type'] = 'pipe' if stat.S_ISSOCK(pstat.st_mode): ret['type'] = 'socket' ret['target'] = os.path.realpath(path) return ret def rmdir(path): ''' .. versionadded:: 2014.1.0 Remove the specified directory. Fails if a directory is not empty. CLI Example: .. code-block:: bash salt '*' file.rmdir /tmp/foo/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') try: os.rmdir(path) return True except OSError as exc: return exc.strerror def remove(path, **kwargs): ''' Remove the named file. If a directory is supplied, it will be recursively deleted. CLI Example: .. code-block:: bash salt '*' file.remove /tmp/foo ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute: {0}'.format(path)) try: if os.path.isfile(path) or os.path.islink(path): os.remove(path) return True elif os.path.isdir(path): shutil.rmtree(path) return True except (OSError, IOError) as exc: raise CommandExecutionError( 'Could not remove \'{0}\': {1}'.format(path, exc) ) return False def directory_exists(path): ''' Tests to see if path is a valid directory. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.directory_exists /etc ''' return os.path.isdir(os.path.expanduser(path)) def file_exists(path): ''' Tests to see if path is a valid file. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.file_exists /etc/passwd ''' return os.path.isfile(os.path.expanduser(path)) def path_exists_glob(path): ''' Tests to see if path after expansion is a valid path (file or directory). Expansion allows usage of ? * and character ranges []. Tilde expansion is not supported. Returns True/False. .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' file.path_exists_glob /etc/pam*/pass* ''' return True if glob.glob(os.path.expanduser(path)) else False def restorecon(path, recursive=False): ''' Reset the SELinux context on a given path CLI Example: .. code-block:: bash salt '*' file.restorecon /home/user/.ssh/authorized_keys ''' if recursive: cmd = ['restorecon', '-FR', path] else: cmd = ['restorecon', '-F', path] return not __salt__['cmd.retcode'](cmd, python_shell=False) def get_selinux_context(path): ''' Get an SELinux context from a given path CLI Example: .. code-block:: bash salt '*' file.get_selinux_context /etc/hosts ''' out = __salt__['cmd.run'](['ls', '-Z', path], python_shell=False) try: ret = re.search(r'\w+:\w+:\w+:\w+', out).group(0) except AttributeError: ret = ( 'No selinux context information is available for {0}'.format(path) ) return ret def set_selinux_context(path, user=None, role=None, type=None, # pylint: disable=W0622 range=None, # pylint: disable=W0622 persist=False): ''' .. versionchanged:: Neon Added persist option Set a specific SELinux label on a given path CLI Example: .. code-block:: bash salt '*' file.set_selinux_context path <user> <role> <type> <range> salt '*' file.set_selinux_context /etc/yum.repos.d/epel.repo system_u object_r system_conf_t s0 ''' if not any((user, role, type, range)): return False if persist: fcontext_result = __salt__['selinux.fcontext_add_policy'](path, sel_type=type, sel_user=user, sel_level=range) if fcontext_result.get('retcode', None) is not 0: # Problem setting fcontext policy raise CommandExecutionError( 'Problem setting fcontext: {0}'.format(fcontext_result) ) cmd = ['chcon'] if user: cmd.extend(['-u', user]) if role: cmd.extend(['-r', role]) if type: cmd.extend(['-t', type]) if range: cmd.extend(['-l', range]) cmd.append(path) ret = not __salt__['cmd.retcode'](cmd, python_shell=False) if ret: return get_selinux_context(path) else: return ret def source_list(source, source_hash, saltenv): ''' Check the source list and return the source to use CLI Example: .. code-block:: bash salt '*' file.source_list salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' base ''' contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv) if contextkey in __context__: return __context__[contextkey] # get the master file list if isinstance(source, list): mfiles = [(f, saltenv) for f in __salt__['cp.list_master'](saltenv)] mdirs = [(d, saltenv) for d in __salt__['cp.list_master_dirs'](saltenv)] for single in source: if isinstance(single, dict): single = next(iter(single)) path, senv = salt.utils.url.parse(single) if senv: mfiles += [(f, senv) for f in __salt__['cp.list_master'](senv)] mdirs += [(d, senv) for d in __salt__['cp.list_master_dirs'](senv)] ret = None for single in source: if isinstance(single, dict): # check the proto, if it is http or ftp then download the file # to check, if it is salt then check the master list # if it is a local file, check if the file exists if len(single) != 1: continue single_src = next(iter(single)) single_hash = single[single_src] if single[single_src] else source_hash urlparsed_single_src = _urlparse(single_src) # Fix this for Windows if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_single_src.scheme.lower() in string.ascii_lowercase: urlparsed_single_src = _urlparse('file://' + single_src) proto = urlparsed_single_src.scheme if proto == 'salt': path, senv = salt.utils.url.parse(single_src) if not senv: senv = saltenv if (path, saltenv) in mfiles or (path, saltenv) in mdirs: ret = (single_src, single_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single_src, single_hash) break elif proto == 'file' and ( os.path.exists(urlparsed_single_src.netloc) or os.path.exists(urlparsed_single_src.path) or os.path.exists(os.path.join( urlparsed_single_src.netloc, urlparsed_single_src.path))): ret = (single_src, single_hash) break elif single_src.startswith(os.sep) and os.path.exists(single_src): ret = (single_src, single_hash) break elif isinstance(single, six.string_types): path, senv = salt.utils.url.parse(single) if not senv: senv = saltenv if (path, senv) in mfiles or (path, senv) in mdirs: ret = (single, source_hash) break urlparsed_src = _urlparse(single) if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_src.scheme.lower() in string.ascii_lowercase: urlparsed_src = _urlparse('file://' + single) proto = urlparsed_src.scheme if proto == 'file' and ( os.path.exists(urlparsed_src.netloc) or os.path.exists(urlparsed_src.path) or os.path.exists(os.path.join( urlparsed_src.netloc, urlparsed_src.path))): ret = (single, source_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single, source_hash) break elif single.startswith(os.sep) and os.path.exists(single): ret = (single, source_hash) break if ret is None: # None of the list items matched raise CommandExecutionError( 'none of the specified sources were found' ) else: ret = (source, source_hash) __context__[contextkey] = ret return ret def apply_template_on_contents( contents, template, context, defaults, saltenv): ''' Return the contents after applying the templating engine contents template string template template format context Overrides default context variables passed to the template. defaults Default context passed to the template. CLI Example: .. code-block:: bash salt '*' file.apply_template_on_contents \\ contents='This is a {{ template }} string.' \\ template=jinja \\ "context={}" "defaults={'template': 'cool'}" \\ saltenv=base ''' if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) # Apply templating contents = salt.utils.templates.TEMPLATE_REGISTRY[template]( contents, from_str=True, to_str=True, context=context_dict, saltenv=saltenv, grains=__opts__['grains'], pillar=__pillar__, salt=__salt__, opts=__opts__)['data'] if six.PY2: contents = contents.encode('utf-8') elif six.PY3 and isinstance(contents, bytes): # bytes -> str contents = contents.decode('utf-8') else: ret = {} ret['result'] = False ret['comment'] = ('Specified template format {0} is not supported' ).format(template) return ret return contents def get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify=False, **kwargs): ''' Return the managed file data for file.managed name location where the file lives on the server template template format source managed source file source_hash hash of the source file source_hash_name When ``source_hash`` refers to a remote file, this specifies the filename to look for in that file. .. versionadded:: 2016.3.5 user Owner of file group Group owner of file mode Permissions of file attrs Attributes of file .. versionadded:: 2018.3.0 context Variables to add to the template context defaults Default values of for context_dict skip_verify If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' file.get_managed /etc/httpd/conf.d/httpd.conf jinja salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' None root root '755' base None None ''' # Copy the file to the minion and templatize it sfn = '' source_sum = {} def _get_local_file_source_sum(path): ''' DRY helper for getting the source_sum value from a locally cached path. ''' return {'hsum': get_hash(path, form='sha256'), 'hash_type': 'sha256'} # If we have a source defined, let's figure out what the hash is if source: urlparsed_source = _urlparse(source) if urlparsed_source.scheme in salt.utils.files.VALID_PROTOS: parsed_scheme = urlparsed_source.scheme else: parsed_scheme = '' parsed_path = os.path.join( urlparsed_source.netloc, urlparsed_source.path).rstrip(os.sep) unix_local_source = parsed_scheme in ('file', '') if parsed_scheme == '': parsed_path = sfn = source if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg elif parsed_scheme == 'file': sfn = parsed_path if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg if parsed_scheme and parsed_scheme.lower() in string.ascii_lowercase: parsed_path = ':'.join([parsed_scheme, parsed_path]) parsed_scheme = 'file' if parsed_scheme == 'salt': source_sum = __salt__['cp.hash_file'](source, saltenv) if not source_sum: return '', {}, 'Source file {0} not found in saltenv \'{1}\''.format(source, saltenv) elif not source_hash and unix_local_source: source_sum = _get_local_file_source_sum(parsed_path) elif not source_hash and source.startswith(os.sep): # This should happen on Windows source_sum = _get_local_file_source_sum(source) else: if not skip_verify: if source_hash: try: source_sum = get_source_sum(name, source, source_hash, source_hash_name, saltenv) except CommandExecutionError as exc: return '', {}, exc.strerror else: msg = ( 'Unable to verify upstream hash of source file {0}, ' 'please set source_hash or set skip_verify to True' .format(salt.utils.url.redact_http_basic_auth(source)) ) return '', {}, msg if source and (template or parsed_scheme in salt.utils.files.REMOTE_PROTOS): # Check if we have the template or remote file cached cache_refetch = False cached_dest = __salt__['cp.is_cached'](source, saltenv) if cached_dest and (source_hash or skip_verify): htype = source_sum.get('hash_type', 'sha256') cached_sum = get_hash(cached_dest, form=htype) if skip_verify: # prev: if skip_verify or cached_sum == source_sum['hsum']: # but `cached_sum == source_sum['hsum']` is elliptical as prev if sfn = cached_dest source_sum = {'hsum': cached_sum, 'hash_type': htype} elif cached_sum != source_sum.get('hsum', __opts__['hash_type']): cache_refetch = True else: sfn = cached_dest # If we didn't have the template or remote file, or the file has been # updated and the cache has to be refreshed, download the file. if not sfn or cache_refetch: try: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum.get('hsum')) except Exception as exc: # A 404 or other error code may raise an exception, catch it # and return a comment that will fail the calling state. _source = salt.utils.url.redact_http_basic_auth(source) return '', {}, 'Failed to cache {0}: {1}'.format(_source, exc) # If cache failed, sfn will be False, so do a truth check on sfn first # as invoking os.path.exists() on a bool raises a TypeError. if not sfn or not os.path.exists(sfn): _source = salt.utils.url.redact_http_basic_auth(source) return sfn, {}, 'Source file \'{0}\' not found'.format(_source) if sfn == name: raise SaltInvocationError( 'Source file cannot be the same as destination' ) if template: if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, name=name, source=source, user=user, group=group, mode=mode, attrs=attrs, saltenv=saltenv, context=context_dict, salt=__salt__, pillar=__pillar__, grains=__opts__['grains'], opts=__opts__, **kwargs) else: return sfn, {}, ('Specified template format {0} is not supported' ).format(template) if data['result']: sfn = data['data'] hsum = get_hash(sfn, form='sha256') source_sum = {'hash_type': 'sha256', 'hsum': hsum} else: __clean_tmp(sfn) return sfn, {}, data['data'] return sfn, source_sum, '' def extract_hash(hash_fn, hash_type='sha256', file_name='', source='', source_hash_name=None): ''' .. versionchanged:: 2016.3.5 Prior to this version, only the ``file_name`` argument was considered for filename matches in the hash file. This would be problematic for cases in which the user was relying on a remote checksum file that they do not control, and they wished to use a different name for that file on the minion from the filename on the remote server (and in the checksum file). For example, managing ``/tmp/myfile.tar.gz`` when the remote file was at ``https://mydomain.tld/different_name.tar.gz``. The :py:func:`file.managed <salt.states.file.managed>` state now also passes this function the source URI as well as the ``source_hash_name`` (if specified). In cases where ``source_hash_name`` is specified, it takes precedence over both the ``file_name`` and ``source``. When it is not specified, ``file_name`` takes precedence over ``source``. This allows for better capability for matching hashes. .. versionchanged:: 2016.11.0 File name and source URI matches are no longer disregarded when ``source_hash_name`` is specified. They will be used as fallback matches if there is no match to the ``source_hash_name`` value. This routine is called from the :mod:`file.managed <salt.states.file.managed>` state to pull a hash from a remote file. Regular expressions are used line by line on the ``source_hash`` file, to find a potential candidate of the indicated hash type. This avoids many problems of arbitrary file layout rules. It specifically permits pulling hash codes from debian ``*.dsc`` files. If no exact match of a hash and filename are found, then the first hash found (if any) will be returned. If no hashes at all are found, then ``None`` will be returned. For example: .. code-block:: yaml openerp_7.0-latest-1.tar.gz: file.managed: - name: /tmp/openerp_7.0-20121227-075624-1_all.deb - source: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.tar.gz - source_hash: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.dsc CLI Example: .. code-block:: bash salt '*' file.extract_hash /path/to/hash/file sha512 /etc/foo ''' hash_len = HASHES.get(hash_type) if hash_len is None: if hash_type: log.warning( 'file.extract_hash: Unsupported hash_type \'%s\', falling ' 'back to matching any supported hash_type', hash_type ) hash_type = '' hash_len_expr = '{0},{1}'.format(min(HASHES_REVMAP), max(HASHES_REVMAP)) else: hash_len_expr = six.text_type(hash_len) filename_separators = string.whitespace + r'\/' if source_hash_name: if not isinstance(source_hash_name, six.string_types): source_hash_name = six.text_type(source_hash_name) source_hash_name_idx = (len(source_hash_name) + 1) * -1 log.debug( 'file.extract_hash: Extracting %s hash for file matching ' 'source_hash_name \'%s\'', 'any supported' if not hash_type else hash_type, source_hash_name ) if file_name: if not isinstance(file_name, six.string_types): file_name = six.text_type(file_name) file_name_basename = os.path.basename(file_name) file_name_idx = (len(file_name_basename) + 1) * -1 if source: if not isinstance(source, six.string_types): source = six.text_type(source) urlparsed_source = _urlparse(source) source_basename = os.path.basename( urlparsed_source.path or urlparsed_source.netloc ) source_idx = (len(source_basename) + 1) * -1 basename_searches = [x for x in (file_name, source) if x] if basename_searches: log.debug( 'file.extract_hash: %s %s hash for file matching%s: %s', 'If no source_hash_name match found, will extract' if source_hash_name else 'Extracting', 'any supported' if not hash_type else hash_type, '' if len(basename_searches) == 1 else ' either of the following', ', '.join(basename_searches) ) partial = None found = {} with salt.utils.files.fopen(hash_fn, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line.strip()) hash_re = r'(?i)(?<![a-z0-9])([a-f0-9]{' + hash_len_expr + '})(?![a-z0-9])' hash_match = re.search(hash_re, line) matched = None if hash_match: matched_hsum = hash_match.group(1) if matched_hsum is not None: matched_type = HASHES_REVMAP.get(len(matched_hsum)) if matched_type is None: # There was a match, but it's not of the correct length # to match one of the supported hash types. matched = None else: matched = {'hsum': matched_hsum, 'hash_type': matched_type} if matched is None: log.debug( 'file.extract_hash: In line \'%s\', no %shash found', line, '' if not hash_type else hash_type + ' ' ) continue if partial is None: partial = matched def _add_to_matches(found, line, match_type, value, matched): log.debug( 'file.extract_hash: Line \'%s\' matches %s \'%s\'', line, match_type, value ) found.setdefault(match_type, []).append(matched) hash_matched = False if source_hash_name: if line.endswith(source_hash_name): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[source_hash_name_idx] in string.whitespace: _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source_hash_name) + r'\s+', line): _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True if file_name: if line.endswith(file_name_basename): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[file_name_idx] in filename_separators: _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(file_name) + r'\s+', line): _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True if source: if line.endswith(source_basename): # Same as above, we can't just do an rsplit here. try: if line[source_idx] in filename_separators: _add_to_matches(found, line, 'source', source, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source) + r'\s+', line): _add_to_matches(found, line, 'source', source, matched) hash_matched = True if not hash_matched: log.debug( 'file.extract_hash: Line \'%s\' contains %s hash ' '\'%s\', but line did not meet the search criteria', line, matched['hash_type'], matched['hsum'] ) for found_type, found_str in (('source_hash_name', source_hash_name), ('file_name', file_name), ('source', source)): if found_type in found: if len(found[found_type]) > 1: log.debug( 'file.extract_hash: Multiple %s matches for %s: %s', found_type, found_str, ', '.join( ['{0} ({1})'.format(x['hsum'], x['hash_type']) for x in found[found_type]] ) ) ret = found[found_type][0] log.debug( 'file.extract_hash: Returning %s hash \'%s\' as a match of %s', ret['hash_type'], ret['hsum'], found_str ) return ret if partial: log.debug( 'file.extract_hash: Returning the partially identified %s hash ' '\'%s\'', partial['hash_type'], partial['hsum'] ) return partial log.debug('file.extract_hash: No matches, returning None') return None def check_perms(name, ret, user, group, mode, attrs=None, follow_symlinks=False, seuser=None, serole=None, setype=None, serange=None): ''' .. versionchanged:: Neon Added selinux options Check the permissions on files, modify attributes and chown if needed. File attributes are only verified if lsattr(1) is installed. CLI Example: .. code-block:: bash salt '*' file.check_perms /etc/sudoers '{}' root root 400 ai .. versionchanged:: 2014.1.3 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': [], 'result': True} orig_comment = '' else: orig_comment = ret['comment'] ret['comment'] = [] # Check permissions perms = {} cur = stats(name, follow_symlinks=follow_symlinks) perms['luser'] = cur['user'] perms['lgroup'] = cur['group'] perms['lmode'] = salt.utils.files.normalize_mode(cur['mode']) is_dir = os.path.isdir(name) is_link = os.path.islink(name) if attrs is not None \ and not salt.utils.platform.is_windows() \ and not is_dir and not is_link: try: lattrs = lsattr(name) except SaltInvocationError: lattrs = None if lattrs is not None: # List attributes on file perms['lattrs'] = ''.join(lattrs.get(name, '')) # Remove attributes on file so changes can be enforced. if perms['lattrs']: chattr(name, operator='remove', attributes=perms['lattrs']) # user/group changes if needed, then check if it worked if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid(perms['luser']) ) or ( not salt.utils.platform.is_windows() and user != perms['luser'] ): perms['cuser'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid(perms['lgroup']) ) or ( not salt.utils.platform.is_windows() and group != perms['lgroup'] ): perms['cgroup'] = group if 'cuser' in perms or 'cgroup' in perms: if not __opts__['test']: if os.path.islink(name) and not follow_symlinks: chown_func = lchown else: chown_func = chown if user is None: user = perms['luser'] if group is None: group = perms['lgroup'] try: chown_func(name, user, group) # Python os.chown() does reset the suid and sgid, # that's why setting the right mode again is needed here. set_mode(name, mode) except OSError: ret['result'] = False if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid( get_user(name, follow_symlinks=follow_symlinks)) and user != '' ) or ( not salt.utils.platform.is_windows() and user != get_user(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['user'] = user else: ret['result'] = False ret['comment'].append('Failed to change user to {0}' .format(user)) elif 'cuser' in perms and user != '': ret['changes']['user'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid( get_group(name, follow_symlinks=follow_symlinks)) and user != '') or ( not salt.utils.platform.is_windows() and group != get_group(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['group'] = group else: ret['result'] = False ret['comment'].append('Failed to change group to {0}' .format(group)) elif 'cgroup' in perms and user != '': ret['changes']['group'] = group if not salt.utils.platform.is_windows() and not is_dir: # Replace attributes on file if it had been removed if perms.get('lattrs', ''): chattr(name, operator='add', attributes=perms['lattrs']) # Mode changes if needed if mode is not None: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: mode = salt.utils.files.normalize_mode(mode) if mode != perms['lmode']: if __opts__['test'] is True: ret['changes']['mode'] = mode else: set_mode(name, mode) if mode != salt.utils.files.normalize_mode(get_mode(name)): ret['result'] = False ret['comment'].append( 'Failed to change mode to {0}'.format(mode) ) else: ret['changes']['mode'] = mode # Modify attributes of file if needed if attrs is not None and not is_dir: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if diff_attrs[0] is not None or diff_attrs[1] is not None: if __opts__['test'] is True: ret['changes']['attrs'] = attrs else: if diff_attrs[0] is not None: chattr(name, operator="add", attributes=diff_attrs[0]) if diff_attrs[1] is not None: chattr(name, operator="remove", attributes=diff_attrs[1]) cmp_attrs = _cmp_attrs(name, attrs) if cmp_attrs[0] is not None or cmp_attrs[1] is not None: ret['result'] = False ret['comment'].append( 'Failed to change attributes to {0}'.format(attrs) ) else: ret['changes']['attrs'] = attrs # Set selinux attributes if needed if salt.utils.platform.is_linux() and (seuser or serole or setype or serange): selinux_error = False try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError: log.error('Unable to get current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to get selinux attributes' ) selinux_error = True if not selinux_error: requested_seuser = None requested_serole = None requested_setype = None requested_serange = None # Only set new selinux variables if updates are needed if seuser and seuser != current_seuser: requested_seuser = seuser if serole and serole != current_serole: requested_serole = serole if setype and setype != current_setype: requested_setype = setype if serange and serange != current_serange: requested_serange = serange if requested_seuser or requested_serole or requested_setype or requested_serange: # selinux updates needed, prep changes output selinux_change_new = '' selinux_change_orig = '' if requested_seuser: selinux_change_new += "User: {0} ".format(requested_seuser) selinux_change_orig += "User: {0} ".format(current_seuser) if requested_serole: selinux_change_new += "Role: {0} ".format(requested_serole) selinux_change_orig += "Role: {0} ".format(current_serole) if requested_setype: selinux_change_new += "Type: {0} ".format(requested_setype) selinux_change_orig += "Type: {0} ".format(current_setype) if requested_serange: selinux_change_new += "Range: {0} ".format(requested_serange) selinux_change_orig += "Range: {0} ".format(current_serange) if __opts__['test']: ret['comment'] = 'File {0} selinux context to be updated'.format(name) ret['result'] = None ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} else: try: # set_selinux_context requires type to be set on any other change if (requested_seuser or requested_serole or requested_serange) and not requested_setype: requested_setype = current_setype result = set_selinux_context(name, user=requested_seuser, role=requested_serole, type=requested_setype, range=requested_serange, persist=True) log.debug('selinux set result: %s', result) current_seuser, current_serole, current_setype, current_serange = result.split(':') except ValueError: log.error('Unable to set current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to set selinux attributes' ) selinux_error = True if not selinux_error: ret['comment'].append('The file {0} is set to be changed'.format(name)) if requested_seuser: if current_seuser != requested_seuser: ret['comment'].append("Unable to update seuser context") ret['result'] = False if requested_serole: if current_serole != requested_serole: ret['comment'].append("Unable to update serole context") ret['result'] = False if requested_setype: if current_setype != requested_setype: ret['comment'].append("Unable to update setype context") ret['result'] = False if requested_serange: if current_serange != requested_serange: ret['comment'].append("Unable to update serange context") ret['result'] = False ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} # Only combine the comment list into a string # after all comments are added above if isinstance(orig_comment, six.string_types): if orig_comment: ret['comment'].insert(0, orig_comment) ret['comment'] = '; '.join(ret['comment']) # Set result to None at the very end of the function, # after all changes have been recorded above if __opts__['test'] is True and ret['changes']: ret['result'] = None return ret, perms def check_managed( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Check to see what changes need to be made for a file CLI Example: .. code-block:: bash salt '*' file.check_managed /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) if comments: __clean_tmp(sfn) return False, comments changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) # Ignore permission for files written temporary directories # Files in any path will still be set correctly using get_managed() if name.startswith(tempfile.gettempdir()): for key in ['user', 'group', 'mode']: changes.pop(key, None) __clean_tmp(sfn) if changes: log.info(changes) comments = ['The following values are set to be changed:\n'] comments.extend('{0}: {1}\n'.format(key, val) for key, val in six.iteritems(changes)) return None, ''.join(comments) return True, 'The file {0} is in the correct state'.format(name) def check_managed_changes( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, keep_mode=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Return a dictionary of what changes need to be made for a file .. versionchanged:: Neon selinux attributes added CLI Example: .. code-block:: bash salt '*' file.check_managed_changes /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if comments: __clean_tmp(sfn) raise CommandExecutionError(comments) if sfn and source and keep_mode: if _urlparse(source).scheme in ('salt', 'file') \ or source.startswith('/'): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) __clean_tmp(sfn) return changes def check_file_meta( name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents=None, seuser=None, serole=None, setype=None, serange=None): ''' Check for the changes in the file metadata. CLI Example: .. code-block:: bash salt '*' file.check_file_meta /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' base .. note:: Supported hash types include sha512, sha384, sha256, sha224, sha1, and md5. name Path to file destination sfn Template-processed source file contents source URL to file source source_sum File checksum information as a dictionary .. code-block:: yaml {hash_type: md5, hsum: <md5sum>} user Destination file user owner group Destination file group owner mode Destination file permissions mode attrs Destination file attributes .. versionadded:: 2018.3.0 saltenv Salt environment used to resolve source files contents File contents seuser selinux user attribute .. versionadded:: Neon serole selinux role attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon ''' changes = {} if not source_sum: source_sum = dict() try: lstats = stats(name, hash_type=source_sum.get('hash_type', None), follow_symlinks=False) except CommandExecutionError: lstats = {} if not lstats: changes['newfile'] = name return changes if 'hsum' in source_sum: if source_sum['hsum'] != lstats['sum']: if not sfn and source: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum['hsum']) if sfn: try: changes['diff'] = get_diff( name, sfn, template=True, show_filenames=False) except CommandExecutionError as exc: changes['diff'] = exc.strerror else: changes['sum'] = 'Checksum differs' if contents is not None: # Write a tempfile with the static contents tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'w') as tmp_: tmp_.write(salt.utils.stringutils.to_str(contents)) # Compare the static contents with the named file try: differences = get_diff(name, tmp, show_filenames=False) except CommandExecutionError as exc: log.error('Failed to diff files: %s', exc) differences = exc.strerror __clean_tmp(tmp) if differences: if __salt__['config.option']('obfuscate_templates'): changes['diff'] = '<Obfuscated Template>' else: changes['diff'] = differences if not salt.utils.platform.is_windows(): # Check owner if (user is not None and user != lstats['user'] and user != lstats['uid']): changes['user'] = user # Check group if (group is not None and group != lstats['group'] and group != lstats['gid']): changes['group'] = group # Normalize the file mode smode = salt.utils.files.normalize_mode(lstats['mode']) mode = salt.utils.files.normalize_mode(mode) if mode is not None and mode != smode: changes['mode'] = mode if attrs: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if attrs is not None \ and (diff_attrs[0] is not None or diff_attrs[1] is not None): changes['attrs'] = attrs # Check selinux if seuser or serole or setype or serange: try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError as exc: log.error('Unable to get current selinux attributes') changes['selinux'] = exc.strerror if seuser and seuser != current_seuser: changes['selinux'] = {"user": seuser} if serole and serole != current_serole: changes['selinux'] = {"role": serole} if setype and setype != current_setype: changes['selinux'] = {"type": setype} if serange and serange != current_serange: changes['selinux'] = {"range": serange} return changes def get_diff(file1, file2, saltenv='base', show_filenames=True, show_changes=True, template=False, source_hash_file1=None, source_hash_file2=None): ''' Return unified diff of two files file1 The first file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, thuis had to be a file local to the minion. file2 The second file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, this had to be a file on the salt fileserver (i.e. ``salt://somefile.txt``) show_filenames : True Set to ``False`` to hide the filenames in the top two lines of the diff. show_changes : True If set to ``False``, and there are differences, then instead of a diff a simple message stating that show_changes is set to ``False`` will be returned. template : False Set to ``True`` if two templates are being compared. This is not useful except for within states, with the ``obfuscate_templates`` option set to ``True``. .. versionadded:: 2018.3.0 source_hash_file1 If ``file1`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 source_hash_file2 If ``file2`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 CLI Examples: .. code-block:: bash salt '*' file.get_diff /home/fred/.vimrc salt://users/fred/.vimrc salt '*' file.get_diff /tmp/foo.txt /tmp/bar.txt ''' files = (file1, file2) source_hashes = (source_hash_file1, source_hash_file2) paths = [] errors = [] for filename, source_hash in zip(files, source_hashes): try: # Local file paths will just return the same path back when passed # to cp.cache_file. cached_path = __salt__['cp.cache_file'](filename, saltenv, source_hash=source_hash) if cached_path is False: errors.append( 'File {0} not found'.format( salt.utils.stringutils.to_unicode(filename) ) ) continue paths.append(cached_path) except MinionError as exc: errors.append(salt.utils.stringutils.to_unicode(exc.__str__())) continue if errors: raise CommandExecutionError( 'Failed to cache one or more files', info=errors ) args = [] for filename in paths: try: with salt.utils.files.fopen(filename, 'rb') as fp_: args.append(fp_.readlines()) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read {0}: {1}'.format( salt.utils.stringutils.to_unicode(filename), exc.strerror ) ) if args[0] != args[1]: if template and __salt__['config.option']('obfuscate_templates'): ret = '<Obfuscated Template>' elif not show_changes: ret = '<show_changes=False>' else: bdiff = _binary_replace(*paths) # pylint: disable=no-value-for-parameter if bdiff: ret = bdiff else: if show_filenames: args.extend(paths) ret = __utils__['stringutils.get_diff'](*args) return ret return '' def manage_file(name, sfn, ret, source, source_sum, user, group, mode, attrs, saltenv, backup, makedirs=False, template=None, # pylint: disable=W0613 show_changes=True, contents=None, dir_mode=None, follow_symlinks=True, skip_verify=False, keep_mode=False, encoding=None, encoding_errors='strict', seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Checks the destination against what was retrieved with get_managed and makes the appropriate modifications (if necessary). name location to place the file sfn location of cached file on the minion This is the path to the file stored on the minion. This file is placed on the minion using cp.cache_file. If the hash sum of that file matches the source_sum, we do not transfer the file to the minion again. This file is then grabbed and if it has template set, it renders the file to be placed into the correct place on the system using salt.files.utils.copyfile() ret The initial state return data structure. Pass in ``None`` to use the default structure. source file reference on the master source_sum sum hash for source user user owner group group owner backup backup_mode attrs attributes to be set on file: '' means remove all of them .. versionadded:: 2018.3.0 makedirs make directories if they do not exist template format of templating show_changes Include diff in state return contents: contents to be placed in the file dir_mode mode for directories created with makedirs skip_verify : False If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 keep_mode : False If ``True``, and the ``source`` is a file from the Salt fileserver (or a local file on the minion), the mode of the destination file will be set to the mode of the source file. .. note:: keep_mode does not work with salt-ssh. As a consequence of how the files are transferred to the minion, and the inability to connect back to the master with salt-ssh, salt is unable to stat the file as it exists on the fileserver and thus cannot mirror the mode on the salt-ssh minion encoding If specified, then the specified encoding will be used. Otherwise, the file will be encoded using the system locale (usually UTF-8). See https://docs.python.org/3/library/codecs.html#standard-encodings for the list of available encodings. .. versionadded:: 2017.7.0 encoding_errors : 'strict' Default is ```'strict'```. See https://docs.python.org/2/library/codecs.html#codec-base-classes for the error handling schemes. .. versionadded:: 2017.7.0 seuser selinux user attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon CLI Example: .. code-block:: bash salt '*' file.manage_file /etc/httpd/conf.d/httpd.conf '' '{}' salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' '' base '' .. versionchanged:: 2014.7.0 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if source: if not sfn: # File is not present, cache it sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) htype = source_sum.get('hash_type', __opts__['hash_type']) # Recalculate source sum now that file has been cached source_sum = { 'hash_type': htype, 'hsum': get_hash(sfn, form=htype) } if keep_mode: if _urlparse(source).scheme in ('salt', 'file', ''): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) # Check changes if the target file exists if os.path.isfile(name) or os.path.islink(name): if os.path.islink(name) and follow_symlinks: real_name = os.path.realpath(name) else: real_name = name # Only test the checksums on files with managed contents if source and not (not follow_symlinks and os.path.islink(real_name)): name_sum = get_hash(real_name, source_sum.get('hash_type', __opts__['hash_type'])) else: name_sum = None # Check if file needs to be replaced if source and (name_sum is None or source_sum.get('hsum', __opts__['hash_type']) != name_sum): if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server or local # source, and we are not skipping checksum verification, then # verify that it matches the specified checksum. if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3}). If the \'source_hash\' value ' 'refers to a remote file with multiple possible ' 'matches, then it may be necessary to set ' '\'source_hash_name\'.'.format( source_sum['hash_type'], source, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # Print a diff equivalent to diff -u old new if __salt__['config.option']('obfuscate_templates'): ret['changes']['diff'] = '<Obfuscated Template>' elif not show_changes: ret['changes']['diff'] = '<show_changes=False>' else: try: ret['changes']['diff'] = get_diff( real_name, sfn, show_filenames=False) except CommandExecutionError as exc: ret['changes']['diff'] = exc.strerror # Pre requisites are met, and the file needs to be replaced, do it try: salt.utils.files.copyfile(sfn, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) try: differences = get_diff( real_name, tmp, show_filenames=False, show_changes=show_changes, template=True) except CommandExecutionError as exc: ret.setdefault('warnings', []).append( 'Failed to detect changes to file: {0}'.format(exc.strerror) ) differences = '' if differences: ret['changes']['diff'] = differences # Pre requisites are met, the file needs to be replaced, do it try: salt.utils.files.copyfile(tmp, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(tmp) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) __clean_tmp(tmp) # Check for changing symlink to regular file here if os.path.islink(name) and not follow_symlinks: if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret try: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) ret['changes']['diff'] = \ 'Replace symbolic link with regular file' if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, follow_symlinks, seuser=seuser, serole=serole, setype=setype, serange=serange) if ret['changes']: ret['comment'] = 'File {0} updated'.format( salt.utils.data.decode(name) ) elif not ret['changes'] and ret['result']: ret['comment'] = 'File {0} is in the correct state'.format( salt.utils.data.decode(name) ) if sfn: __clean_tmp(sfn) return ret else: # target file does not exist contain_dir = os.path.dirname(name) def _set_mode_and_make_dirs(name, dir_mode, mode, user, group): # check for existence of windows drive letter if salt.utils.platform.is_windows(): drive, _ = os.path.splitdrive(name) if drive and not os.path.exists(drive): __clean_tmp(sfn) return _error(ret, '{0} drive not present'.format(drive)) if dir_mode is None and mode is not None: # Add execute bit to each nonzero digit in the mode, if # dir_mode was not specified. Otherwise, any # directories created with makedirs_() below can't be # listed via a shell. mode_list = [x for x in six.text_type(mode)][-3:] for idx in range(len(mode_list)): if mode_list[idx] != '0': mode_list[idx] = six.text_type(int(mode_list[idx]) | 1) dir_mode = ''.join(mode_list) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 makedirs_( path=name, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: makedirs_(name, user=user, group=group, mode=dir_mode) if source: # Apply the new file if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # It is a new file, set the diff accordingly ret['changes']['diff'] = 'New file' if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') else: # source != True if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') # Create the file, user rw-only if mode will be set to prevent # a small security race problem before the permissions are set with salt.utils.files.set_umask(0o077 if mode else None): # Create a new file when test is False and source is None if contents is None: if not __opts__['test']: if touch(name): ret['changes']['new'] = 'file {0} created'.format(name) ret['comment'] = 'Empty file' else: return _error( ret, 'Empty file {0} not created'.format(name) ) else: if not __opts__['test']: if touch(name): ret['changes']['diff'] = 'New file' else: return _error( ret, 'File {0} not created'.format(name) ) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) # Copy into place salt.utils.files.copyfile(tmp, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(tmp) # Now copy the file contents if there is a source file elif sfn: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(sfn) # This is a new file, if no mode specified, use the umask to figure # out what mode to use for the new file. if mode is None and not salt.utils.platform.is_windows(): # Get current umask mask = salt.utils.files.get_umask() # Calculate the mode value that results from the umask mode = oct((0o777 ^ mask) & 0o666) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, seuser=seuser, serole=serole, setype=setype, serange=serange) if not ret['comment']: ret['comment'] = 'File ' + name + ' updated' if __opts__['test']: ret['comment'] = 'File ' + name + ' not updated' elif not ret['changes'] and ret['result']: ret['comment'] = 'File ' + name + ' is in the correct state' if sfn: __clean_tmp(sfn) return ret def mkdir(dir_path, user=None, group=None, mode=None): ''' Ensure that a directory is available. CLI Example: .. code-block:: bash salt '*' file.mkdir /opt/jetty/context ''' dir_path = os.path.expanduser(dir_path) directory = os.path.normpath(dir_path) if not os.path.isdir(directory): # If a caller such as managed() is invoked with makedirs=True, make # sure that any created dirs are created with the same user and group # to follow the principal of least surprise method. makedirs_perms(directory, user, group, mode) return True def makedirs_(path, user=None, group=None, mode=None): ''' Ensure that the directory containing this path is available. .. note:: The path must end with a trailing slash otherwise the directory/directories will be created up to the parent directory. For example if path is ``/opt/code``, then it would be treated as ``/opt/`` but if the path ends with a trailing slash like ``/opt/code/``, then it would be treated as ``/opt/code/``. CLI Example: .. code-block:: bash salt '*' file.makedirs /opt/code/ ''' path = os.path.expanduser(path) if mode: mode = salt.utils.files.normalize_mode(mode) # walk up the directory structure until we find the first existing # directory dirname = os.path.normpath(os.path.dirname(path)) if os.path.isdir(dirname): # There's nothing for us to do msg = 'Directory \'{0}\' already exists'.format(dirname) log.debug(msg) return msg if os.path.exists(dirname): msg = 'The path \'{0}\' already exists and is not a directory'.format( dirname ) log.debug(msg) return msg directories_to_create = [] while True: if os.path.isdir(dirname): break directories_to_create.append(dirname) current_dirname = dirname dirname = os.path.dirname(dirname) if current_dirname == dirname: raise SaltInvocationError( 'Recursive creation for path \'{0}\' would result in an ' 'infinite loop. Please use an absolute path.'.format(dirname) ) # create parent directories from the topmost to the most deeply nested one directories_to_create.reverse() for directory_to_create in directories_to_create: # all directories have the user, group and mode set!! log.debug('Creating directory: %s', directory_to_create) mkdir(directory_to_create, user=user, group=group, mode=mode) def makedirs_perms(name, user=None, group=None, mode='0755'): ''' Taken and modified from os.makedirs to set user, group and mode for each directory created. CLI Example: .. code-block:: bash salt '*' file.makedirs_perms /opt/code ''' name = os.path.expanduser(name) path = os.path head, tail = path.split(name) if not tail: head, tail = path.split(head) if head and tail and not path.exists(head): try: makedirs_perms(head, user, group, mode) except OSError as exc: # be happy if someone already created the path if exc.errno != errno.EEXIST: raise if tail == os.curdir: # xxx/newdir/. exists if xxx/newdir exists return os.mkdir(name) check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) def get_devmm(name): ''' Get major/minor info from a device CLI Example: .. code-block:: bash salt '*' file.get_devmm /dev/chr ''' name = os.path.expanduser(name) if is_chrdev(name) or is_blkdev(name): stat_structure = os.stat(name) return ( os.major(stat_structure.st_rdev), os.minor(stat_structure.st_rdev)) else: return (0, 0) def is_chrdev(name): ''' Check if a file exists and is a character device. CLI Example: .. code-block:: bash salt '*' file.is_chrdev /dev/chr ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the character device does not exist in the first place return False else: raise return stat.S_ISCHR(stat_structure.st_mode) def mknod_chrdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a character device. CLI Example: .. code-block:: bash salt '*' file.mknod_chrdev /dev/chr 180 31 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating character device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFCHR, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created character device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_blkdev(name): ''' Check if a file exists and is a block device. CLI Example: .. code-block:: bash salt '*' file.is_blkdev /dev/blk ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the block device does not exist in the first place return False else: raise return stat.S_ISBLK(stat_structure.st_mode) def mknod_blkdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a block device. CLI Example: .. code-block:: bash salt '*' file.mknod_blkdev /dev/blk 8 999 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating block device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFBLK, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created block device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_fifo(name): ''' Check if a file exists and is a FIFO. CLI Example: .. code-block:: bash salt '*' file.is_fifo /dev/fifo ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the fifo does not exist in the first place return False else: raise return stat.S_ISFIFO(stat_structure.st_mode) def mknod_fifo(name, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a FIFO pipe. CLI Example: .. code-block:: bash salt '*' file.mknod_fifo /dev/fifo ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating FIFO name: %s', name) try: if __opts__['test']: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = None else: if os.mkfifo(name, int(six.text_type(mode).lstrip('0Oo'), 8)) is None: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created fifo check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def mknod(name, ntype, major=0, minor=0, user=None, group=None, mode='0600'): ''' .. versionadded:: 0.17.0 Create a block device, character device, or fifo pipe. Identical to the gnu mknod. CLI Examples: .. code-block:: bash salt '*' file.mknod /dev/chr c 180 31 salt '*' file.mknod /dev/blk b 8 999 salt '*' file.nknod /dev/fifo p ''' ret = False makedirs_(name, user, group) if ntype == 'c': ret = mknod_chrdev(name, major, minor, user, group, mode) elif ntype == 'b': ret = mknod_blkdev(name, major, minor, user, group, mode) elif ntype == 'p': ret = mknod_fifo(name, user, group, mode) else: raise SaltInvocationError( 'Node type unavailable: \'{0}\'. Available node types are ' 'character (\'c\'), block (\'b\'), and pipe (\'p\').'.format(ntype) ) return ret def list_backups(path, limit=None): ''' .. versionadded:: 0.17.0 Lists the previous versions of a file backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups /foo/bar/baz.txt ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows src_dir = parent_dir.replace(':', '_') else: src_dir = parent_dir[1:] # Figure out full path of location of backup file in minion cache bkdir = os.path.join(bkroot, src_dir) if not os.path.isdir(bkdir): return {} files = {} for fname in [x for x in os.listdir(bkdir) if os.path.isfile(os.path.join(bkdir, x))]: if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows strpfmt = '{0}_%a_%b_%d_%H-%M-%S_%f_%Y'.format(basename) else: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(fname, strpfmt) except ValueError: # File didn't match the strp format string, so it's not a backup # for this file. Move on to the next one. continue if salt.utils.platform.is_windows(): str_format = '%a %b %d %Y %H-%M-%S.%f' else: str_format = '%a %b %d %Y %H:%M:%S.%f' files.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime(str_format) location = os.path.join(bkdir, fname) files[timestamp]['Size'] = os.stat(location).st_size files[timestamp]['Location'] = location return dict(list(zip( list(range(len(files))), [files[x] for x in sorted(files, reverse=True)[:limit]] ))) list_backup = salt.utils.functools.alias_function(list_backups, 'list_backup') def list_backups_dir(path, limit=None): ''' Lists the previous versions of a directory backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The directory on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups_dir /foo/bar/baz/ ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups_dir: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) # Figure out full path of location of backup folder in minion cache bkdir = os.path.join(bkroot, parent_dir[1:]) if not os.path.isdir(bkdir): return {} files = {} f = dict([(i, len(list(n))) for i, n in itertools.groupby([x.split("_")[0] for x in sorted(os.listdir(bkdir))])]) ff = os.listdir(bkdir) for i, n in six.iteritems(f): ssfile = {} for x in sorted(ff): basename = x.split('_')[0] if i == basename: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(x, strpfmt) except ValueError: # Folder didn't match the strp format string, so it's not a backup # for this folder. Move on to the next one. continue ssfile.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime('%a %b %d %Y %H:%M:%S.%f') location = os.path.join(bkdir, x) ssfile[timestamp]['Size'] = os.stat(location).st_size ssfile[timestamp]['Location'] = location sfiles = dict(list(zip(list(range(n)), [ssfile[x] for x in sorted(ssfile, reverse=True)[:limit]]))) sefiles = {i: sfiles} files.update(sefiles) return files def restore_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Restore a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to restore, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.restore_backup /foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) # Note: This only supports minion backups, so this function will need to be # modified if/when master backups are implemented. ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret salt.utils.files.backup_minion(path, _get_bkroot()) try: shutil.copyfile(backup['Location'], path) except IOError as exc: ret['comment'] = \ 'Unable to restore {0} to {1}: ' \ '{2}'.format(backup['Location'], path, exc) return ret else: ret['result'] = True ret['comment'] = 'Successfully restored {0} to ' \ '{1}'.format(backup['Location'], path) # Try to set proper ownership if not salt.utils.platform.is_windows(): try: fstat = os.stat(path) except (OSError, IOError): ret['comment'] += ', but was unable to set ownership' else: os.chown(path, fstat.st_uid, fstat.st_gid) return ret def delete_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Delete a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to delete, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.delete_backup /var/cache/salt/minion/file_backup/home/foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret try: os.remove(backup['Location']) except IOError as exc: ret['comment'] = 'Unable to remove {0}: {1}'.format(backup['Location'], exc) else: ret['result'] = True ret['comment'] = 'Successfully removed {0}'.format(backup['Location']) return ret remove_backup = salt.utils.functools.alias_function(delete_backup, 'remove_backup') def grep(path, pattern, *opts): ''' Grep for a string in the specified file .. note:: This function's return value is slated for refinement in future versions of Salt path Path to the file to be searched .. note:: Globbing is supported (i.e. ``/var/log/foo/*.log``, but if globbing is being used then the path should be quoted to keep the shell from attempting to expand the glob expression. pattern Pattern to match. For example: ``test``, or ``a[0-5]`` opts Additional command-line flags to pass to the grep command. For example: ``-v``, or ``-i -B2`` .. note:: The options should come after a double-dash (as shown in the examples below) to keep Salt's own argument parser from interpreting them. CLI Example: .. code-block:: bash salt '*' file.grep /etc/passwd nobody salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i -B2 salt '*' file.grep "/etc/sysconfig/network-scripts/*" ipaddr -- -i -l ''' path = os.path.expanduser(path) # Backup the path in case the glob returns nothing _path = path path = glob.glob(path) # If the list is empty no files exist # so we revert back to the original path # so the result is an error. if not path: path = _path split_opts = [] for opt in opts: try: split = salt.utils.args.shlex_split(opt) except AttributeError: split = salt.utils.args.shlex_split(six.text_type(opt)) if len(split) > 1: raise SaltInvocationError( 'Passing multiple command line arguments in a single string ' 'is not supported, please pass the following arguments ' 'separately: {0}'.format(opt) ) split_opts.extend(split) if isinstance(path, list): cmd = ['grep'] + split_opts + [pattern] + path else: cmd = ['grep'] + split_opts + [pattern, path] try: ret = __salt__['cmd.run_all'](cmd, python_shell=False) except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return ret def open_files(by_pid=False): ''' Return a list of all physical open files on the system. CLI Examples: .. code-block:: bash salt '*' file.open_files salt '*' file.open_files by_pid=True ''' # First we collect valid PIDs pids = {} procfs = os.listdir('/proc/') for pfile in procfs: try: pids[int(pfile)] = [] except ValueError: # Not a valid PID, move on pass # Then we look at the open files for each PID files = {} for pid in pids: ppath = '/proc/{0}'.format(pid) try: tids = os.listdir('{0}/task'.format(ppath)) except OSError: continue # Collect the names of all of the file descriptors fd_ = [] #try: # fd_.append(os.path.realpath('{0}/task/{1}exe'.format(ppath, tid))) #except Exception: # pass for fpath in os.listdir('{0}/fd'.format(ppath)): fd_.append('{0}/fd/{1}'.format(ppath, fpath)) for tid in tids: try: fd_.append( os.path.realpath('{0}/task/{1}/exe'.format(ppath, tid)) ) except OSError: continue for tpath in os.listdir('{0}/task/{1}/fd'.format(ppath, tid)): fd_.append('{0}/task/{1}/fd/{2}'.format(ppath, tid, tpath)) fd_ = sorted(set(fd_)) # Loop through file descriptors and return useful data for each file for fdpath in fd_: # Sometimes PIDs and TIDs disappear before we can query them try: name = os.path.realpath(fdpath) # Running stat on the file cuts out all of the sockets and # deleted files from the list os.stat(name) except OSError: continue if name not in files: files[name] = [pid] else: # We still want to know which PIDs are using each file files[name].append(pid) files[name] = sorted(set(files[name])) pids[pid].append(name) pids[pid] = sorted(set(pids[pid])) if by_pid: return pids return files def pardir(): ''' Return the relative parent directory path symbol for underlying OS .. versionadded:: 2014.7.0 This can be useful when constructing Salt Formulas. .. code-block:: jinja {% set pardir = salt['file.pardir']() %} {% set final_path = salt['file.join']('subdir', pardir, 'confdir') %} CLI Example: .. code-block:: bash salt '*' file.pardir ''' return os.path.pardir def normpath(path): ''' Returns Normalize path, eliminating double slashes, etc. .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.normpath'](tpldir + '/../vars.jinja') import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.normpath 'a/b/c/..' ''' return os.path.normpath(path) def basename(path): ''' Returns the final component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- set filename = salt['file.basename'](source_file) %} CLI Example: .. code-block:: bash salt '*' file.basename 'test/test.config' ''' return os.path.basename(path) def dirname(path): ''' Returns the directory component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.dirname'](tpldir) + '/vars.jinja' import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.dirname 'test/path/filename.config' ''' return os.path.dirname(path) def join(*args): ''' Return a normalized file system path for the underlying OS .. versionadded:: 2014.7.0 This can be useful at the CLI but is frequently useful when scripting combining path variables: .. code-block:: jinja {% set www_root = '/var' %} {% set app_dir = 'myapp' %} myapp_config: file: - managed - name: {{ salt['file.join'](www_root, app_dir, 'config.yaml') }} CLI Example: .. code-block:: bash salt '*' file.join '/' 'usr' 'local' 'bin' ''' return os.path.join(*args) def move(src, dst): ''' Move a file or directory CLI Example: .. code-block:: bash salt '*' file.move /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('Source path must be absolute.') if not os.path.isabs(dst): raise SaltInvocationError('Destination path must be absolute.') ret = { 'result': True, 'comment': "'{0}' moved to '{1}'".format(src, dst), } try: shutil.move(src, dst) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move '{0}' to '{1}': {2}".format(src, dst, exc) ) return ret def diskusage(path): ''' Recursively calculate disk usage of path and return it in bytes CLI Example: .. code-block:: bash salt '*' file.diskusage /path/to/check ''' total_size = 0 seen = set() if os.path.isfile(path): stat_structure = os.stat(path) ret = stat_structure.st_size return ret for dirpath, dirnames, filenames in salt.utils.path.os_walk(path): for f in filenames: fp = os.path.join(dirpath, f) try: stat_structure = os.stat(fp) except OSError: continue if stat_structure.st_ino in seen: continue seen.add(stat_structure.st_ino) total_size += stat_structure.st_size ret = total_size return ret
saltstack/salt
salt/modules/file.py
get_group
python
def get_group(path, follow_symlinks=True): ''' Return the group that owns a given file path file or directory of which to get the group follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_group /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('group', False)
Return the group that owns a given file path file or directory of which to get the group follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_group /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L238-L257
[ "def stats(path, hash_type=None, follow_symlinks=True):\n '''\n Return a dict containing the stats for a given file\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' file.stats /etc/passwd\n '''\n path = os.path.expanduser(path)\n\n ret = {}\n if not os.path.exists(path):\n try:\n # Broken symlinks will return False for os.path.exists(), but still\n # have a uid and gid\n pstat = os.lstat(path)\n except OSError:\n # Not a broken symlink, just a nonexistent path\n # NOTE: The file.directory state checks the content of the error\n # message in this exception. Any changes made to the message for this\n # exception will reflect the file.directory state as well, and will\n # likely require changes there.\n raise CommandExecutionError('Path not found: {0}'.format(path))\n else:\n if follow_symlinks:\n pstat = os.stat(path)\n else:\n pstat = os.lstat(path)\n ret['inode'] = pstat.st_ino\n ret['uid'] = pstat.st_uid\n ret['gid'] = pstat.st_gid\n ret['group'] = gid_to_group(pstat.st_gid)\n ret['user'] = uid_to_user(pstat.st_uid)\n ret['atime'] = pstat.st_atime\n ret['mtime'] = pstat.st_mtime\n ret['ctime'] = pstat.st_ctime\n ret['size'] = pstat.st_size\n ret['mode'] = six.text_type(oct(stat.S_IMODE(pstat.st_mode)))\n if hash_type:\n ret['sum'] = get_hash(path, hash_type)\n ret['type'] = 'file'\n if stat.S_ISDIR(pstat.st_mode):\n ret['type'] = 'dir'\n if stat.S_ISCHR(pstat.st_mode):\n ret['type'] = 'char'\n if stat.S_ISBLK(pstat.st_mode):\n ret['type'] = 'block'\n if stat.S_ISREG(pstat.st_mode):\n ret['type'] = 'file'\n if stat.S_ISLNK(pstat.st_mode):\n ret['type'] = 'link'\n if stat.S_ISFIFO(pstat.st_mode):\n ret['type'] = 'pipe'\n if stat.S_ISSOCK(pstat.st_mode):\n ret['type'] = 'socket'\n ret['target'] = os.path.realpath(path)\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage information about regular files, directories, and special files on the minion, set/read user, group, mode, and data ''' # TODO: We should add the capability to do u+r type operations here # some time in the future from __future__ import absolute_import, print_function, unicode_literals # Import python libs import datetime import errno import fnmatch import io import itertools import logging import operator import os import re import shutil import stat import string import sys import tempfile import time import glob import hashlib import mmap from collections import Iterable, Mapping from functools import reduce # pylint: disable=redefined-builtin # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range, zip from salt.ext.six.moves.urllib.parse import urlparse as _urlparse # pylint: enable=import-error,no-name-in-module,redefined-builtin try: import grp import pwd except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.atomicfile import salt.utils.data import salt.utils.dictupdate import salt.utils.filebuffer import salt.utils.files import salt.utils.find import salt.utils.functools import salt.utils.hashutils import salt.utils.itertools import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.templates import salt.utils.url import salt.utils.user from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError, get_error_message as _get_error_message from salt.utils.files import HASHES, HASHES_REVMAP log = logging.getLogger(__name__) __func_alias__ = { 'makedirs_': 'makedirs' } def __virtual__(): ''' Only work on POSIX-like systems ''' # win_file takes care of windows if salt.utils.platform.is_windows(): return ( False, 'The file execution module cannot be loaded: only available on ' 'non-Windows systems - use win_file instead.' ) return True def __clean_tmp(sfn): ''' Clean out a template temp file ''' if sfn.startswith(os.path.join(tempfile.gettempdir(), salt.utils.files.TEMPFILE_PREFIX)): # Don't remove if it exists in file_roots (any saltenv) all_roots = itertools.chain.from_iterable( six.itervalues(__opts__['file_roots'])) in_roots = any(sfn.startswith(root) for root in all_roots) # Only clean up files that exist if os.path.exists(sfn) and not in_roots: os.remove(sfn) def _error(ret, err_msg): ''' Common function for setting error information for return dicts ''' ret['result'] = False ret['comment'] = err_msg return ret def _binary_replace(old, new): ''' This function does NOT do any diffing, it just checks the old and new files to see if either is binary, and provides an appropriate string noting the difference between the two files. If neither file is binary, an empty string is returned. This function should only be run AFTER it has been determined that the files differ. ''' old_isbin = not __utils__['files.is_text'](old) new_isbin = not __utils__['files.is_text'](new) if any((old_isbin, new_isbin)): if all((old_isbin, new_isbin)): return 'Replace binary file' elif old_isbin: return 'Replace binary file with text file' elif new_isbin: return 'Replace text file with binary file' return '' def _get_bkroot(): ''' Get the location of the backup dir in the minion cache ''' # Get the cachedir from the minion config return os.path.join(__salt__['config.get']('cachedir'), 'file_backup') def _splitlines_preserving_trailing_newline(str): ''' Returns a list of the lines in the string, breaking at line boundaries and preserving a trailing newline (if present). Essentially, this works like ``str.striplines(False)`` but preserves an empty line at the end. This is equivalent to the following code: .. code-block:: python lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') ''' lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') return lines def gid_to_group(gid): ''' Convert the group id to the group name on this system gid gid to convert to a group name CLI Example: .. code-block:: bash salt '*' file.gid_to_group 0 ''' try: gid = int(gid) except ValueError: # This is not an integer, maybe it's already the group name? gid = group_to_gid(gid) if gid == '': # Don't even bother to feed it to grp return '' try: return grp.getgrgid(gid).gr_name except (KeyError, NameError): # If group is not present, fall back to the gid. return gid def group_to_gid(group): ''' Convert the group to the gid on this system group group to convert to its gid CLI Example: .. code-block:: bash salt '*' file.group_to_gid root ''' if group is None: return '' try: if isinstance(group, int): return group return grp.getgrnam(group).gr_gid except KeyError: return '' def get_gid(path, follow_symlinks=True): ''' Return the id of the group that owns a given file path file or directory of which to get the gid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_gid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('gid', -1) def uid_to_user(uid): ''' Convert a uid to a user name uid uid to convert to a username CLI Example: .. code-block:: bash salt '*' file.uid_to_user 0 ''' try: return pwd.getpwuid(uid).pw_name except (KeyError, NameError): # If user is not present, fall back to the uid. return uid def user_to_uid(user): ''' Convert user name to a uid user user name to convert to its uid CLI Example: .. code-block:: bash salt '*' file.user_to_uid root ''' if user is None: user = salt.utils.user.get_user() try: if isinstance(user, int): return user return pwd.getpwnam(user).pw_uid except KeyError: return '' def get_uid(path, follow_symlinks=True): ''' Return the id of the user that owns a given file path file or directory of which to get the uid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_uid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('uid', -1) def get_user(path, follow_symlinks=True): ''' Return the user that owns a given file path file or directory of which to get the user follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_user /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('user', False) def get_mode(path, follow_symlinks=True): ''' Return the mode of a file path file or directory of which to get the mode follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_mode /etc/passwd .. versionchanged:: 2014.1.0 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('mode', '') def set_mode(path, mode): ''' Set the mode of a file path file or directory of which to set the mode mode mode to set the path to CLI Example: .. code-block:: bash salt '*' file.set_mode /etc/passwd 0644 ''' path = os.path.expanduser(path) mode = six.text_type(mode).lstrip('0Oo') if not mode: mode = '0' if not os.path.exists(path): raise CommandExecutionError('{0}: File not found'.format(path)) try: os.chmod(path, int(mode, 8)) except Exception: return 'Invalid Mode ' + mode return get_mode(path) def lchown(path, user, group): ''' Chown a file, pass the file the desired user and group without following symlinks. path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 return os.lchown(path, uid, gid) def chown(path, user, group): ''' Chown a file, pass the file the desired user and group path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 if not os.path.exists(path): try: # Broken symlinks will return false, but still need to be chowned return os.lchown(path, uid, gid) except OSError: pass err += 'File not found' if err: return err return os.chown(path, uid, gid) def chgrp(path, group): ''' Change the group of a file path path to the file or directory group group owner CLI Example: .. code-block:: bash salt '*' file.chgrp /etc/passwd root ''' path = os.path.expanduser(path) user = get_user(path) return chown(path, user, group) def _cmp_attrs(path, attrs): ''' .. versionadded:: 2018.3.0 Compare attributes of a given file to given attributes. Returns a pair (list) where first item are attributes to add and second item are to be removed. Please take into account when using this function that some minions will not have lsattr installed. path path to file to compare attributes with. attrs string of attributes to compare against a given file ''' diff = [None, None] # lsattr for AIX is not the same thing as lsattr for linux. if salt.utils.platform.is_aix(): return None try: lattrs = lsattr(path).get(path, '') except AttributeError: # lsattr not installed return None old = [chr for chr in lattrs if chr not in attrs] if old: diff[1] = ''.join(old) new = [chr for chr in attrs if chr not in lattrs] if new: diff[0] = ''.join(new) return diff def lsattr(path): ''' .. versionadded:: 2018.3.0 .. versionchanged:: 2018.3.1 If ``lsattr`` is not installed on the system, ``None`` is returned. .. versionchanged:: 2018.3.4 If on ``AIX``, ``None`` is returned even if in filesystem as lsattr on ``AIX`` is not the same thing as the linux version. Obtain the modifiable attributes of the given file. If path is to a directory, an empty list is returned. path path to file to obtain attributes of. File/directory must exist. CLI Example: .. code-block:: bash salt '*' file.lsattr foo1.txt ''' if not salt.utils.path.which('lsattr') or salt.utils.platform.is_aix(): return None if not os.path.exists(path): raise SaltInvocationError("File or directory does not exist: " + path) cmd = ['lsattr', path] result = __salt__['cmd.run'](cmd, ignore_retcode=True, python_shell=False) results = {} for line in result.splitlines(): if not line.startswith('lsattr: '): vals = line.split(None, 1) results[vals[1]] = re.findall(r"[aAcCdDeijPsStTu]", vals[0]) return results def chattr(*files, **kwargs): ''' .. versionadded:: 2018.3.0 Change the attributes of files. This function accepts one or more files and the following options: operator Can be wither ``add`` or ``remove``. Determines whether attributes should be added or removed from files attributes One or more of the following characters: ``aAcCdDeijPsStTu``, representing attributes to add to/remove from files version a version number to assign to the file(s) flags One or more of the following characters: ``RVf``, representing flags to assign to chattr (recurse, verbose, suppress most errors) CLI Example: .. code-block:: bash salt '*' file.chattr foo1.txt foo2.txt operator=add attributes=ai salt '*' file.chattr foo3.txt operator=remove attributes=i version=2 ''' operator = kwargs.pop('operator', None) attributes = kwargs.pop('attributes', None) flags = kwargs.pop('flags', None) version = kwargs.pop('version', None) if (operator is None) or (operator not in ('add', 'remove')): raise SaltInvocationError( "Need an operator: 'add' or 'remove' to modify attributes.") if attributes is None: raise SaltInvocationError("Need attributes: [aAcCdDeijPsStTu]") cmd = ['chattr'] if operator == "add": attrs = '+{0}'.format(attributes) elif operator == "remove": attrs = '-{0}'.format(attributes) cmd.append(attrs) if flags is not None: cmd.append('-{0}'.format(flags)) if version is not None: cmd.extend(['-v', version]) cmd.extend(files) result = __salt__['cmd.run'](cmd, python_shell=False) if bool(result): raise CommandExecutionError( "chattr failed to run, possibly due to bad parameters.") return True def get_sum(path, form='sha256'): ''' Return the checksum for the given file. The following checksum algorithms are supported: * md5 * sha1 * sha224 * sha256 **(default)** * sha384 * sha512 path path to the file or directory form desired sum format CLI Example: .. code-block:: bash salt '*' file.get_sum /etc/passwd sha512 ''' path = os.path.expanduser(path) if not os.path.isfile(path): return 'File not found' return salt.utils.hashutils.get_hash(path, form, 4096) def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` path path to the file or directory form desired sum format chunk_size amount to sum at once CLI Example: .. code-block:: bash salt '*' file.get_hash /etc/shadow ''' return salt.utils.hashutils.get_hash(os.path.expanduser(path), form, chunk_size) def get_source_sum(file_name='', source='', source_hash=None, source_hash_name=None, saltenv='base'): ''' .. versionadded:: 2016.11.0 Used by :py:func:`file.get_managed <salt.modules.file.get_managed>` to obtain the hash and hash type from the parameters specified below. file_name Optional file name being managed, for matching with :py:func:`file.extract_hash <salt.modules.file.extract_hash>`. source Source file, as used in :py:mod:`file <salt.states.file>` and other states. If ``source_hash`` refers to a file containing hashes, then this filename will be used to match a filename in that file. If the ``source_hash`` is a hash expression, then this argument will be ignored. source_hash Hash file/expression, as used in :py:mod:`file <salt.states.file>` and other states. If this value refers to a remote URL or absolute path to a local file, it will be cached and :py:func:`file.extract_hash <salt.modules.file.extract_hash>` will be used to obtain a hash from it. source_hash_name Specific file name to look for when ``source_hash`` refers to a remote file, used to disambiguate ambiguous matches. saltenv : base Salt fileserver environment from which to retrieve the source_hash. This value will only be used when ``source_hash`` refers to a file on the Salt fileserver (i.e. one beginning with ``salt://``). CLI Example: .. code-block:: bash salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=499ae16dcae71eeb7c3a30c75ea7a1a6 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 source_hash_name=./dir2/foo.tar.gz ''' def _invalid_source_hash_format(): ''' DRY helper for reporting invalid source_hash input ''' raise CommandExecutionError( 'Source hash {0} format is invalid. The supported formats are: ' '1) a hash, 2) an expression in the format <hash_type>=<hash>, or ' '3) either a path to a local file containing hashes, or a URI of ' 'a remote hash file. Supported protocols for remote hash files ' 'are: {1}. The hash may also not be of a valid length, the ' 'following are supported hash types and lengths: {2}.'.format( source_hash, ', '.join(salt.utils.files.VALID_PROTOS), ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) hash_fn = None if os.path.isabs(source_hash): hash_fn = source_hash else: try: proto = _urlparse(source_hash).scheme if proto in salt.utils.files.VALID_PROTOS: hash_fn = __salt__['cp.cache_file'](source_hash, saltenv) if not hash_fn: raise CommandExecutionError( 'Source hash file {0} not found'.format(source_hash) ) else: if proto != '': # Some unsupported protocol (e.g. foo://) is being used. # We'll get into this else block if a hash expression # (like md5=<md5 checksum here>), but in those cases, the # protocol will be an empty string, in which case we avoid # this error condition. _invalid_source_hash_format() except (AttributeError, TypeError): _invalid_source_hash_format() if hash_fn is not None: ret = extract_hash(hash_fn, '', file_name, source, source_hash_name) if ret is None: _invalid_source_hash_format() ret['hsum'] = ret['hsum'].lower() return ret else: # The source_hash is a hash expression ret = {} try: ret['hash_type'], ret['hsum'] = \ [x.strip() for x in source_hash.split('=', 1)] except AttributeError: _invalid_source_hash_format() except ValueError: # No hash type, try to figure out by hash length if not re.match('^[{0}]+$'.format(string.hexdigits), source_hash): _invalid_source_hash_format() ret['hsum'] = source_hash source_hash_len = len(source_hash) if source_hash_len in HASHES_REVMAP: ret['hash_type'] = HASHES_REVMAP[source_hash_len] else: _invalid_source_hash_format() if ret['hash_type'] not in HASHES: raise CommandExecutionError( 'Invalid hash type \'{0}\'. Supported hash types are: {1}. ' 'Either remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to a supported type.' .format(ret['hash_type'], ', '.join(HASHES), ret['hsum']) ) else: hsum_len = len(ret['hsum']) if hsum_len not in HASHES_REVMAP: _invalid_source_hash_format() elif hsum_len != HASHES[ret['hash_type']]: raise CommandExecutionError( 'Invalid length ({0}) for hash type \'{1}\'. Either ' 'remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to \'{3}\''.format( hsum_len, ret['hash_type'], ret['hsum'], HASHES_REVMAP[hsum_len], ) ) ret['hsum'] = ret['hsum'].lower() return ret def check_hash(path, file_hash): ''' Check if a file matches the given hash string Returns ``True`` if the hash matches, otherwise ``False``. path Path to a file local to the minion. hash The hash to check against the file specified in the ``path`` argument. .. versionchanged:: 2016.11.4 For this and newer versions the hash can be specified without an accompanying hash type (e.g. ``e138491e9d5b97023cea823fe17bac22``), but for earlier releases it is necessary to also specify the hash type in the format ``<hash_type>=<hash_value>`` (e.g. ``md5=e138491e9d5b97023cea823fe17bac22``). CLI Example: .. code-block:: bash salt '*' file.check_hash /etc/fstab e138491e9d5b97023cea823fe17bac22 salt '*' file.check_hash /etc/fstab md5=e138491e9d5b97023cea823fe17bac22 ''' path = os.path.expanduser(path) if not isinstance(file_hash, six.string_types): raise SaltInvocationError('hash must be a string') for sep in (':', '='): if sep in file_hash: hash_type, hash_value = file_hash.split(sep, 1) break else: hash_value = file_hash hash_len = len(file_hash) hash_type = HASHES_REVMAP.get(hash_len) if hash_type is None: raise SaltInvocationError( 'Hash {0} (length: {1}) could not be matched to a supported ' 'hash type. The supported hash types and lengths are: ' '{2}'.format( file_hash, hash_len, ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) return get_hash(path, hash_type) == hash_value def find(path, *args, **kwargs): ''' Approximate the Unix ``find(1)`` command and return a list of paths that meet the specified criteria. The options include match criteria: .. code-block:: text name = path-glob # case sensitive iname = path-glob # case insensitive regex = path-regex # case sensitive iregex = path-regex # case insensitive type = file-types # match any listed type user = users # match any listed user group = groups # match any listed group size = [+-]number[size-unit] # default unit = byte mtime = interval # modified since date grep = regex # search file contents and/or actions: .. code-block:: text delete [= file-types] # default type = 'f' exec = command [arg ...] # where {} is replaced by pathname print [= print-opts] and/or depth criteria: .. code-block:: text maxdepth = maximum depth to transverse in path mindepth = minimum depth to transverse before checking files or directories The default action is ``print=path`` ``path-glob``: .. code-block:: text * = match zero or more chars ? = match any char [abc] = match a, b, or c [!abc] or [^abc] = match anything except a, b, and c [x-y] = match chars x through y [!x-y] or [^x-y] = match anything except chars x through y {a,b,c} = match a or b or c ``path-regex``: a Python Regex (regular expression) pattern to match pathnames ``file-types``: a string of one or more of the following: .. code-block:: text a: all file types b: block device c: character device d: directory p: FIFO (named pipe) f: plain file l: symlink s: socket ``users``: a space and/or comma separated list of user names and/or uids ``groups``: a space and/or comma separated list of group names and/or gids ``size-unit``: .. code-block:: text b: bytes k: kilobytes m: megabytes g: gigabytes t: terabytes interval: .. code-block:: text [<num>w] [<num>d] [<num>h] [<num>m] [<num>s] where: w: week d: day h: hour m: minute s: second print-opts: a comma and/or space separated list of one or more of the following: .. code-block:: text group: group name md5: MD5 digest of file contents mode: file permissions (as integer) mtime: last modification time (as time_t) name: file basename path: file absolute path size: file size in bytes type: file type user: user name CLI Examples: .. code-block:: bash salt '*' file.find / type=f name=\\*.bak size=+10m salt '*' file.find /var mtime=+30d size=+10m print=path,size,mtime salt '*' file.find /var/log name=\\*.[0-9] mtime=+30d size=+10m delete ''' if 'delete' in args: kwargs['delete'] = 'f' elif 'print' in args: kwargs['print'] = 'path' try: finder = salt.utils.find.Finder(kwargs) except ValueError as ex: return 'error: {0}'.format(ex) ret = [item for i in [finder.find(p) for p in glob.glob(os.path.expanduser(path))] for item in i] ret.sort() return ret def _sed_esc(string, escape_all=False): ''' Escape single quotes and forward slashes ''' special_chars = "^.[$()|*+?{" string = string.replace("'", "'\"'\"'").replace("/", "\\/") if escape_all is True: for char in special_chars: string = string.replace(char, "\\" + char) return string def sed(path, before, after, limit='', backup='.bak', options='-r -e', flags='g', escape_all=False, negate_match=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup options : ``-r -e`` Options to pass to sed flags : ``g`` Flags to modify the sed search; e.g., ``i`` for case-insensitive pattern matching negate_match : False Negate the search command (``!``) .. versionadded:: 0.17.0 Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # path = os.path.expanduser(path) if not os.path.exists(path): return False # Mandate that before and after are strings before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.append('-i{0}'.format(backup) if backup else '-i') cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}{negate_match}s/{before}/{after}/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', negate_match='!' if negate_match else '', before=before, after=after, flags=flags ) ) cmd.append(path) return __salt__['cmd.run_all'](cmd, python_shell=False) def sed_contains(path, text, limit='', flags='g'): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the file at ``path`` contains ``text``. Utilizes sed to perform the search (line-wise search). Note: the ``p`` flag will be added to any flags you pass in. CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' # Largely inspired by Fabric's contrib.files.contains() path = os.path.expanduser(path) if not os.path.exists(path): return False before = _sed_esc(six.text_type(text), False) limit = _sed_esc(six.text_type(limit), False) options = '-n -r -e' if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}s/{before}/$/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', before=before, flags='p{0}'.format(flags) ) ) cmd.append(path) result = __salt__['cmd.run'](cmd, python_shell=False) return bool(result) def psed(path, before, after, limit='', backup='.bak', flags='gMS', escape_all=False, multi=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file (pure Python version) Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup flags : ``gMS`` Flags to modify the search. Valid values are: - ``g``: Replace all occurrences of the pattern, not just the first. - ``I``: Ignore case. - ``L``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\s`` and ``\\S`` dependent on the locale. - ``M``: Treat multiple lines as a single line. - ``S``: Make `.` match all characters, including newlines. - ``U``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\d``, ``\\D``, ``\\s`` and ``\\S`` dependent on Unicode. - ``X``: Verbose (whitespace is ignored). multi: ``False`` If True, treat the entire file as a single line Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # # Mandate that before and after are strings path = os.path.expanduser(path) multi = bool(multi) before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) # The pattern to replace with does not need to be escaped!!! # after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) shutil.copy2(path, '{0}{1}'.format(path, backup)) with salt.utils.files.fopen(path, 'w') as ofile: with salt.utils.files.fopen('{0}{1}'.format(path, backup), 'r') as ifile: if multi is True: for line in ifile.readline(): ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(line), before, after, limit, flags ) ) ) else: ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(ifile.read()), before, after, limit, flags ) ) ) RE_FLAG_TABLE = {'I': re.I, 'L': re.L, 'M': re.M, 'S': re.S, 'U': re.U, 'X': re.X} def _psed(text, before, after, limit, flags): ''' Does the actual work for file.psed, so that single lines can be passed in ''' atext = text if limit: limit = re.compile(limit) comps = text.split(limit) atext = ''.join(comps[1:]) count = 1 if 'g' in flags: count = 0 flags = flags.replace('g', '') aflags = 0 for flag in flags: aflags |= RE_FLAG_TABLE[flag] before = re.compile(before, flags=aflags) text = re.sub(before, after, atext, count=count) return text def uncomment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Uncomment specified commented lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be uncommented. This regex should not include the comment character. A leading ``^`` character will be stripped for convenience (for easily switching between comment() and uncomment()). char : ``#`` The character to remove in order to uncomment a line backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup CLI Example: .. code-block:: bash salt '*' file.uncomment /etc/hosts.deny 'ALL: PARANOID' ''' return comment_line(path=path, regex=regex, char=char, cmnt=False, backup=backup) def comment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Comment out specified lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be commented; this pattern will be wrapped in parenthesis and will move any preceding/trailing ``^`` or ``$`` characters outside the parenthesis (e.g., the pattern ``^foo$`` will be rewritten as ``^(foo)$``) char : ``#`` The character to be inserted at the beginning of a line in order to comment it out backup : ``.bak`` The file will be backed up before edit with this file extension .. warning:: This backup will be overwritten each time ``sed`` / ``comment`` / ``uncomment`` is called. Meaning the backup will only be useful after the first invocation. CLI Example: .. code-block:: bash salt '*' file.comment /etc/modules pcspkr ''' return comment_line(path=path, regex=regex, char=char, cmnt=True, backup=backup) def comment_line(path, regex, char='#', cmnt=True, backup='.bak'): r''' Comment or Uncomment a line in a text file. :param path: string The full path to the text file. :param regex: string A regex expression that begins with ``^`` that will find the line you wish to comment. Can be as simple as ``^color =`` :param char: string The character used to comment a line in the type of file you're referencing. Default is ``#`` :param cmnt: boolean True to comment the line. False to uncomment the line. Default is True. :param backup: string The file extension to give the backup file. Default is ``.bak`` Set to False/None to not keep a backup. :return: boolean Returns True if successful, False if not CLI Example: The following example will comment out the ``pcspkr`` line in the ``/etc/modules`` file using the default ``#`` character and create a backup file named ``modules.bak`` .. code-block:: bash salt '*' file.comment_line '/etc/modules' '^pcspkr' CLI Example: The following example will uncomment the ``log_level`` setting in ``minion`` config file if it is set to either ``warning``, ``info``, or ``debug`` using the ``#`` character and create a backup file named ``minion.bk`` .. code-block:: bash salt '*' file.comment_line 'C:\salt\conf\minion' '^log_level: (warning|info|debug)' '#' False '.bk' ''' # Get the regex for comment or uncomment if cmnt: regex = '{0}({1}){2}'.format( '^' if regex.startswith('^') else '', regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') else: regex = r'^{0}\s*({1}){2}'.format( char, regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') # Load the real path to the file path = os.path.realpath(os.path.expanduser(path)) # Make sure the file exists if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) # Make sure it is a text file if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}'.format(path)) # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes found = False # Dictionaries for comparing changes orig_file = [] new_file = [] # Buffer size for fopen bufsize = os.path.getsize(path) try: # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: # Is it in this line line = salt.utils.stringutils.to_unicode(line) if re.match(regex, line): # Load lines into dictionaries, set found to True orig_file.append(line) if cmnt: new_file.append('{0}{1}'.format(char, line)) else: new_file.append(line.lstrip(char)) found = True except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) # We've searched the whole file. If we didn't find anything, return False if not found: return False if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Create a copy to read from and to use as a backup later try: temp_file = _mkstemp_copy(path=path, preserve_inode=False) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) try: # Open the file in write mode mode = 'wb' if six.PY2 and salt.utils.platform.is_windows() else 'w' with salt.utils.files.fopen(path, mode=mode, buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: line = salt.utils.stringutils.to_unicode(line) try: # Is it in this line if re.match(regex, line): # Write the new line if cmnt: wline = '{0}{1}'.format(char, line) else: wline = line.lstrip(char) else: # Write the existing line (no change) wline = line wline = salt.utils.stringutils.to_bytes(wline) \ if six.PY2 and salt.utils.platform.is_windows() \ else salt.utils.stringutils.to_str(wline) w_file.write(wline) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if backup: # Move the backup file to the original directory backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: os.remove(temp_file) if not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) # Return a diff using the two dictionaries return __utils__['stringutils.get_diff'](orig_file, new_file) def _get_flags(flags): ''' Return an integer appropriate for use as a flag for the re module from a list of human-readable strings .. code-block:: python >>> _get_flags(['MULTILINE', 'IGNORECASE']) 10 >>> _get_flags('MULTILINE') 8 >>> _get_flags(2) 2 ''' if isinstance(flags, six.string_types): flags = [flags] if isinstance(flags, Iterable) and not isinstance(flags, Mapping): _flags_acc = [] for flag in flags: _flag = getattr(re, six.text_type(flag).upper()) if not isinstance(_flag, six.integer_types): raise SaltInvocationError( 'Invalid re flag given: {0}'.format(flag) ) _flags_acc.append(_flag) return reduce(operator.__or__, _flags_acc) elif isinstance(flags, six.integer_types): return flags else: raise SaltInvocationError( 'Invalid re flags: "{0}", must be given either as a single flag ' 'string, a list of strings, or as an integer'.format(flags) ) def _add_flags(flags, new_flags): ''' Combine ``flags`` and ``new_flags`` ''' flags = _get_flags(flags) new_flags = _get_flags(new_flags) return flags | new_flags def _mkstemp_copy(path, preserve_inode=True): ''' Create a temp file and move/copy the contents of ``path`` to the temp file. Return the path to the temp file. path The full path to the file whose contents will be moved/copied to a temp file. Whether it's moved or copied depends on the value of ``preserve_inode``. preserve_inode Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). Default is ``True``. ''' temp_file = None # Create the temp file try: temp_file = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to create temp file. " "Exception: {0}".format(exc) ) # use `copy` to preserve the inode of the # original file, and thus preserve hardlinks # to the inode. otherwise, use `move` to # preserve prior behavior, which results in # writing the file to a new inode. if preserve_inode: try: shutil.copy2(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to copy file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: try: shutil.move(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) return temp_file def _starts_till(src, probe, strip_comments=True): ''' Returns True if src and probe at least matches at the beginning till some point. ''' def _strip_comments(txt): ''' Strip possible comments. Usually comments are one or two symbols at the beginning of the line, separated with space ''' buff = txt.split(" ", 1) return len(buff) == 2 and len(buff[0]) < 2 and buff[1] or txt def _to_words(txt): ''' Split by words ''' return txt and [w for w in txt.strip().split(" ") if w.strip()] or txt no_match = -1 equal = 0 if not src or not probe: return no_match src = src.rstrip('\n\r') probe = probe.rstrip('\n\r') if src == probe: return equal src = _to_words(strip_comments and _strip_comments(src) or src) probe = _to_words(strip_comments and _strip_comments(probe) or probe) a_buff, b_buff = len(src) < len(probe) and (src, probe) or (probe, src) b_buff = ' '.join(b_buff) for idx in range(len(a_buff)): prb = ' '.join(a_buff[:-(idx + 1)]) if prb and b_buff.startswith(prb): return idx return no_match def _regex_to_static(src, regex): ''' Expand regular expression to static match. ''' if not src or not regex: return None try: compiled = re.compile(regex, re.DOTALL) src = [line for line in src if compiled.search(line) or line.count(regex)] except Exception as ex: raise CommandExecutionError("{0}: '{1}'".format(_get_error_message(ex), regex)) return src and src or [] def _assert_occurrence(probe, target, amount=1): ''' Raise an exception, if there are different amount of specified occurrences in src. ''' occ = len(probe) if occ > amount: msg = 'more than' elif occ < amount: msg = 'less than' elif not occ: msg = 'no' else: msg = None if msg: raise CommandExecutionError('Found {0} expected occurrences in "{1}" expression'.format(msg, target)) return occ def _set_line_indent(src, line, indent): ''' Indent the line with the source line. ''' if not indent: return line idt = [] for c in src: if c not in ['\t', ' ']: break idt.append(c) return ''.join(idt) + line.lstrip() def _get_eol(line): match = re.search('((?<!\r)\n|\r(?!\n)|\r\n)$', line) return match and match.group() or '' def _set_line_eol(src, line): ''' Add line ending ''' line_ending = _get_eol(src) or os.linesep return line.rstrip() + line_ending def _insert_line_before(idx, body, content, indent): if not idx or (idx and _starts_till(body[idx - 1], content) < 0): cnd = _set_line_indent(body[idx], content, indent) body.insert(idx, cnd) return body def _insert_line_after(idx, body, content, indent): # No duplicates or append, if "after" is the last line next_line = idx + 1 < len(body) and body[idx + 1] or None if next_line is None or _starts_till(next_line, content) < 0: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) return body def line(path, content=None, match=None, mode=None, location=None, before=None, after=None, show_changes=True, backup=False, quiet=False, indent=True): ''' .. versionadded:: 2015.8.0 Edit a line in the configuration file. The ``path`` and ``content`` arguments are required, as well as passing in one of the ``mode`` options. path Filesystem path to the file to be edited. content Content of the line. Allowed to be empty if mode=delete. match Match the target line for an action by a fragment of a string or regular expression. If neither ``before`` nor ``after`` are provided, and ``match`` is also ``None``, match becomes the ``content`` value. mode Defines how to edit a line. One of the following options is required: - ensure If line does not exist, it will be added. This is based on the ``content`` argument. - replace If line already exists, it will be replaced. - delete Delete the line, once found. - insert Insert a line. .. note:: If ``mode=insert`` is used, at least one of the following options must also be defined: ``location``, ``before``, or ``after``. If ``location`` is used, it takes precedence over the other two options. location Defines where to place content in the line. Note this option is only used when ``mode=insert`` is specified. If a location is passed in, it takes precedence over both the ``before`` and ``after`` kwargs. Valid locations are: - start Place the content at the beginning of the file. - end Place the content at the end of the file. before Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. after Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. show_changes Output a unified diff of the old file and the new file. If ``False`` return a boolean if any changes were made. Default is ``True`` .. note:: Using this option will store two copies of the file in-memory (the original version and the edited version) in order to generate the diff. backup Create a backup of the original file with the extension: "Year-Month-Day-Hour-Minutes-Seconds". quiet Do not raise any exceptions. E.g. ignore the fact that the file that is tried to be edited does not exist and nothing really happened. indent Keep indentation with the previous line. This option is not considered when the ``delete`` mode is specified. CLI Example: .. code-block:: bash salt '*' file.line /etc/nsswitch.conf "networks:\tfiles dns" after="hosts:.*?" mode='ensure' .. note:: If an equal sign (``=``) appears in an argument to a Salt command, it is interpreted as a keyword argument in the format of ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.line /path/to/file content="CREATEMAIL_SPOOL=no" match="CREATE_MAIL_SPOOL=yes" mode="replace" ''' path = os.path.realpath(os.path.expanduser(path)) if not os.path.isfile(path): if not quiet: raise CommandExecutionError('File "{0}" does not exists or is not a file.'.format(path)) return False # No changes had happened mode = mode and mode.lower() or mode if mode not in ['insert', 'ensure', 'delete', 'replace']: if mode is None: raise CommandExecutionError('Mode was not defined. How to process the file?') else: raise CommandExecutionError('Unknown mode: "{0}"'.format(mode)) # We've set the content to be empty in the function params but we want to make sure # it gets passed when needed. Feature #37092 empty_content_modes = ['delete'] if mode not in empty_content_modes and content is None: raise CommandExecutionError('Content can only be empty if mode is "{0}"'.format(', '.join(empty_content_modes))) del empty_content_modes # Before/after has privilege. If nothing defined, match is used by content. if before is None and after is None and not match: match = content with salt.utils.files.fopen(path, mode='r') as fp_: body = salt.utils.data.decode_list(fp_.readlines()) body_before = hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() # Add empty line at the end if last line ends with eol. # Allows simpler code if body and _get_eol(body[-1]): body.append('') after = _regex_to_static(body, after) before = _regex_to_static(body, before) match = _regex_to_static(body, match) if os.stat(path).st_size == 0 and mode in ('delete', 'replace'): log.warning('Cannot find text to %s. File \'%s\' is empty.', mode, path) body = [] elif mode == 'delete' and match: body = [line for line in body if line != match[0]] elif mode == 'replace' and match: idx = body.index(match[0]) file_line = body.pop(idx) body.insert(idx, _set_line_indent(file_line, content, indent)) elif mode == 'insert': if not location and not before and not after: raise CommandExecutionError('On insert must be defined either "location" or "before/after" conditions.') if not location: if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') out = [] in_range = False for line in body: if line == after[0]: in_range = True elif line == before[0] and in_range: cnd = _set_line_indent(line, content, indent) out.append(cnd) out.append(line) body = out if before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif after and not before: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: if location == 'start': if body: body.insert(0, _set_line_eol(body[0], content)) else: body.append(content + os.linesep) elif location == 'end': body.append(_set_line_indent(body[-1], content, indent) if body else content) elif mode == 'ensure': if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') is_there = bool([l for l in body if l.count(content)]) if not is_there: idx = body.index(after[0]) if idx < (len(body) - 1) and body[idx + 1] == before[0]: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) else: raise CommandExecutionError('Found more than one line between ' 'boundaries "before" and "after".') elif before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif not before and after: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: raise CommandExecutionError("Wrong conditions? " "Unable to ensure line without knowing " "where to put it before and/or after.") if body: for idx, line in enumerate(body): if not _get_eol(line) and idx+1 < len(body): prev = idx and idx-1 or 1 body[idx] = _set_line_eol(body[prev], line) # We do not need empty line at the end anymore if '' == body[-1]: body.pop() changed = body_before != hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() if backup and changed and __opts__['test'] is False: try: temp_file = _mkstemp_copy(path=path, preserve_inode=True) shutil.move(temp_file, '{0}.{1}'.format(path, time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime()))) except (OSError, IOError) as exc: raise CommandExecutionError("Unable to create the backup file of {0}. Exception: {1}".format(path, exc)) changes_diff = None if changed: if show_changes: with salt.utils.files.fopen(path, 'r') as fp_: path_content = salt.utils.data.decode_list(fp_.read().splitlines(True)) changes_diff = __utils__['stringutils.get_diff'](path_content, body) if __opts__['test'] is False: fh_ = None try: # Make sure we match the file mode from salt.utils.files.fopen if six.PY2 and salt.utils.platform.is_windows(): mode = 'wb' body = salt.utils.data.encode_list(body) else: mode = 'w' body = salt.utils.data.decode_list(body, to_str=True) fh_ = salt.utils.atomicfile.atomic_open(path, mode) fh_.writelines(body) finally: if fh_: fh_.close() return show_changes and changes_diff or changed def replace(path, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, backup='.bak', dry_run=False, search_only=False, show_changes=True, ignore_if_missing=False, preserve_inode=True, backslash_literal=False, ): ''' .. versionadded:: 0.17.0 Replace occurrences of a pattern in a file. If ``show_changes`` is ``True``, then a diff of what changed will be returned, otherwise a ``True`` will be returned when changes are made, and ``False`` when no changes are made. This is a pure Python implementation that wraps Python's :py:func:`~re.sub`. path Filesystem path to the file to be edited. If a symlink is specified, it will be resolved to its target. pattern A regular expression, to be matched using Python's :py:func:`~re.search`. repl The replacement text count : 0 Maximum number of pattern occurrences to be replaced. If count is a positive integer ``n``, only ``n`` occurrences will be replaced, otherwise all occurrences will be replaced. flags (list or int) A list of flags defined in the ``re`` module documentation from the Python standard library. Each list item should be a string that will correlate to the human-friendly flag name. E.g., ``['IGNORECASE', 'MULTILINE']``. Optionally, ``flags`` may be an int, with a value corresponding to the XOR (``|``) of all the desired flags. Defaults to 8 (which supports 'MULTILINE'). bufsize (int or str) How much of the file to buffer into memory at once. The default value ``1`` processes one line at a time. The special value ``file`` may be specified which will read the entire file into memory before processing. append_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True``, and pattern is not found, then the content will be appended to the file. prepend_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True`` and pattern is not found, then the content will be prepended to the file. not_found_content .. versionadded:: 2014.7.0 Content to use for append/prepend if not found. If None (default), uses ``repl``. Useful when ``repl`` uses references to group in pattern. backup : .bak The file extension to use for a backup of the file before editing. Set to ``False`` to skip making a backup. dry_run : False If set to ``True``, no changes will be made to the file, the function will just return the changes that would have been made (or a ``True``/``False`` value if ``show_changes`` is set to ``False``). search_only : False If set to true, this no changes will be performed on the file, and this function will simply return ``True`` if the pattern was matched, and ``False`` if not. show_changes : True If ``True``, return a diff of changes made. Otherwise, return ``True`` if changes were made, and ``False`` if not. .. note:: Using this option will store two copies of the file in memory (the original version and the edited version) in order to generate the diff. This may not normally be a concern, but could impact performance if used with large files. ignore_if_missing : False .. versionadded:: 2015.8.0 If set to ``True``, this function will simply return ``False`` if the file doesn't exist. Otherwise, an error will be thrown. preserve_inode : True .. versionadded:: 2015.8.0 Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). backslash_literal : False .. versionadded:: 2016.11.7 Interpret backslashes as literal backslashes for the repl and not escape characters. This will help when using append/prepend so that the backslashes are not interpreted for the repl on the second run of the state. If an equal sign (``=``) appears in an argument to a Salt command it is interpreted as a keyword argument in the format ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.replace /path/to/file pattern='=' repl=':' salt '*' file.replace /path/to/file pattern="bind-address\\s*=" repl='bind-address:' CLI Examples: .. code-block:: bash salt '*' file.replace /etc/httpd/httpd.conf pattern='LogLevel warn' repl='LogLevel info' salt '*' file.replace /some/file pattern='before' repl='after' flags='[MULTILINE, IGNORECASE]' ''' symlink = False if is_link(path): symlink = True target_path = os.readlink(path) given_path = os.path.expanduser(path) path = os.path.realpath(os.path.expanduser(path)) if not os.path.exists(path): if ignore_if_missing: return False else: raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if search_only and (append_if_not_found or prepend_if_not_found): raise SaltInvocationError( 'search_only cannot be used with append/prepend_if_not_found' ) if append_if_not_found and prepend_if_not_found: raise SaltInvocationError( 'Only one of append and prepend_if_not_found is permitted' ) flags_num = _get_flags(flags) cpattern = re.compile(salt.utils.stringutils.to_bytes(pattern), flags_num) filesize = os.path.getsize(path) if bufsize == 'file': bufsize = filesize # Search the file; track if any changes have been made for the return val has_changes = False orig_file = [] # used for show_changes and change detection new_file = [] # used for show_changes and change detection if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Avoid TypeErrors by forcing repl to be bytearray related to mmap # Replacement text may contains integer: 123 for example repl = salt.utils.stringutils.to_bytes(six.text_type(repl)) if not_found_content: not_found_content = salt.utils.stringutils.to_bytes(not_found_content) found = False temp_file = None content = salt.utils.stringutils.to_unicode(not_found_content) \ if not_found_content and (prepend_if_not_found or append_if_not_found) \ else salt.utils.stringutils.to_unicode(repl) try: # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes r_data = None # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: try: # mmap throws a ValueError if the file is empty. r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) except (ValueError, mmap.error): # size of file in /proc is 0, but contains data r_data = salt.utils.stringutils.to_bytes("".join(r_file)) if search_only: # Just search; bail as early as a match is found if re.search(cpattern, r_data): return True # `with` block handles file closure else: return False else: result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) # found anything? (even if no change) if nrepl > 0: found = True # Identity check the potential change has_changes = True if pattern != repl else has_changes if prepend_if_not_found or append_if_not_found: # Search for content, to avoid pre/appending the # content if it was pre/appended in a previous run. if re.search(salt.utils.stringutils.to_bytes('^{0}($|(?=\r\n))'.format(re.escape(content))), r_data, flags=flags_num): # Content was found, so set found. found = True orig_file = r_data.read(filesize).splitlines(True) \ if isinstance(r_data, mmap.mmap) \ else r_data.splitlines(True) new_file = result.splitlines(True) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() if has_changes and not dry_run: # Write the replacement text in this block. try: # Create a copy to read from and to use as a backup later temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) r_data = None try: # Open the file in write mode with salt.utils.files.fopen(path, mode='w', buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='r', buffering=bufsize) as r_file: r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) try: w_file.write(salt.utils.stringutils.to_str(result)) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if not found and (append_if_not_found or prepend_if_not_found): if not_found_content is None: not_found_content = repl if prepend_if_not_found: new_file.insert(0, not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) else: # append_if_not_found # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(salt.utils.stringutils.to_bytes(os.linesep)): new_file[-1] += salt.utils.stringutils.to_bytes(os.linesep) new_file.append(not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) has_changes = True if not dry_run: try: # Create a copy to read from and for later use as a backup temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line)) finally: fh_.close() if backup and has_changes and not dry_run: # keep the backup only if it was requested # and only if there were any changes backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) if symlink: symlink_backup = '{0}{1}'.format(given_path, backup) target_backup = '{0}{1}'.format(target_path, backup) # Always clobber any existing symlink backup # to match the behaviour of the 'backup' option try: os.symlink(target_backup, symlink_backup) except OSError: os.remove(symlink_backup) os.symlink(target_backup, symlink_backup) except Exception: raise CommandExecutionError( "Unable create backup symlink '{0}'. " "Target was '{1}'. " "Exception: {2}".format(symlink_backup, target_backup, exc) ) elif temp_file: try: os.remove(temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to delete temp file '{0}'. " "Exception: {1}".format(temp_file, exc) ) if not dry_run and not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) differences = __utils__['stringutils.get_diff'](orig_file, new_file) if show_changes: return differences # We may have found a regex line match but don't need to change the line # (for situations where the pattern also matches the repl). Revert the # has_changes flag to False if the final result is unchanged. if not differences: has_changes = False return has_changes def blockreplace(path, marker_start='#-- start managed zone --', marker_end='#-- end managed zone --', content='', append_if_not_found=False, prepend_if_not_found=False, backup='.bak', dry_run=False, show_changes=True, append_newline=False, insert_before_match=None, insert_after_match=None): ''' .. versionadded:: 2014.1.0 Replace content of a text block in a file, delimited by line markers A block of content delimited by comments can help you manage several lines entries without worrying about old entries removal. .. note:: This function will store two copies of the file in-memory (the original version and the edited version) in order to detect changes and only edit the targeted file if necessary. path Filesystem path to the file to be edited marker_start The line content identifying a line as the start of the content block. Note that the whole line containing this marker will be considered, so whitespace or extra content before or after the marker is included in final output marker_end The line content identifying the end of the content block. As of versions 2017.7.5 and 2018.3.1, everything up to the text matching the marker will be replaced, so it's important to ensure that your marker includes the beginning of the text you wish to replace. content The content to be used between the two lines identified by marker_start and marker_stop. append_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be appended to the file. prepend_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be prepended to the file. insert_before_match If markers are not found, this parameter can be set to a regex which will insert the block before the first found occurrence in the file. .. versionadded:: Neon insert_after_match If markers are not found, this parameter can be set to a regex which will insert the block after the first found occurrence in the file. .. versionadded:: Neon backup The file extension to use for a backup of the file if any edit is made. Set to ``False`` to skip making a backup. dry_run : False If ``True``, do not make any edits to the file and simply return the changes that *would* be made. show_changes : True Controls how changes are presented. If ``True``, this function will return a unified diff of the changes made. If False, then it will return a boolean (``True`` if any changes were made, otherwise ``False``). append_newline : False Controls whether or not a newline is appended to the content block. If the value of this argument is ``True`` then a newline will be added to the content block. If it is ``False``, then a newline will *not* be added to the content block. If it is ``None`` then a newline will only be added to the content block if it does not already end in a newline. .. versionadded:: 2016.3.4 .. versionchanged:: 2017.7.5,2018.3.1 New behavior added when value is ``None``. .. versionchanged:: 2019.2.0 The default value of this argument will change to ``None`` to match the behavior of the :py:func:`file.blockreplace state <salt.states.file.blockreplace>` CLI Example: .. code-block:: bash salt '*' file.blockreplace /etc/hosts '#-- start managed zone foobar : DO NOT EDIT --' \\ '#-- end managed zone foobar --' $'10.0.1.1 foo.foobar\\n10.0.1.2 bar.foobar' True ''' exclusive_params = [append_if_not_found, prepend_if_not_found, bool(insert_before_match), bool(insert_after_match)] if sum(exclusive_params) > 1: raise SaltInvocationError( 'Only one of append_if_not_found, prepend_if_not_found,' ' insert_before_match, and insert_after_match is permitted' ) path = os.path.expanduser(path) if not os.path.exists(path): raise SaltInvocationError('File not found: {0}'.format(path)) try: file_encoding = __utils__['files.get_encoding'](path) except CommandExecutionError: file_encoding = None if __utils__['files.is_binary'](path): if not file_encoding: raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if insert_before_match or insert_after_match: if insert_before_match: if not isinstance(insert_before_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_before_match parameter.' ) elif insert_after_match: if not isinstance(insert_after_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_after_match parameter.' ) if append_newline is None and not content.endswith((os.linesep, '\n')): append_newline = True # Split the content into a list of lines, removing newline characters. To # ensure that we handle both Windows and POSIX newlines, first split on # Windows newlines, and then split on POSIX newlines. split_content = [] for win_line in content.split('\r\n'): for content_line in win_line.split('\n'): split_content.append(content_line) line_count = len(split_content) has_changes = False orig_file = [] new_file = [] in_block = False block_found = False linesep = None def _add_content(linesep, lines=None, include_marker_start=True, end_line=None): if lines is None: lines = [] include_marker_start = True if end_line is None: end_line = marker_end end_line = end_line.rstrip('\r\n') + linesep if include_marker_start: lines.append(marker_start + linesep) if split_content: for index, content_line in enumerate(split_content, 1): if index != line_count: lines.append(content_line + linesep) else: # We're on the last line of the content block if append_newline: lines.append(content_line + linesep) lines.append(end_line) else: lines.append(content_line + end_line) else: lines.append(end_line) return lines # We do not use in-place editing to avoid file attrs modifications when # no changes are required and to avoid any file access on a partially # written file. try: fi_file = io.open(path, mode='r', encoding=file_encoding, newline='') for line in fi_file: write_line_to_new_file = True if linesep is None: # Auto-detect line separator if line.endswith('\r\n'): linesep = '\r\n' elif line.endswith('\n'): linesep = '\n' else: # No newline(s) in file, fall back to system's linesep linesep = os.linesep if marker_start in line: # We've entered the content block in_block = True else: if in_block: # We're not going to write the lines from the old file to # the new file until we have exited the block. write_line_to_new_file = False marker_end_pos = line.find(marker_end) if marker_end_pos != -1: # End of block detected in_block = False # We've found and exited the block block_found = True _add_content(linesep, lines=new_file, include_marker_start=False, end_line=line[marker_end_pos:]) # Save the line from the original file orig_file.append(line) if write_line_to_new_file: new_file.append(line) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read from {0}: {1}'.format(path, exc) ) finally: if linesep is None: # If the file was empty, we will not have set linesep yet. Assume # the system's line separator. This is needed for when we # prepend/append later on. linesep = os.linesep try: fi_file.close() except Exception: pass if in_block: # unterminated block => bad, always fail raise CommandExecutionError( 'Unterminated marked block. End of file reached before marker_end.' ) if not block_found: if prepend_if_not_found: # add the markers and content at the beginning of file prepended_content = _add_content(linesep) prepended_content.extend(new_file) new_file = prepended_content block_found = True elif append_if_not_found: # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(linesep): new_file[-1] += linesep # add the markers and content at the end of file _add_content(linesep, lines=new_file) block_found = True elif insert_before_match or insert_after_match: match_regex = insert_before_match or insert_after_match match_idx = [i for i, item in enumerate(orig_file) if re.search(match_regex, item)] if match_idx: match_idx = match_idx[0] for line in _add_content(linesep): if insert_after_match: match_idx += 1 new_file.insert(match_idx, line) if insert_before_match: match_idx += 1 block_found = True if not block_found: raise CommandExecutionError( 'Cannot edit marked block. Markers were not found in file.' ) diff = __utils__['stringutils.get_diff'](orig_file, new_file) has_changes = diff is not '' if has_changes and not dry_run: # changes detected # backup file attrs perms = {} perms['user'] = get_user(path) perms['group'] = get_group(path) perms['mode'] = salt.utils.files.normalize_mode(get_mode(path)) # backup old content if backup is not False: backup_path = '{0}{1}'.format(path, backup) shutil.copy2(path, backup_path) # copy2 does not preserve ownership check_perms(backup_path, None, perms['user'], perms['group'], perms['mode']) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line, encoding=file_encoding)) finally: fh_.close() # this may have overwritten file attrs check_perms(path, None, perms['user'], perms['group'], perms['mode']) if show_changes: return diff return has_changes def search(path, pattern, flags=8, bufsize=1, ignore_if_missing=False, multiline=False ): ''' .. versionadded:: 0.17.0 Search for occurrences of a pattern in a file Except for multiline, params are identical to :py:func:`~salt.modules.file.replace`. multiline If true, inserts 'MULTILINE' into ``flags`` and sets ``bufsize`` to 'file'. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' file.search /etc/crontab 'mymaintenance.sh' ''' if multiline: flags = _add_flags(flags, 'MULTILINE') bufsize = 'file' # This function wraps file.replace on purpose in order to enforce # consistent usage, compatible regex's, expected behavior, *and* bugs. :) # Any enhancements or fixes to one should affect the other. return replace(path, pattern, '', flags=flags, bufsize=bufsize, dry_run=True, search_only=True, show_changes=False, ignore_if_missing=ignore_if_missing) def patch(originalfile, patchfile, options='', dry_run=False): ''' .. versionadded:: 0.10.4 Apply a patch to a file or directory. Equivalent to: .. code-block:: bash patch <options> -i <patchfile> <originalfile> Or, when a directory is patched: .. code-block:: bash patch <options> -i <patchfile> -d <originalfile> -p0 originalfile The full path to the file or directory to be patched patchfile A patch file to apply to ``originalfile`` options Options to pass to patch. CLI Example: .. code-block:: bash salt '*' file.patch /opt/file.txt /tmp/file.txt.patch ''' patchpath = salt.utils.path.which('patch') if not patchpath: raise CommandExecutionError( 'patch executable not found. Is the distribution\'s patch ' 'package installed?' ) cmd = [patchpath] cmd.extend(salt.utils.args.shlex_split(options)) if dry_run: if __grains__['kernel'] in ('FreeBSD', 'OpenBSD'): cmd.append('-C') else: cmd.append('--dry-run') # this argument prevents interactive prompts when the patch fails to apply. # the exit code will still be greater than 0 if that is the case. if '-N' not in cmd and '--forward' not in cmd: cmd.append('--forward') has_rejectfile_option = False for option in cmd: if option == '-r' or option.startswith('-r ') \ or option.startswith('--reject-file'): has_rejectfile_option = True break # by default, patch will write rejected patch files to <filename>.rej. # this option prevents that. if not has_rejectfile_option: cmd.append('--reject-file=-') cmd.extend(['-i', patchfile]) if os.path.isdir(originalfile): cmd.extend(['-d', originalfile]) has_strip_option = False for option in cmd: if option.startswith('-p') or option.startswith('--strip='): has_strip_option = True break if not has_strip_option: cmd.append('--strip=0') else: cmd.append(originalfile) return __salt__['cmd.run_all'](cmd, python_shell=False) def contains(path, text): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the file at ``path`` contains ``text`` CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False stripped_text = six.text_type(text).strip() try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if stripped_text in chunk: return True return False except (IOError, OSError): return False def contains_regex(path, regex, lchar=''): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the given regular expression matches on any line in the text of a given file. If the lchar argument (leading char) is specified, it will strip `lchar` from the left side of each line before trying to match CLI Example: .. code-block:: bash salt '*' file.contains_regex /etc/crontab ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.files.fopen(path, 'r') as target: for line in target: line = salt.utils.stringutils.to_unicode(line) if lchar: line = line.lstrip(lchar) if re.search(regex, line): return True return False except (IOError, OSError): return False def contains_glob(path, glob_expr): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the given glob matches a string in the named file CLI Example: .. code-block:: bash salt '*' file.contains_glob /etc/foobar '*cheese*' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if fnmatch.fnmatch(chunk, glob_expr): return True return False except (IOError, OSError): return False def append(path, *args, **kwargs): ''' .. versionadded:: 0.9.5 Append text to the end of a file path path to file `*args` strings to append to file CLI Example: .. code-block:: bash salt '*' file.append /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.append /etc/motd args='cheese=spam' salt '*' file.append /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) # Largely inspired by Fabric's contrib.files.append() if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] # Make sure we have a newline at the end of the file. Do this in binary # mode so SEEK_END with nonzero offset will work. with salt.utils.files.fopen(path, 'rb+') as ofile: linesep = salt.utils.stringutils.to_bytes(os.linesep) try: ofile.seek(-len(linesep), os.SEEK_END) except IOError as exc: if exc.errno in (errno.EINVAL, errno.ESPIPE): # Empty file, simply append lines at the beginning of the file pass else: raise else: if ofile.read(len(linesep)) != linesep: ofile.seek(0, os.SEEK_END) ofile.write(linesep) # Append lines in text mode with salt.utils.files.fopen(path, 'a') as ofile: for new_line in args: ofile.write( salt.utils.stringutils.to_str( '{0}{1}'.format(new_line, os.linesep) ) ) return 'Wrote {0} lines to "{1}"'.format(len(args), path) def prepend(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Prepend text to the beginning of a file path path to file `*args` strings to prepend to the file CLI Example: .. code-block:: bash salt '*' file.prepend /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.prepend /etc/motd args='cheese=spam' salt '*' file.prepend /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] try: with salt.utils.files.fopen(path) as fhr: contents = [salt.utils.stringutils.to_unicode(line) for line in fhr.readlines()] except IOError: contents = [] preface = [] for line in args: preface.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, 'w') as ofile: contents = preface + contents ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Prepended {0} lines to "{1}"'.format(len(args), path) def write(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Write text to a file, overwriting any existing contents. path path to file `*args` strings to write to the file CLI Example: .. code-block:: bash salt '*' file.write /etc/motd \\ "With all thine offerings thou shalt offer salt." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.write /etc/motd args='cheese=spam' salt '*' file.write /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] contents = [] for line in args: contents.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, "w") as ofile: ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Wrote {0} lines to "{1}"'.format(len(contents), path) def touch(name, atime=None, mtime=None): ''' .. versionadded:: 0.9.5 Just like the ``touch`` command, create a file if it doesn't exist or simply update the atime and mtime if it already does. atime: Access time in Unix epoch time. Set it to 0 to set atime of the file with Unix date of birth. If this parameter isn't set, atime will be set with current time. mtime: Last modification in Unix epoch time. Set it to 0 to set mtime of the file with Unix date of birth. If this parameter isn't set, mtime will be set with current time. CLI Example: .. code-block:: bash salt '*' file.touch /var/log/emptyfile ''' name = os.path.expanduser(name) if atime and atime.isdigit(): atime = int(atime) if mtime and mtime.isdigit(): mtime = int(mtime) try: if not os.path.exists(name): with salt.utils.files.fopen(name, 'a'): pass if atime is None and mtime is None: times = None elif mtime is None and atime is not None: times = (atime, time.time()) elif atime is None and mtime is not None: times = (time.time(), mtime) else: times = (atime, mtime) os.utime(name, times) except TypeError: raise SaltInvocationError('atime and mtime must be integers') except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return os.path.exists(name) def tail(path, lines): ''' .. versionadded:: Neon Read the last n lines from a file path path to file lines number of lines to read CLI Example: .. code-block:: bash salt '*' file.tail /path/to/file 10 ''' path = os.path.expanduser(path) lines_found = [] buffer_size = 4098 if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot tail a binary file: {0}'.format(path)) try: lines = int(lines) except ValueError: raise SaltInvocationError('file.tail: \'lines\' value must be an integer') try: with salt.utils.fopen(path) as tail_fh: blk_cnt = 1 size = os.stat(path).st_size if size > buffer_size: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size), os.linesep) for i in range(lines): while len(data) == 1 and ((blk_cnt * buffer_size) < size): blk_cnt += 1 line = data[0] try: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size) + line, os.linesep) except IOError: tail_fh.seek(0) data = string.split(tail_fh.read(size - (buffer_size * (blk_cnt - 1))) + line, os.linesep) line = data[-1] data.pop() lines_found.append(line) return lines_found[-lines:] except (OSError, IOError): raise CommandExecutionError('Could not tail \'{0}\''.format(path)) def seek_read(path, size, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and read it path path to file seek amount to read at once offset offset to start into the file CLI Example: .. code-block:: bash salt '*' file.seek_read /path/to/file 4096 0 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_RDONLY) try: os.lseek(seek_fh, int(offset), 0) data = os.read(seek_fh, int(size)) finally: os.close(seek_fh) return data def seek_write(path, data, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and write to it path path to file data data to write to file offset position in file to start writing CLI Example: .. code-block:: bash salt '*' file.seek_write /path/to/file 'some data' 4096 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_WRONLY) try: os.lseek(seek_fh, int(offset), 0) ret = os.write(seek_fh, data) os.fsync(seek_fh) finally: os.close(seek_fh) return ret def truncate(path, length): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and delete everything after that point path path to file length offset into file to truncate CLI Example: .. code-block:: bash salt '*' file.truncate /path/to/file 512 ''' path = os.path.expanduser(path) with salt.utils.files.fopen(path, 'rb+') as seek_fh: seek_fh.truncate(int(length)) def link(src, path): ''' .. versionadded:: 2014.1.0 Create a hard link to a file CLI Example: .. code-block:: bash salt '*' file.link /path/to/file /path/to/link ''' src = os.path.expanduser(src) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.link(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def is_link(path): ''' Check if the path is a symbolic link CLI Example: .. code-block:: bash salt '*' file.is_link /path/to/link ''' # This function exists because os.path.islink does not support Windows, # therefore a custom function will need to be called. This function # therefore helps API consistency by providing a single function to call for # both operating systems. return os.path.islink(os.path.expanduser(path)) def symlink(src, path): ''' Create a symbolic link (symlink, soft link) to a file CLI Example: .. code-block:: bash salt '*' file.symlink /path/to/file /path/to/link ''' path = os.path.expanduser(path) try: if os.path.normpath(os.readlink(path)) == os.path.normpath(src): log.debug('link already in correct state: %s -> %s', path, src) return True except OSError: pass if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: os.symlink(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def rename(src, dst): ''' Rename a file or directory CLI Example: .. code-block:: bash salt '*' file.rename /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.rename(src, dst) return True except OSError: raise CommandExecutionError( 'Could not rename \'{0}\' to \'{1}\''.format(src, dst) ) return False def copy(src, dst, recurse=False, remove_existing=False): ''' Copy a file or directory from source to dst In order to copy a directory, the recurse flag is required, and will by default overwrite files in the destination with the same path, and retain all other existing files. (similar to cp -r on unix) remove_existing will remove all files in the target directory, and then copy files from the source. .. note:: The copy function accepts paths that are local to the Salt minion. This function does not support salt://, http://, or the other additional file paths that are supported by :mod:`states.file.managed <salt.states.file.managed>` and :mod:`states.file.recurse <salt.states.file.recurse>`. CLI Example: .. code-block:: bash salt '*' file.copy /path/to/src /path/to/dst salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True remove_existing=True ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') if not os.path.exists(src): raise CommandExecutionError('No such file or directory \'{0}\''.format(src)) if not salt.utils.platform.is_windows(): pre_user = get_user(src) pre_group = get_group(src) pre_mode = salt.utils.files.normalize_mode(get_mode(src)) try: if (os.path.exists(dst) and os.path.isdir(dst)) or os.path.isdir(src): if not recurse: raise SaltInvocationError( "Cannot copy overwriting a directory without recurse flag set to true!") if remove_existing: if os.path.exists(dst): shutil.rmtree(dst) shutil.copytree(src, dst) else: salt.utils.files.recursive_copy(src, dst) else: shutil.copyfile(src, dst) except OSError: raise CommandExecutionError( 'Could not copy \'{0}\' to \'{1}\''.format(src, dst) ) if not salt.utils.platform.is_windows(): check_perms(dst, None, pre_user, pre_group, pre_mode) return True def lstat(path): ''' .. versionadded:: 2014.1.0 Returns the lstat attributes for the given file or dir. Does not support symbolic links. CLI Example: .. code-block:: bash salt '*' file.lstat /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to file must be absolute.') try: lst = os.lstat(path) return dict((key, getattr(lst, key)) for key in ('st_atime', 'st_ctime', 'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid')) except Exception: return {} def access(path, mode): ''' .. versionadded:: 2014.1.0 Test whether the Salt process has the specified access to the file. One of the following modes must be specified: .. code-block::text f: Test the existence of the path r: Test the readability of the path w: Test the writability of the path x: Test whether the path can be executed CLI Example: .. code-block:: bash salt '*' file.access /path/to/file f salt '*' file.access /path/to/file x ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') modes = {'f': os.F_OK, 'r': os.R_OK, 'w': os.W_OK, 'x': os.X_OK} if mode in modes: return os.access(path, modes[mode]) elif mode in six.itervalues(modes): return os.access(path, mode) else: raise SaltInvocationError('Invalid mode specified.') def read(path, binary=False): ''' .. versionadded:: 2017.7.0 Return the content of the file. CLI Example: .. code-block:: bash salt '*' file.read /path/to/file ''' access_mode = 'r' if binary is True: access_mode += 'b' with salt.utils.files.fopen(path, access_mode) as file_obj: return salt.utils.stringutils.to_unicode(file_obj.read()) def readlink(path, canonicalize=False): ''' .. versionadded:: 2014.1.0 Return the path that a symlink points to If canonicalize is set to True, then it return the final target CLI Example: .. code-block:: bash salt '*' file.readlink /path/to/link ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') if not os.path.islink(path): raise SaltInvocationError('A valid link was not specified.') if canonicalize: return os.path.realpath(path) else: return os.readlink(path) def readdir(path): ''' .. versionadded:: 2014.1.0 Return a list containing the contents of a directory CLI Example: .. code-block:: bash salt '*' file.readdir /path/to/dir/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Dir path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') dirents = ['.', '..'] dirents.extend(os.listdir(path)) return dirents def statvfs(path): ''' .. versionadded:: 2014.1.0 Perform a statvfs call against the filesystem that the file resides on CLI Example: .. code-block:: bash salt '*' file.statvfs /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: stv = os.statvfs(path) return dict((key, getattr(stv, key)) for key in ('f_bavail', 'f_bfree', 'f_blocks', 'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag', 'f_frsize', 'f_namemax')) except (OSError, IOError): raise CommandExecutionError('Could not statvfs \'{0}\''.format(path)) return False def stats(path, hash_type=None, follow_symlinks=True): ''' Return a dict containing the stats for a given file CLI Example: .. code-block:: bash salt '*' file.stats /etc/passwd ''' path = os.path.expanduser(path) ret = {} if not os.path.exists(path): try: # Broken symlinks will return False for os.path.exists(), but still # have a uid and gid pstat = os.lstat(path) except OSError: # Not a broken symlink, just a nonexistent path # NOTE: The file.directory state checks the content of the error # message in this exception. Any changes made to the message for this # exception will reflect the file.directory state as well, and will # likely require changes there. raise CommandExecutionError('Path not found: {0}'.format(path)) else: if follow_symlinks: pstat = os.stat(path) else: pstat = os.lstat(path) ret['inode'] = pstat.st_ino ret['uid'] = pstat.st_uid ret['gid'] = pstat.st_gid ret['group'] = gid_to_group(pstat.st_gid) ret['user'] = uid_to_user(pstat.st_uid) ret['atime'] = pstat.st_atime ret['mtime'] = pstat.st_mtime ret['ctime'] = pstat.st_ctime ret['size'] = pstat.st_size ret['mode'] = six.text_type(oct(stat.S_IMODE(pstat.st_mode))) if hash_type: ret['sum'] = get_hash(path, hash_type) ret['type'] = 'file' if stat.S_ISDIR(pstat.st_mode): ret['type'] = 'dir' if stat.S_ISCHR(pstat.st_mode): ret['type'] = 'char' if stat.S_ISBLK(pstat.st_mode): ret['type'] = 'block' if stat.S_ISREG(pstat.st_mode): ret['type'] = 'file' if stat.S_ISLNK(pstat.st_mode): ret['type'] = 'link' if stat.S_ISFIFO(pstat.st_mode): ret['type'] = 'pipe' if stat.S_ISSOCK(pstat.st_mode): ret['type'] = 'socket' ret['target'] = os.path.realpath(path) return ret def rmdir(path): ''' .. versionadded:: 2014.1.0 Remove the specified directory. Fails if a directory is not empty. CLI Example: .. code-block:: bash salt '*' file.rmdir /tmp/foo/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') try: os.rmdir(path) return True except OSError as exc: return exc.strerror def remove(path, **kwargs): ''' Remove the named file. If a directory is supplied, it will be recursively deleted. CLI Example: .. code-block:: bash salt '*' file.remove /tmp/foo ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute: {0}'.format(path)) try: if os.path.isfile(path) or os.path.islink(path): os.remove(path) return True elif os.path.isdir(path): shutil.rmtree(path) return True except (OSError, IOError) as exc: raise CommandExecutionError( 'Could not remove \'{0}\': {1}'.format(path, exc) ) return False def directory_exists(path): ''' Tests to see if path is a valid directory. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.directory_exists /etc ''' return os.path.isdir(os.path.expanduser(path)) def file_exists(path): ''' Tests to see if path is a valid file. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.file_exists /etc/passwd ''' return os.path.isfile(os.path.expanduser(path)) def path_exists_glob(path): ''' Tests to see if path after expansion is a valid path (file or directory). Expansion allows usage of ? * and character ranges []. Tilde expansion is not supported. Returns True/False. .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' file.path_exists_glob /etc/pam*/pass* ''' return True if glob.glob(os.path.expanduser(path)) else False def restorecon(path, recursive=False): ''' Reset the SELinux context on a given path CLI Example: .. code-block:: bash salt '*' file.restorecon /home/user/.ssh/authorized_keys ''' if recursive: cmd = ['restorecon', '-FR', path] else: cmd = ['restorecon', '-F', path] return not __salt__['cmd.retcode'](cmd, python_shell=False) def get_selinux_context(path): ''' Get an SELinux context from a given path CLI Example: .. code-block:: bash salt '*' file.get_selinux_context /etc/hosts ''' out = __salt__['cmd.run'](['ls', '-Z', path], python_shell=False) try: ret = re.search(r'\w+:\w+:\w+:\w+', out).group(0) except AttributeError: ret = ( 'No selinux context information is available for {0}'.format(path) ) return ret def set_selinux_context(path, user=None, role=None, type=None, # pylint: disable=W0622 range=None, # pylint: disable=W0622 persist=False): ''' .. versionchanged:: Neon Added persist option Set a specific SELinux label on a given path CLI Example: .. code-block:: bash salt '*' file.set_selinux_context path <user> <role> <type> <range> salt '*' file.set_selinux_context /etc/yum.repos.d/epel.repo system_u object_r system_conf_t s0 ''' if not any((user, role, type, range)): return False if persist: fcontext_result = __salt__['selinux.fcontext_add_policy'](path, sel_type=type, sel_user=user, sel_level=range) if fcontext_result.get('retcode', None) is not 0: # Problem setting fcontext policy raise CommandExecutionError( 'Problem setting fcontext: {0}'.format(fcontext_result) ) cmd = ['chcon'] if user: cmd.extend(['-u', user]) if role: cmd.extend(['-r', role]) if type: cmd.extend(['-t', type]) if range: cmd.extend(['-l', range]) cmd.append(path) ret = not __salt__['cmd.retcode'](cmd, python_shell=False) if ret: return get_selinux_context(path) else: return ret def source_list(source, source_hash, saltenv): ''' Check the source list and return the source to use CLI Example: .. code-block:: bash salt '*' file.source_list salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' base ''' contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv) if contextkey in __context__: return __context__[contextkey] # get the master file list if isinstance(source, list): mfiles = [(f, saltenv) for f in __salt__['cp.list_master'](saltenv)] mdirs = [(d, saltenv) for d in __salt__['cp.list_master_dirs'](saltenv)] for single in source: if isinstance(single, dict): single = next(iter(single)) path, senv = salt.utils.url.parse(single) if senv: mfiles += [(f, senv) for f in __salt__['cp.list_master'](senv)] mdirs += [(d, senv) for d in __salt__['cp.list_master_dirs'](senv)] ret = None for single in source: if isinstance(single, dict): # check the proto, if it is http or ftp then download the file # to check, if it is salt then check the master list # if it is a local file, check if the file exists if len(single) != 1: continue single_src = next(iter(single)) single_hash = single[single_src] if single[single_src] else source_hash urlparsed_single_src = _urlparse(single_src) # Fix this for Windows if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_single_src.scheme.lower() in string.ascii_lowercase: urlparsed_single_src = _urlparse('file://' + single_src) proto = urlparsed_single_src.scheme if proto == 'salt': path, senv = salt.utils.url.parse(single_src) if not senv: senv = saltenv if (path, saltenv) in mfiles or (path, saltenv) in mdirs: ret = (single_src, single_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single_src, single_hash) break elif proto == 'file' and ( os.path.exists(urlparsed_single_src.netloc) or os.path.exists(urlparsed_single_src.path) or os.path.exists(os.path.join( urlparsed_single_src.netloc, urlparsed_single_src.path))): ret = (single_src, single_hash) break elif single_src.startswith(os.sep) and os.path.exists(single_src): ret = (single_src, single_hash) break elif isinstance(single, six.string_types): path, senv = salt.utils.url.parse(single) if not senv: senv = saltenv if (path, senv) in mfiles or (path, senv) in mdirs: ret = (single, source_hash) break urlparsed_src = _urlparse(single) if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_src.scheme.lower() in string.ascii_lowercase: urlparsed_src = _urlparse('file://' + single) proto = urlparsed_src.scheme if proto == 'file' and ( os.path.exists(urlparsed_src.netloc) or os.path.exists(urlparsed_src.path) or os.path.exists(os.path.join( urlparsed_src.netloc, urlparsed_src.path))): ret = (single, source_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single, source_hash) break elif single.startswith(os.sep) and os.path.exists(single): ret = (single, source_hash) break if ret is None: # None of the list items matched raise CommandExecutionError( 'none of the specified sources were found' ) else: ret = (source, source_hash) __context__[contextkey] = ret return ret def apply_template_on_contents( contents, template, context, defaults, saltenv): ''' Return the contents after applying the templating engine contents template string template template format context Overrides default context variables passed to the template. defaults Default context passed to the template. CLI Example: .. code-block:: bash salt '*' file.apply_template_on_contents \\ contents='This is a {{ template }} string.' \\ template=jinja \\ "context={}" "defaults={'template': 'cool'}" \\ saltenv=base ''' if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) # Apply templating contents = salt.utils.templates.TEMPLATE_REGISTRY[template]( contents, from_str=True, to_str=True, context=context_dict, saltenv=saltenv, grains=__opts__['grains'], pillar=__pillar__, salt=__salt__, opts=__opts__)['data'] if six.PY2: contents = contents.encode('utf-8') elif six.PY3 and isinstance(contents, bytes): # bytes -> str contents = contents.decode('utf-8') else: ret = {} ret['result'] = False ret['comment'] = ('Specified template format {0} is not supported' ).format(template) return ret return contents def get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify=False, **kwargs): ''' Return the managed file data for file.managed name location where the file lives on the server template template format source managed source file source_hash hash of the source file source_hash_name When ``source_hash`` refers to a remote file, this specifies the filename to look for in that file. .. versionadded:: 2016.3.5 user Owner of file group Group owner of file mode Permissions of file attrs Attributes of file .. versionadded:: 2018.3.0 context Variables to add to the template context defaults Default values of for context_dict skip_verify If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' file.get_managed /etc/httpd/conf.d/httpd.conf jinja salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' None root root '755' base None None ''' # Copy the file to the minion and templatize it sfn = '' source_sum = {} def _get_local_file_source_sum(path): ''' DRY helper for getting the source_sum value from a locally cached path. ''' return {'hsum': get_hash(path, form='sha256'), 'hash_type': 'sha256'} # If we have a source defined, let's figure out what the hash is if source: urlparsed_source = _urlparse(source) if urlparsed_source.scheme in salt.utils.files.VALID_PROTOS: parsed_scheme = urlparsed_source.scheme else: parsed_scheme = '' parsed_path = os.path.join( urlparsed_source.netloc, urlparsed_source.path).rstrip(os.sep) unix_local_source = parsed_scheme in ('file', '') if parsed_scheme == '': parsed_path = sfn = source if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg elif parsed_scheme == 'file': sfn = parsed_path if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg if parsed_scheme and parsed_scheme.lower() in string.ascii_lowercase: parsed_path = ':'.join([parsed_scheme, parsed_path]) parsed_scheme = 'file' if parsed_scheme == 'salt': source_sum = __salt__['cp.hash_file'](source, saltenv) if not source_sum: return '', {}, 'Source file {0} not found in saltenv \'{1}\''.format(source, saltenv) elif not source_hash and unix_local_source: source_sum = _get_local_file_source_sum(parsed_path) elif not source_hash and source.startswith(os.sep): # This should happen on Windows source_sum = _get_local_file_source_sum(source) else: if not skip_verify: if source_hash: try: source_sum = get_source_sum(name, source, source_hash, source_hash_name, saltenv) except CommandExecutionError as exc: return '', {}, exc.strerror else: msg = ( 'Unable to verify upstream hash of source file {0}, ' 'please set source_hash or set skip_verify to True' .format(salt.utils.url.redact_http_basic_auth(source)) ) return '', {}, msg if source and (template or parsed_scheme in salt.utils.files.REMOTE_PROTOS): # Check if we have the template or remote file cached cache_refetch = False cached_dest = __salt__['cp.is_cached'](source, saltenv) if cached_dest and (source_hash or skip_verify): htype = source_sum.get('hash_type', 'sha256') cached_sum = get_hash(cached_dest, form=htype) if skip_verify: # prev: if skip_verify or cached_sum == source_sum['hsum']: # but `cached_sum == source_sum['hsum']` is elliptical as prev if sfn = cached_dest source_sum = {'hsum': cached_sum, 'hash_type': htype} elif cached_sum != source_sum.get('hsum', __opts__['hash_type']): cache_refetch = True else: sfn = cached_dest # If we didn't have the template or remote file, or the file has been # updated and the cache has to be refreshed, download the file. if not sfn or cache_refetch: try: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum.get('hsum')) except Exception as exc: # A 404 or other error code may raise an exception, catch it # and return a comment that will fail the calling state. _source = salt.utils.url.redact_http_basic_auth(source) return '', {}, 'Failed to cache {0}: {1}'.format(_source, exc) # If cache failed, sfn will be False, so do a truth check on sfn first # as invoking os.path.exists() on a bool raises a TypeError. if not sfn or not os.path.exists(sfn): _source = salt.utils.url.redact_http_basic_auth(source) return sfn, {}, 'Source file \'{0}\' not found'.format(_source) if sfn == name: raise SaltInvocationError( 'Source file cannot be the same as destination' ) if template: if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, name=name, source=source, user=user, group=group, mode=mode, attrs=attrs, saltenv=saltenv, context=context_dict, salt=__salt__, pillar=__pillar__, grains=__opts__['grains'], opts=__opts__, **kwargs) else: return sfn, {}, ('Specified template format {0} is not supported' ).format(template) if data['result']: sfn = data['data'] hsum = get_hash(sfn, form='sha256') source_sum = {'hash_type': 'sha256', 'hsum': hsum} else: __clean_tmp(sfn) return sfn, {}, data['data'] return sfn, source_sum, '' def extract_hash(hash_fn, hash_type='sha256', file_name='', source='', source_hash_name=None): ''' .. versionchanged:: 2016.3.5 Prior to this version, only the ``file_name`` argument was considered for filename matches in the hash file. This would be problematic for cases in which the user was relying on a remote checksum file that they do not control, and they wished to use a different name for that file on the minion from the filename on the remote server (and in the checksum file). For example, managing ``/tmp/myfile.tar.gz`` when the remote file was at ``https://mydomain.tld/different_name.tar.gz``. The :py:func:`file.managed <salt.states.file.managed>` state now also passes this function the source URI as well as the ``source_hash_name`` (if specified). In cases where ``source_hash_name`` is specified, it takes precedence over both the ``file_name`` and ``source``. When it is not specified, ``file_name`` takes precedence over ``source``. This allows for better capability for matching hashes. .. versionchanged:: 2016.11.0 File name and source URI matches are no longer disregarded when ``source_hash_name`` is specified. They will be used as fallback matches if there is no match to the ``source_hash_name`` value. This routine is called from the :mod:`file.managed <salt.states.file.managed>` state to pull a hash from a remote file. Regular expressions are used line by line on the ``source_hash`` file, to find a potential candidate of the indicated hash type. This avoids many problems of arbitrary file layout rules. It specifically permits pulling hash codes from debian ``*.dsc`` files. If no exact match of a hash and filename are found, then the first hash found (if any) will be returned. If no hashes at all are found, then ``None`` will be returned. For example: .. code-block:: yaml openerp_7.0-latest-1.tar.gz: file.managed: - name: /tmp/openerp_7.0-20121227-075624-1_all.deb - source: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.tar.gz - source_hash: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.dsc CLI Example: .. code-block:: bash salt '*' file.extract_hash /path/to/hash/file sha512 /etc/foo ''' hash_len = HASHES.get(hash_type) if hash_len is None: if hash_type: log.warning( 'file.extract_hash: Unsupported hash_type \'%s\', falling ' 'back to matching any supported hash_type', hash_type ) hash_type = '' hash_len_expr = '{0},{1}'.format(min(HASHES_REVMAP), max(HASHES_REVMAP)) else: hash_len_expr = six.text_type(hash_len) filename_separators = string.whitespace + r'\/' if source_hash_name: if not isinstance(source_hash_name, six.string_types): source_hash_name = six.text_type(source_hash_name) source_hash_name_idx = (len(source_hash_name) + 1) * -1 log.debug( 'file.extract_hash: Extracting %s hash for file matching ' 'source_hash_name \'%s\'', 'any supported' if not hash_type else hash_type, source_hash_name ) if file_name: if not isinstance(file_name, six.string_types): file_name = six.text_type(file_name) file_name_basename = os.path.basename(file_name) file_name_idx = (len(file_name_basename) + 1) * -1 if source: if not isinstance(source, six.string_types): source = six.text_type(source) urlparsed_source = _urlparse(source) source_basename = os.path.basename( urlparsed_source.path or urlparsed_source.netloc ) source_idx = (len(source_basename) + 1) * -1 basename_searches = [x for x in (file_name, source) if x] if basename_searches: log.debug( 'file.extract_hash: %s %s hash for file matching%s: %s', 'If no source_hash_name match found, will extract' if source_hash_name else 'Extracting', 'any supported' if not hash_type else hash_type, '' if len(basename_searches) == 1 else ' either of the following', ', '.join(basename_searches) ) partial = None found = {} with salt.utils.files.fopen(hash_fn, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line.strip()) hash_re = r'(?i)(?<![a-z0-9])([a-f0-9]{' + hash_len_expr + '})(?![a-z0-9])' hash_match = re.search(hash_re, line) matched = None if hash_match: matched_hsum = hash_match.group(1) if matched_hsum is not None: matched_type = HASHES_REVMAP.get(len(matched_hsum)) if matched_type is None: # There was a match, but it's not of the correct length # to match one of the supported hash types. matched = None else: matched = {'hsum': matched_hsum, 'hash_type': matched_type} if matched is None: log.debug( 'file.extract_hash: In line \'%s\', no %shash found', line, '' if not hash_type else hash_type + ' ' ) continue if partial is None: partial = matched def _add_to_matches(found, line, match_type, value, matched): log.debug( 'file.extract_hash: Line \'%s\' matches %s \'%s\'', line, match_type, value ) found.setdefault(match_type, []).append(matched) hash_matched = False if source_hash_name: if line.endswith(source_hash_name): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[source_hash_name_idx] in string.whitespace: _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source_hash_name) + r'\s+', line): _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True if file_name: if line.endswith(file_name_basename): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[file_name_idx] in filename_separators: _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(file_name) + r'\s+', line): _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True if source: if line.endswith(source_basename): # Same as above, we can't just do an rsplit here. try: if line[source_idx] in filename_separators: _add_to_matches(found, line, 'source', source, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source) + r'\s+', line): _add_to_matches(found, line, 'source', source, matched) hash_matched = True if not hash_matched: log.debug( 'file.extract_hash: Line \'%s\' contains %s hash ' '\'%s\', but line did not meet the search criteria', line, matched['hash_type'], matched['hsum'] ) for found_type, found_str in (('source_hash_name', source_hash_name), ('file_name', file_name), ('source', source)): if found_type in found: if len(found[found_type]) > 1: log.debug( 'file.extract_hash: Multiple %s matches for %s: %s', found_type, found_str, ', '.join( ['{0} ({1})'.format(x['hsum'], x['hash_type']) for x in found[found_type]] ) ) ret = found[found_type][0] log.debug( 'file.extract_hash: Returning %s hash \'%s\' as a match of %s', ret['hash_type'], ret['hsum'], found_str ) return ret if partial: log.debug( 'file.extract_hash: Returning the partially identified %s hash ' '\'%s\'', partial['hash_type'], partial['hsum'] ) return partial log.debug('file.extract_hash: No matches, returning None') return None def check_perms(name, ret, user, group, mode, attrs=None, follow_symlinks=False, seuser=None, serole=None, setype=None, serange=None): ''' .. versionchanged:: Neon Added selinux options Check the permissions on files, modify attributes and chown if needed. File attributes are only verified if lsattr(1) is installed. CLI Example: .. code-block:: bash salt '*' file.check_perms /etc/sudoers '{}' root root 400 ai .. versionchanged:: 2014.1.3 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': [], 'result': True} orig_comment = '' else: orig_comment = ret['comment'] ret['comment'] = [] # Check permissions perms = {} cur = stats(name, follow_symlinks=follow_symlinks) perms['luser'] = cur['user'] perms['lgroup'] = cur['group'] perms['lmode'] = salt.utils.files.normalize_mode(cur['mode']) is_dir = os.path.isdir(name) is_link = os.path.islink(name) if attrs is not None \ and not salt.utils.platform.is_windows() \ and not is_dir and not is_link: try: lattrs = lsattr(name) except SaltInvocationError: lattrs = None if lattrs is not None: # List attributes on file perms['lattrs'] = ''.join(lattrs.get(name, '')) # Remove attributes on file so changes can be enforced. if perms['lattrs']: chattr(name, operator='remove', attributes=perms['lattrs']) # user/group changes if needed, then check if it worked if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid(perms['luser']) ) or ( not salt.utils.platform.is_windows() and user != perms['luser'] ): perms['cuser'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid(perms['lgroup']) ) or ( not salt.utils.platform.is_windows() and group != perms['lgroup'] ): perms['cgroup'] = group if 'cuser' in perms or 'cgroup' in perms: if not __opts__['test']: if os.path.islink(name) and not follow_symlinks: chown_func = lchown else: chown_func = chown if user is None: user = perms['luser'] if group is None: group = perms['lgroup'] try: chown_func(name, user, group) # Python os.chown() does reset the suid and sgid, # that's why setting the right mode again is needed here. set_mode(name, mode) except OSError: ret['result'] = False if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid( get_user(name, follow_symlinks=follow_symlinks)) and user != '' ) or ( not salt.utils.platform.is_windows() and user != get_user(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['user'] = user else: ret['result'] = False ret['comment'].append('Failed to change user to {0}' .format(user)) elif 'cuser' in perms and user != '': ret['changes']['user'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid( get_group(name, follow_symlinks=follow_symlinks)) and user != '') or ( not salt.utils.platform.is_windows() and group != get_group(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['group'] = group else: ret['result'] = False ret['comment'].append('Failed to change group to {0}' .format(group)) elif 'cgroup' in perms and user != '': ret['changes']['group'] = group if not salt.utils.platform.is_windows() and not is_dir: # Replace attributes on file if it had been removed if perms.get('lattrs', ''): chattr(name, operator='add', attributes=perms['lattrs']) # Mode changes if needed if mode is not None: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: mode = salt.utils.files.normalize_mode(mode) if mode != perms['lmode']: if __opts__['test'] is True: ret['changes']['mode'] = mode else: set_mode(name, mode) if mode != salt.utils.files.normalize_mode(get_mode(name)): ret['result'] = False ret['comment'].append( 'Failed to change mode to {0}'.format(mode) ) else: ret['changes']['mode'] = mode # Modify attributes of file if needed if attrs is not None and not is_dir: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if diff_attrs[0] is not None or diff_attrs[1] is not None: if __opts__['test'] is True: ret['changes']['attrs'] = attrs else: if diff_attrs[0] is not None: chattr(name, operator="add", attributes=diff_attrs[0]) if diff_attrs[1] is not None: chattr(name, operator="remove", attributes=diff_attrs[1]) cmp_attrs = _cmp_attrs(name, attrs) if cmp_attrs[0] is not None or cmp_attrs[1] is not None: ret['result'] = False ret['comment'].append( 'Failed to change attributes to {0}'.format(attrs) ) else: ret['changes']['attrs'] = attrs # Set selinux attributes if needed if salt.utils.platform.is_linux() and (seuser or serole or setype or serange): selinux_error = False try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError: log.error('Unable to get current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to get selinux attributes' ) selinux_error = True if not selinux_error: requested_seuser = None requested_serole = None requested_setype = None requested_serange = None # Only set new selinux variables if updates are needed if seuser and seuser != current_seuser: requested_seuser = seuser if serole and serole != current_serole: requested_serole = serole if setype and setype != current_setype: requested_setype = setype if serange and serange != current_serange: requested_serange = serange if requested_seuser or requested_serole or requested_setype or requested_serange: # selinux updates needed, prep changes output selinux_change_new = '' selinux_change_orig = '' if requested_seuser: selinux_change_new += "User: {0} ".format(requested_seuser) selinux_change_orig += "User: {0} ".format(current_seuser) if requested_serole: selinux_change_new += "Role: {0} ".format(requested_serole) selinux_change_orig += "Role: {0} ".format(current_serole) if requested_setype: selinux_change_new += "Type: {0} ".format(requested_setype) selinux_change_orig += "Type: {0} ".format(current_setype) if requested_serange: selinux_change_new += "Range: {0} ".format(requested_serange) selinux_change_orig += "Range: {0} ".format(current_serange) if __opts__['test']: ret['comment'] = 'File {0} selinux context to be updated'.format(name) ret['result'] = None ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} else: try: # set_selinux_context requires type to be set on any other change if (requested_seuser or requested_serole or requested_serange) and not requested_setype: requested_setype = current_setype result = set_selinux_context(name, user=requested_seuser, role=requested_serole, type=requested_setype, range=requested_serange, persist=True) log.debug('selinux set result: %s', result) current_seuser, current_serole, current_setype, current_serange = result.split(':') except ValueError: log.error('Unable to set current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to set selinux attributes' ) selinux_error = True if not selinux_error: ret['comment'].append('The file {0} is set to be changed'.format(name)) if requested_seuser: if current_seuser != requested_seuser: ret['comment'].append("Unable to update seuser context") ret['result'] = False if requested_serole: if current_serole != requested_serole: ret['comment'].append("Unable to update serole context") ret['result'] = False if requested_setype: if current_setype != requested_setype: ret['comment'].append("Unable to update setype context") ret['result'] = False if requested_serange: if current_serange != requested_serange: ret['comment'].append("Unable to update serange context") ret['result'] = False ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} # Only combine the comment list into a string # after all comments are added above if isinstance(orig_comment, six.string_types): if orig_comment: ret['comment'].insert(0, orig_comment) ret['comment'] = '; '.join(ret['comment']) # Set result to None at the very end of the function, # after all changes have been recorded above if __opts__['test'] is True and ret['changes']: ret['result'] = None return ret, perms def check_managed( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Check to see what changes need to be made for a file CLI Example: .. code-block:: bash salt '*' file.check_managed /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) if comments: __clean_tmp(sfn) return False, comments changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) # Ignore permission for files written temporary directories # Files in any path will still be set correctly using get_managed() if name.startswith(tempfile.gettempdir()): for key in ['user', 'group', 'mode']: changes.pop(key, None) __clean_tmp(sfn) if changes: log.info(changes) comments = ['The following values are set to be changed:\n'] comments.extend('{0}: {1}\n'.format(key, val) for key, val in six.iteritems(changes)) return None, ''.join(comments) return True, 'The file {0} is in the correct state'.format(name) def check_managed_changes( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, keep_mode=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Return a dictionary of what changes need to be made for a file .. versionchanged:: Neon selinux attributes added CLI Example: .. code-block:: bash salt '*' file.check_managed_changes /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if comments: __clean_tmp(sfn) raise CommandExecutionError(comments) if sfn and source and keep_mode: if _urlparse(source).scheme in ('salt', 'file') \ or source.startswith('/'): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) __clean_tmp(sfn) return changes def check_file_meta( name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents=None, seuser=None, serole=None, setype=None, serange=None): ''' Check for the changes in the file metadata. CLI Example: .. code-block:: bash salt '*' file.check_file_meta /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' base .. note:: Supported hash types include sha512, sha384, sha256, sha224, sha1, and md5. name Path to file destination sfn Template-processed source file contents source URL to file source source_sum File checksum information as a dictionary .. code-block:: yaml {hash_type: md5, hsum: <md5sum>} user Destination file user owner group Destination file group owner mode Destination file permissions mode attrs Destination file attributes .. versionadded:: 2018.3.0 saltenv Salt environment used to resolve source files contents File contents seuser selinux user attribute .. versionadded:: Neon serole selinux role attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon ''' changes = {} if not source_sum: source_sum = dict() try: lstats = stats(name, hash_type=source_sum.get('hash_type', None), follow_symlinks=False) except CommandExecutionError: lstats = {} if not lstats: changes['newfile'] = name return changes if 'hsum' in source_sum: if source_sum['hsum'] != lstats['sum']: if not sfn and source: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum['hsum']) if sfn: try: changes['diff'] = get_diff( name, sfn, template=True, show_filenames=False) except CommandExecutionError as exc: changes['diff'] = exc.strerror else: changes['sum'] = 'Checksum differs' if contents is not None: # Write a tempfile with the static contents tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'w') as tmp_: tmp_.write(salt.utils.stringutils.to_str(contents)) # Compare the static contents with the named file try: differences = get_diff(name, tmp, show_filenames=False) except CommandExecutionError as exc: log.error('Failed to diff files: %s', exc) differences = exc.strerror __clean_tmp(tmp) if differences: if __salt__['config.option']('obfuscate_templates'): changes['diff'] = '<Obfuscated Template>' else: changes['diff'] = differences if not salt.utils.platform.is_windows(): # Check owner if (user is not None and user != lstats['user'] and user != lstats['uid']): changes['user'] = user # Check group if (group is not None and group != lstats['group'] and group != lstats['gid']): changes['group'] = group # Normalize the file mode smode = salt.utils.files.normalize_mode(lstats['mode']) mode = salt.utils.files.normalize_mode(mode) if mode is not None and mode != smode: changes['mode'] = mode if attrs: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if attrs is not None \ and (diff_attrs[0] is not None or diff_attrs[1] is not None): changes['attrs'] = attrs # Check selinux if seuser or serole or setype or serange: try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError as exc: log.error('Unable to get current selinux attributes') changes['selinux'] = exc.strerror if seuser and seuser != current_seuser: changes['selinux'] = {"user": seuser} if serole and serole != current_serole: changes['selinux'] = {"role": serole} if setype and setype != current_setype: changes['selinux'] = {"type": setype} if serange and serange != current_serange: changes['selinux'] = {"range": serange} return changes def get_diff(file1, file2, saltenv='base', show_filenames=True, show_changes=True, template=False, source_hash_file1=None, source_hash_file2=None): ''' Return unified diff of two files file1 The first file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, thuis had to be a file local to the minion. file2 The second file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, this had to be a file on the salt fileserver (i.e. ``salt://somefile.txt``) show_filenames : True Set to ``False`` to hide the filenames in the top two lines of the diff. show_changes : True If set to ``False``, and there are differences, then instead of a diff a simple message stating that show_changes is set to ``False`` will be returned. template : False Set to ``True`` if two templates are being compared. This is not useful except for within states, with the ``obfuscate_templates`` option set to ``True``. .. versionadded:: 2018.3.0 source_hash_file1 If ``file1`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 source_hash_file2 If ``file2`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 CLI Examples: .. code-block:: bash salt '*' file.get_diff /home/fred/.vimrc salt://users/fred/.vimrc salt '*' file.get_diff /tmp/foo.txt /tmp/bar.txt ''' files = (file1, file2) source_hashes = (source_hash_file1, source_hash_file2) paths = [] errors = [] for filename, source_hash in zip(files, source_hashes): try: # Local file paths will just return the same path back when passed # to cp.cache_file. cached_path = __salt__['cp.cache_file'](filename, saltenv, source_hash=source_hash) if cached_path is False: errors.append( 'File {0} not found'.format( salt.utils.stringutils.to_unicode(filename) ) ) continue paths.append(cached_path) except MinionError as exc: errors.append(salt.utils.stringutils.to_unicode(exc.__str__())) continue if errors: raise CommandExecutionError( 'Failed to cache one or more files', info=errors ) args = [] for filename in paths: try: with salt.utils.files.fopen(filename, 'rb') as fp_: args.append(fp_.readlines()) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read {0}: {1}'.format( salt.utils.stringutils.to_unicode(filename), exc.strerror ) ) if args[0] != args[1]: if template and __salt__['config.option']('obfuscate_templates'): ret = '<Obfuscated Template>' elif not show_changes: ret = '<show_changes=False>' else: bdiff = _binary_replace(*paths) # pylint: disable=no-value-for-parameter if bdiff: ret = bdiff else: if show_filenames: args.extend(paths) ret = __utils__['stringutils.get_diff'](*args) return ret return '' def manage_file(name, sfn, ret, source, source_sum, user, group, mode, attrs, saltenv, backup, makedirs=False, template=None, # pylint: disable=W0613 show_changes=True, contents=None, dir_mode=None, follow_symlinks=True, skip_verify=False, keep_mode=False, encoding=None, encoding_errors='strict', seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Checks the destination against what was retrieved with get_managed and makes the appropriate modifications (if necessary). name location to place the file sfn location of cached file on the minion This is the path to the file stored on the minion. This file is placed on the minion using cp.cache_file. If the hash sum of that file matches the source_sum, we do not transfer the file to the minion again. This file is then grabbed and if it has template set, it renders the file to be placed into the correct place on the system using salt.files.utils.copyfile() ret The initial state return data structure. Pass in ``None`` to use the default structure. source file reference on the master source_sum sum hash for source user user owner group group owner backup backup_mode attrs attributes to be set on file: '' means remove all of them .. versionadded:: 2018.3.0 makedirs make directories if they do not exist template format of templating show_changes Include diff in state return contents: contents to be placed in the file dir_mode mode for directories created with makedirs skip_verify : False If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 keep_mode : False If ``True``, and the ``source`` is a file from the Salt fileserver (or a local file on the minion), the mode of the destination file will be set to the mode of the source file. .. note:: keep_mode does not work with salt-ssh. As a consequence of how the files are transferred to the minion, and the inability to connect back to the master with salt-ssh, salt is unable to stat the file as it exists on the fileserver and thus cannot mirror the mode on the salt-ssh minion encoding If specified, then the specified encoding will be used. Otherwise, the file will be encoded using the system locale (usually UTF-8). See https://docs.python.org/3/library/codecs.html#standard-encodings for the list of available encodings. .. versionadded:: 2017.7.0 encoding_errors : 'strict' Default is ```'strict'```. See https://docs.python.org/2/library/codecs.html#codec-base-classes for the error handling schemes. .. versionadded:: 2017.7.0 seuser selinux user attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon CLI Example: .. code-block:: bash salt '*' file.manage_file /etc/httpd/conf.d/httpd.conf '' '{}' salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' '' base '' .. versionchanged:: 2014.7.0 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if source: if not sfn: # File is not present, cache it sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) htype = source_sum.get('hash_type', __opts__['hash_type']) # Recalculate source sum now that file has been cached source_sum = { 'hash_type': htype, 'hsum': get_hash(sfn, form=htype) } if keep_mode: if _urlparse(source).scheme in ('salt', 'file', ''): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) # Check changes if the target file exists if os.path.isfile(name) or os.path.islink(name): if os.path.islink(name) and follow_symlinks: real_name = os.path.realpath(name) else: real_name = name # Only test the checksums on files with managed contents if source and not (not follow_symlinks and os.path.islink(real_name)): name_sum = get_hash(real_name, source_sum.get('hash_type', __opts__['hash_type'])) else: name_sum = None # Check if file needs to be replaced if source and (name_sum is None or source_sum.get('hsum', __opts__['hash_type']) != name_sum): if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server or local # source, and we are not skipping checksum verification, then # verify that it matches the specified checksum. if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3}). If the \'source_hash\' value ' 'refers to a remote file with multiple possible ' 'matches, then it may be necessary to set ' '\'source_hash_name\'.'.format( source_sum['hash_type'], source, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # Print a diff equivalent to diff -u old new if __salt__['config.option']('obfuscate_templates'): ret['changes']['diff'] = '<Obfuscated Template>' elif not show_changes: ret['changes']['diff'] = '<show_changes=False>' else: try: ret['changes']['diff'] = get_diff( real_name, sfn, show_filenames=False) except CommandExecutionError as exc: ret['changes']['diff'] = exc.strerror # Pre requisites are met, and the file needs to be replaced, do it try: salt.utils.files.copyfile(sfn, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) try: differences = get_diff( real_name, tmp, show_filenames=False, show_changes=show_changes, template=True) except CommandExecutionError as exc: ret.setdefault('warnings', []).append( 'Failed to detect changes to file: {0}'.format(exc.strerror) ) differences = '' if differences: ret['changes']['diff'] = differences # Pre requisites are met, the file needs to be replaced, do it try: salt.utils.files.copyfile(tmp, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(tmp) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) __clean_tmp(tmp) # Check for changing symlink to regular file here if os.path.islink(name) and not follow_symlinks: if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret try: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) ret['changes']['diff'] = \ 'Replace symbolic link with regular file' if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, follow_symlinks, seuser=seuser, serole=serole, setype=setype, serange=serange) if ret['changes']: ret['comment'] = 'File {0} updated'.format( salt.utils.data.decode(name) ) elif not ret['changes'] and ret['result']: ret['comment'] = 'File {0} is in the correct state'.format( salt.utils.data.decode(name) ) if sfn: __clean_tmp(sfn) return ret else: # target file does not exist contain_dir = os.path.dirname(name) def _set_mode_and_make_dirs(name, dir_mode, mode, user, group): # check for existence of windows drive letter if salt.utils.platform.is_windows(): drive, _ = os.path.splitdrive(name) if drive and not os.path.exists(drive): __clean_tmp(sfn) return _error(ret, '{0} drive not present'.format(drive)) if dir_mode is None and mode is not None: # Add execute bit to each nonzero digit in the mode, if # dir_mode was not specified. Otherwise, any # directories created with makedirs_() below can't be # listed via a shell. mode_list = [x for x in six.text_type(mode)][-3:] for idx in range(len(mode_list)): if mode_list[idx] != '0': mode_list[idx] = six.text_type(int(mode_list[idx]) | 1) dir_mode = ''.join(mode_list) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 makedirs_( path=name, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: makedirs_(name, user=user, group=group, mode=dir_mode) if source: # Apply the new file if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # It is a new file, set the diff accordingly ret['changes']['diff'] = 'New file' if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') else: # source != True if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') # Create the file, user rw-only if mode will be set to prevent # a small security race problem before the permissions are set with salt.utils.files.set_umask(0o077 if mode else None): # Create a new file when test is False and source is None if contents is None: if not __opts__['test']: if touch(name): ret['changes']['new'] = 'file {0} created'.format(name) ret['comment'] = 'Empty file' else: return _error( ret, 'Empty file {0} not created'.format(name) ) else: if not __opts__['test']: if touch(name): ret['changes']['diff'] = 'New file' else: return _error( ret, 'File {0} not created'.format(name) ) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) # Copy into place salt.utils.files.copyfile(tmp, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(tmp) # Now copy the file contents if there is a source file elif sfn: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(sfn) # This is a new file, if no mode specified, use the umask to figure # out what mode to use for the new file. if mode is None and not salt.utils.platform.is_windows(): # Get current umask mask = salt.utils.files.get_umask() # Calculate the mode value that results from the umask mode = oct((0o777 ^ mask) & 0o666) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, seuser=seuser, serole=serole, setype=setype, serange=serange) if not ret['comment']: ret['comment'] = 'File ' + name + ' updated' if __opts__['test']: ret['comment'] = 'File ' + name + ' not updated' elif not ret['changes'] and ret['result']: ret['comment'] = 'File ' + name + ' is in the correct state' if sfn: __clean_tmp(sfn) return ret def mkdir(dir_path, user=None, group=None, mode=None): ''' Ensure that a directory is available. CLI Example: .. code-block:: bash salt '*' file.mkdir /opt/jetty/context ''' dir_path = os.path.expanduser(dir_path) directory = os.path.normpath(dir_path) if not os.path.isdir(directory): # If a caller such as managed() is invoked with makedirs=True, make # sure that any created dirs are created with the same user and group # to follow the principal of least surprise method. makedirs_perms(directory, user, group, mode) return True def makedirs_(path, user=None, group=None, mode=None): ''' Ensure that the directory containing this path is available. .. note:: The path must end with a trailing slash otherwise the directory/directories will be created up to the parent directory. For example if path is ``/opt/code``, then it would be treated as ``/opt/`` but if the path ends with a trailing slash like ``/opt/code/``, then it would be treated as ``/opt/code/``. CLI Example: .. code-block:: bash salt '*' file.makedirs /opt/code/ ''' path = os.path.expanduser(path) if mode: mode = salt.utils.files.normalize_mode(mode) # walk up the directory structure until we find the first existing # directory dirname = os.path.normpath(os.path.dirname(path)) if os.path.isdir(dirname): # There's nothing for us to do msg = 'Directory \'{0}\' already exists'.format(dirname) log.debug(msg) return msg if os.path.exists(dirname): msg = 'The path \'{0}\' already exists and is not a directory'.format( dirname ) log.debug(msg) return msg directories_to_create = [] while True: if os.path.isdir(dirname): break directories_to_create.append(dirname) current_dirname = dirname dirname = os.path.dirname(dirname) if current_dirname == dirname: raise SaltInvocationError( 'Recursive creation for path \'{0}\' would result in an ' 'infinite loop. Please use an absolute path.'.format(dirname) ) # create parent directories from the topmost to the most deeply nested one directories_to_create.reverse() for directory_to_create in directories_to_create: # all directories have the user, group and mode set!! log.debug('Creating directory: %s', directory_to_create) mkdir(directory_to_create, user=user, group=group, mode=mode) def makedirs_perms(name, user=None, group=None, mode='0755'): ''' Taken and modified from os.makedirs to set user, group and mode for each directory created. CLI Example: .. code-block:: bash salt '*' file.makedirs_perms /opt/code ''' name = os.path.expanduser(name) path = os.path head, tail = path.split(name) if not tail: head, tail = path.split(head) if head and tail and not path.exists(head): try: makedirs_perms(head, user, group, mode) except OSError as exc: # be happy if someone already created the path if exc.errno != errno.EEXIST: raise if tail == os.curdir: # xxx/newdir/. exists if xxx/newdir exists return os.mkdir(name) check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) def get_devmm(name): ''' Get major/minor info from a device CLI Example: .. code-block:: bash salt '*' file.get_devmm /dev/chr ''' name = os.path.expanduser(name) if is_chrdev(name) or is_blkdev(name): stat_structure = os.stat(name) return ( os.major(stat_structure.st_rdev), os.minor(stat_structure.st_rdev)) else: return (0, 0) def is_chrdev(name): ''' Check if a file exists and is a character device. CLI Example: .. code-block:: bash salt '*' file.is_chrdev /dev/chr ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the character device does not exist in the first place return False else: raise return stat.S_ISCHR(stat_structure.st_mode) def mknod_chrdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a character device. CLI Example: .. code-block:: bash salt '*' file.mknod_chrdev /dev/chr 180 31 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating character device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFCHR, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created character device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_blkdev(name): ''' Check if a file exists and is a block device. CLI Example: .. code-block:: bash salt '*' file.is_blkdev /dev/blk ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the block device does not exist in the first place return False else: raise return stat.S_ISBLK(stat_structure.st_mode) def mknod_blkdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a block device. CLI Example: .. code-block:: bash salt '*' file.mknod_blkdev /dev/blk 8 999 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating block device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFBLK, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created block device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_fifo(name): ''' Check if a file exists and is a FIFO. CLI Example: .. code-block:: bash salt '*' file.is_fifo /dev/fifo ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the fifo does not exist in the first place return False else: raise return stat.S_ISFIFO(stat_structure.st_mode) def mknod_fifo(name, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a FIFO pipe. CLI Example: .. code-block:: bash salt '*' file.mknod_fifo /dev/fifo ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating FIFO name: %s', name) try: if __opts__['test']: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = None else: if os.mkfifo(name, int(six.text_type(mode).lstrip('0Oo'), 8)) is None: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created fifo check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def mknod(name, ntype, major=0, minor=0, user=None, group=None, mode='0600'): ''' .. versionadded:: 0.17.0 Create a block device, character device, or fifo pipe. Identical to the gnu mknod. CLI Examples: .. code-block:: bash salt '*' file.mknod /dev/chr c 180 31 salt '*' file.mknod /dev/blk b 8 999 salt '*' file.nknod /dev/fifo p ''' ret = False makedirs_(name, user, group) if ntype == 'c': ret = mknod_chrdev(name, major, minor, user, group, mode) elif ntype == 'b': ret = mknod_blkdev(name, major, minor, user, group, mode) elif ntype == 'p': ret = mknod_fifo(name, user, group, mode) else: raise SaltInvocationError( 'Node type unavailable: \'{0}\'. Available node types are ' 'character (\'c\'), block (\'b\'), and pipe (\'p\').'.format(ntype) ) return ret def list_backups(path, limit=None): ''' .. versionadded:: 0.17.0 Lists the previous versions of a file backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups /foo/bar/baz.txt ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows src_dir = parent_dir.replace(':', '_') else: src_dir = parent_dir[1:] # Figure out full path of location of backup file in minion cache bkdir = os.path.join(bkroot, src_dir) if not os.path.isdir(bkdir): return {} files = {} for fname in [x for x in os.listdir(bkdir) if os.path.isfile(os.path.join(bkdir, x))]: if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows strpfmt = '{0}_%a_%b_%d_%H-%M-%S_%f_%Y'.format(basename) else: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(fname, strpfmt) except ValueError: # File didn't match the strp format string, so it's not a backup # for this file. Move on to the next one. continue if salt.utils.platform.is_windows(): str_format = '%a %b %d %Y %H-%M-%S.%f' else: str_format = '%a %b %d %Y %H:%M:%S.%f' files.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime(str_format) location = os.path.join(bkdir, fname) files[timestamp]['Size'] = os.stat(location).st_size files[timestamp]['Location'] = location return dict(list(zip( list(range(len(files))), [files[x] for x in sorted(files, reverse=True)[:limit]] ))) list_backup = salt.utils.functools.alias_function(list_backups, 'list_backup') def list_backups_dir(path, limit=None): ''' Lists the previous versions of a directory backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The directory on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups_dir /foo/bar/baz/ ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups_dir: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) # Figure out full path of location of backup folder in minion cache bkdir = os.path.join(bkroot, parent_dir[1:]) if not os.path.isdir(bkdir): return {} files = {} f = dict([(i, len(list(n))) for i, n in itertools.groupby([x.split("_")[0] for x in sorted(os.listdir(bkdir))])]) ff = os.listdir(bkdir) for i, n in six.iteritems(f): ssfile = {} for x in sorted(ff): basename = x.split('_')[0] if i == basename: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(x, strpfmt) except ValueError: # Folder didn't match the strp format string, so it's not a backup # for this folder. Move on to the next one. continue ssfile.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime('%a %b %d %Y %H:%M:%S.%f') location = os.path.join(bkdir, x) ssfile[timestamp]['Size'] = os.stat(location).st_size ssfile[timestamp]['Location'] = location sfiles = dict(list(zip(list(range(n)), [ssfile[x] for x in sorted(ssfile, reverse=True)[:limit]]))) sefiles = {i: sfiles} files.update(sefiles) return files def restore_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Restore a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to restore, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.restore_backup /foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) # Note: This only supports minion backups, so this function will need to be # modified if/when master backups are implemented. ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret salt.utils.files.backup_minion(path, _get_bkroot()) try: shutil.copyfile(backup['Location'], path) except IOError as exc: ret['comment'] = \ 'Unable to restore {0} to {1}: ' \ '{2}'.format(backup['Location'], path, exc) return ret else: ret['result'] = True ret['comment'] = 'Successfully restored {0} to ' \ '{1}'.format(backup['Location'], path) # Try to set proper ownership if not salt.utils.platform.is_windows(): try: fstat = os.stat(path) except (OSError, IOError): ret['comment'] += ', but was unable to set ownership' else: os.chown(path, fstat.st_uid, fstat.st_gid) return ret def delete_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Delete a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to delete, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.delete_backup /var/cache/salt/minion/file_backup/home/foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret try: os.remove(backup['Location']) except IOError as exc: ret['comment'] = 'Unable to remove {0}: {1}'.format(backup['Location'], exc) else: ret['result'] = True ret['comment'] = 'Successfully removed {0}'.format(backup['Location']) return ret remove_backup = salt.utils.functools.alias_function(delete_backup, 'remove_backup') def grep(path, pattern, *opts): ''' Grep for a string in the specified file .. note:: This function's return value is slated for refinement in future versions of Salt path Path to the file to be searched .. note:: Globbing is supported (i.e. ``/var/log/foo/*.log``, but if globbing is being used then the path should be quoted to keep the shell from attempting to expand the glob expression. pattern Pattern to match. For example: ``test``, or ``a[0-5]`` opts Additional command-line flags to pass to the grep command. For example: ``-v``, or ``-i -B2`` .. note:: The options should come after a double-dash (as shown in the examples below) to keep Salt's own argument parser from interpreting them. CLI Example: .. code-block:: bash salt '*' file.grep /etc/passwd nobody salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i -B2 salt '*' file.grep "/etc/sysconfig/network-scripts/*" ipaddr -- -i -l ''' path = os.path.expanduser(path) # Backup the path in case the glob returns nothing _path = path path = glob.glob(path) # If the list is empty no files exist # so we revert back to the original path # so the result is an error. if not path: path = _path split_opts = [] for opt in opts: try: split = salt.utils.args.shlex_split(opt) except AttributeError: split = salt.utils.args.shlex_split(six.text_type(opt)) if len(split) > 1: raise SaltInvocationError( 'Passing multiple command line arguments in a single string ' 'is not supported, please pass the following arguments ' 'separately: {0}'.format(opt) ) split_opts.extend(split) if isinstance(path, list): cmd = ['grep'] + split_opts + [pattern] + path else: cmd = ['grep'] + split_opts + [pattern, path] try: ret = __salt__['cmd.run_all'](cmd, python_shell=False) except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return ret def open_files(by_pid=False): ''' Return a list of all physical open files on the system. CLI Examples: .. code-block:: bash salt '*' file.open_files salt '*' file.open_files by_pid=True ''' # First we collect valid PIDs pids = {} procfs = os.listdir('/proc/') for pfile in procfs: try: pids[int(pfile)] = [] except ValueError: # Not a valid PID, move on pass # Then we look at the open files for each PID files = {} for pid in pids: ppath = '/proc/{0}'.format(pid) try: tids = os.listdir('{0}/task'.format(ppath)) except OSError: continue # Collect the names of all of the file descriptors fd_ = [] #try: # fd_.append(os.path.realpath('{0}/task/{1}exe'.format(ppath, tid))) #except Exception: # pass for fpath in os.listdir('{0}/fd'.format(ppath)): fd_.append('{0}/fd/{1}'.format(ppath, fpath)) for tid in tids: try: fd_.append( os.path.realpath('{0}/task/{1}/exe'.format(ppath, tid)) ) except OSError: continue for tpath in os.listdir('{0}/task/{1}/fd'.format(ppath, tid)): fd_.append('{0}/task/{1}/fd/{2}'.format(ppath, tid, tpath)) fd_ = sorted(set(fd_)) # Loop through file descriptors and return useful data for each file for fdpath in fd_: # Sometimes PIDs and TIDs disappear before we can query them try: name = os.path.realpath(fdpath) # Running stat on the file cuts out all of the sockets and # deleted files from the list os.stat(name) except OSError: continue if name not in files: files[name] = [pid] else: # We still want to know which PIDs are using each file files[name].append(pid) files[name] = sorted(set(files[name])) pids[pid].append(name) pids[pid] = sorted(set(pids[pid])) if by_pid: return pids return files def pardir(): ''' Return the relative parent directory path symbol for underlying OS .. versionadded:: 2014.7.0 This can be useful when constructing Salt Formulas. .. code-block:: jinja {% set pardir = salt['file.pardir']() %} {% set final_path = salt['file.join']('subdir', pardir, 'confdir') %} CLI Example: .. code-block:: bash salt '*' file.pardir ''' return os.path.pardir def normpath(path): ''' Returns Normalize path, eliminating double slashes, etc. .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.normpath'](tpldir + '/../vars.jinja') import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.normpath 'a/b/c/..' ''' return os.path.normpath(path) def basename(path): ''' Returns the final component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- set filename = salt['file.basename'](source_file) %} CLI Example: .. code-block:: bash salt '*' file.basename 'test/test.config' ''' return os.path.basename(path) def dirname(path): ''' Returns the directory component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.dirname'](tpldir) + '/vars.jinja' import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.dirname 'test/path/filename.config' ''' return os.path.dirname(path) def join(*args): ''' Return a normalized file system path for the underlying OS .. versionadded:: 2014.7.0 This can be useful at the CLI but is frequently useful when scripting combining path variables: .. code-block:: jinja {% set www_root = '/var' %} {% set app_dir = 'myapp' %} myapp_config: file: - managed - name: {{ salt['file.join'](www_root, app_dir, 'config.yaml') }} CLI Example: .. code-block:: bash salt '*' file.join '/' 'usr' 'local' 'bin' ''' return os.path.join(*args) def move(src, dst): ''' Move a file or directory CLI Example: .. code-block:: bash salt '*' file.move /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('Source path must be absolute.') if not os.path.isabs(dst): raise SaltInvocationError('Destination path must be absolute.') ret = { 'result': True, 'comment': "'{0}' moved to '{1}'".format(src, dst), } try: shutil.move(src, dst) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move '{0}' to '{1}': {2}".format(src, dst, exc) ) return ret def diskusage(path): ''' Recursively calculate disk usage of path and return it in bytes CLI Example: .. code-block:: bash salt '*' file.diskusage /path/to/check ''' total_size = 0 seen = set() if os.path.isfile(path): stat_structure = os.stat(path) ret = stat_structure.st_size return ret for dirpath, dirnames, filenames in salt.utils.path.os_walk(path): for f in filenames: fp = os.path.join(dirpath, f) try: stat_structure = os.stat(fp) except OSError: continue if stat_structure.st_ino in seen: continue seen.add(stat_structure.st_ino) total_size += stat_structure.st_size ret = total_size return ret
saltstack/salt
salt/modules/file.py
user_to_uid
python
def user_to_uid(user): ''' Convert user name to a uid user user name to convert to its uid CLI Example: .. code-block:: bash salt '*' file.user_to_uid root ''' if user is None: user = salt.utils.user.get_user() try: if isinstance(user, int): return user return pwd.getpwnam(user).pw_uid except KeyError: return ''
Convert user name to a uid user user name to convert to its uid CLI Example: .. code-block:: bash salt '*' file.user_to_uid root
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L280-L300
[ "def get_user():\n '''\n Get the current user\n '''\n if HAS_PWD:\n ret = pwd.getpwuid(os.geteuid()).pw_name\n elif HAS_WIN_FUNCTIONS and salt.utils.win_functions.HAS_WIN32:\n ret = salt.utils.win_functions.get_current_user()\n else:\n raise CommandExecutionError(\n 'Required external library (pwd or win32api) not installed')\n return salt.utils.stringutils.to_unicode(ret)\n" ]
# -*- coding: utf-8 -*- ''' Manage information about regular files, directories, and special files on the minion, set/read user, group, mode, and data ''' # TODO: We should add the capability to do u+r type operations here # some time in the future from __future__ import absolute_import, print_function, unicode_literals # Import python libs import datetime import errno import fnmatch import io import itertools import logging import operator import os import re import shutil import stat import string import sys import tempfile import time import glob import hashlib import mmap from collections import Iterable, Mapping from functools import reduce # pylint: disable=redefined-builtin # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range, zip from salt.ext.six.moves.urllib.parse import urlparse as _urlparse # pylint: enable=import-error,no-name-in-module,redefined-builtin try: import grp import pwd except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.atomicfile import salt.utils.data import salt.utils.dictupdate import salt.utils.filebuffer import salt.utils.files import salt.utils.find import salt.utils.functools import salt.utils.hashutils import salt.utils.itertools import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.templates import salt.utils.url import salt.utils.user from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError, get_error_message as _get_error_message from salt.utils.files import HASHES, HASHES_REVMAP log = logging.getLogger(__name__) __func_alias__ = { 'makedirs_': 'makedirs' } def __virtual__(): ''' Only work on POSIX-like systems ''' # win_file takes care of windows if salt.utils.platform.is_windows(): return ( False, 'The file execution module cannot be loaded: only available on ' 'non-Windows systems - use win_file instead.' ) return True def __clean_tmp(sfn): ''' Clean out a template temp file ''' if sfn.startswith(os.path.join(tempfile.gettempdir(), salt.utils.files.TEMPFILE_PREFIX)): # Don't remove if it exists in file_roots (any saltenv) all_roots = itertools.chain.from_iterable( six.itervalues(__opts__['file_roots'])) in_roots = any(sfn.startswith(root) for root in all_roots) # Only clean up files that exist if os.path.exists(sfn) and not in_roots: os.remove(sfn) def _error(ret, err_msg): ''' Common function for setting error information for return dicts ''' ret['result'] = False ret['comment'] = err_msg return ret def _binary_replace(old, new): ''' This function does NOT do any diffing, it just checks the old and new files to see if either is binary, and provides an appropriate string noting the difference between the two files. If neither file is binary, an empty string is returned. This function should only be run AFTER it has been determined that the files differ. ''' old_isbin = not __utils__['files.is_text'](old) new_isbin = not __utils__['files.is_text'](new) if any((old_isbin, new_isbin)): if all((old_isbin, new_isbin)): return 'Replace binary file' elif old_isbin: return 'Replace binary file with text file' elif new_isbin: return 'Replace text file with binary file' return '' def _get_bkroot(): ''' Get the location of the backup dir in the minion cache ''' # Get the cachedir from the minion config return os.path.join(__salt__['config.get']('cachedir'), 'file_backup') def _splitlines_preserving_trailing_newline(str): ''' Returns a list of the lines in the string, breaking at line boundaries and preserving a trailing newline (if present). Essentially, this works like ``str.striplines(False)`` but preserves an empty line at the end. This is equivalent to the following code: .. code-block:: python lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') ''' lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') return lines def gid_to_group(gid): ''' Convert the group id to the group name on this system gid gid to convert to a group name CLI Example: .. code-block:: bash salt '*' file.gid_to_group 0 ''' try: gid = int(gid) except ValueError: # This is not an integer, maybe it's already the group name? gid = group_to_gid(gid) if gid == '': # Don't even bother to feed it to grp return '' try: return grp.getgrgid(gid).gr_name except (KeyError, NameError): # If group is not present, fall back to the gid. return gid def group_to_gid(group): ''' Convert the group to the gid on this system group group to convert to its gid CLI Example: .. code-block:: bash salt '*' file.group_to_gid root ''' if group is None: return '' try: if isinstance(group, int): return group return grp.getgrnam(group).gr_gid except KeyError: return '' def get_gid(path, follow_symlinks=True): ''' Return the id of the group that owns a given file path file or directory of which to get the gid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_gid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('gid', -1) def get_group(path, follow_symlinks=True): ''' Return the group that owns a given file path file or directory of which to get the group follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_group /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('group', False) def uid_to_user(uid): ''' Convert a uid to a user name uid uid to convert to a username CLI Example: .. code-block:: bash salt '*' file.uid_to_user 0 ''' try: return pwd.getpwuid(uid).pw_name except (KeyError, NameError): # If user is not present, fall back to the uid. return uid def get_uid(path, follow_symlinks=True): ''' Return the id of the user that owns a given file path file or directory of which to get the uid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_uid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('uid', -1) def get_user(path, follow_symlinks=True): ''' Return the user that owns a given file path file or directory of which to get the user follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_user /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('user', False) def get_mode(path, follow_symlinks=True): ''' Return the mode of a file path file or directory of which to get the mode follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_mode /etc/passwd .. versionchanged:: 2014.1.0 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('mode', '') def set_mode(path, mode): ''' Set the mode of a file path file or directory of which to set the mode mode mode to set the path to CLI Example: .. code-block:: bash salt '*' file.set_mode /etc/passwd 0644 ''' path = os.path.expanduser(path) mode = six.text_type(mode).lstrip('0Oo') if not mode: mode = '0' if not os.path.exists(path): raise CommandExecutionError('{0}: File not found'.format(path)) try: os.chmod(path, int(mode, 8)) except Exception: return 'Invalid Mode ' + mode return get_mode(path) def lchown(path, user, group): ''' Chown a file, pass the file the desired user and group without following symlinks. path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 return os.lchown(path, uid, gid) def chown(path, user, group): ''' Chown a file, pass the file the desired user and group path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 if not os.path.exists(path): try: # Broken symlinks will return false, but still need to be chowned return os.lchown(path, uid, gid) except OSError: pass err += 'File not found' if err: return err return os.chown(path, uid, gid) def chgrp(path, group): ''' Change the group of a file path path to the file or directory group group owner CLI Example: .. code-block:: bash salt '*' file.chgrp /etc/passwd root ''' path = os.path.expanduser(path) user = get_user(path) return chown(path, user, group) def _cmp_attrs(path, attrs): ''' .. versionadded:: 2018.3.0 Compare attributes of a given file to given attributes. Returns a pair (list) where first item are attributes to add and second item are to be removed. Please take into account when using this function that some minions will not have lsattr installed. path path to file to compare attributes with. attrs string of attributes to compare against a given file ''' diff = [None, None] # lsattr for AIX is not the same thing as lsattr for linux. if salt.utils.platform.is_aix(): return None try: lattrs = lsattr(path).get(path, '') except AttributeError: # lsattr not installed return None old = [chr for chr in lattrs if chr not in attrs] if old: diff[1] = ''.join(old) new = [chr for chr in attrs if chr not in lattrs] if new: diff[0] = ''.join(new) return diff def lsattr(path): ''' .. versionadded:: 2018.3.0 .. versionchanged:: 2018.3.1 If ``lsattr`` is not installed on the system, ``None`` is returned. .. versionchanged:: 2018.3.4 If on ``AIX``, ``None`` is returned even if in filesystem as lsattr on ``AIX`` is not the same thing as the linux version. Obtain the modifiable attributes of the given file. If path is to a directory, an empty list is returned. path path to file to obtain attributes of. File/directory must exist. CLI Example: .. code-block:: bash salt '*' file.lsattr foo1.txt ''' if not salt.utils.path.which('lsattr') or salt.utils.platform.is_aix(): return None if not os.path.exists(path): raise SaltInvocationError("File or directory does not exist: " + path) cmd = ['lsattr', path] result = __salt__['cmd.run'](cmd, ignore_retcode=True, python_shell=False) results = {} for line in result.splitlines(): if not line.startswith('lsattr: '): vals = line.split(None, 1) results[vals[1]] = re.findall(r"[aAcCdDeijPsStTu]", vals[0]) return results def chattr(*files, **kwargs): ''' .. versionadded:: 2018.3.0 Change the attributes of files. This function accepts one or more files and the following options: operator Can be wither ``add`` or ``remove``. Determines whether attributes should be added or removed from files attributes One or more of the following characters: ``aAcCdDeijPsStTu``, representing attributes to add to/remove from files version a version number to assign to the file(s) flags One or more of the following characters: ``RVf``, representing flags to assign to chattr (recurse, verbose, suppress most errors) CLI Example: .. code-block:: bash salt '*' file.chattr foo1.txt foo2.txt operator=add attributes=ai salt '*' file.chattr foo3.txt operator=remove attributes=i version=2 ''' operator = kwargs.pop('operator', None) attributes = kwargs.pop('attributes', None) flags = kwargs.pop('flags', None) version = kwargs.pop('version', None) if (operator is None) or (operator not in ('add', 'remove')): raise SaltInvocationError( "Need an operator: 'add' or 'remove' to modify attributes.") if attributes is None: raise SaltInvocationError("Need attributes: [aAcCdDeijPsStTu]") cmd = ['chattr'] if operator == "add": attrs = '+{0}'.format(attributes) elif operator == "remove": attrs = '-{0}'.format(attributes) cmd.append(attrs) if flags is not None: cmd.append('-{0}'.format(flags)) if version is not None: cmd.extend(['-v', version]) cmd.extend(files) result = __salt__['cmd.run'](cmd, python_shell=False) if bool(result): raise CommandExecutionError( "chattr failed to run, possibly due to bad parameters.") return True def get_sum(path, form='sha256'): ''' Return the checksum for the given file. The following checksum algorithms are supported: * md5 * sha1 * sha224 * sha256 **(default)** * sha384 * sha512 path path to the file or directory form desired sum format CLI Example: .. code-block:: bash salt '*' file.get_sum /etc/passwd sha512 ''' path = os.path.expanduser(path) if not os.path.isfile(path): return 'File not found' return salt.utils.hashutils.get_hash(path, form, 4096) def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` path path to the file or directory form desired sum format chunk_size amount to sum at once CLI Example: .. code-block:: bash salt '*' file.get_hash /etc/shadow ''' return salt.utils.hashutils.get_hash(os.path.expanduser(path), form, chunk_size) def get_source_sum(file_name='', source='', source_hash=None, source_hash_name=None, saltenv='base'): ''' .. versionadded:: 2016.11.0 Used by :py:func:`file.get_managed <salt.modules.file.get_managed>` to obtain the hash and hash type from the parameters specified below. file_name Optional file name being managed, for matching with :py:func:`file.extract_hash <salt.modules.file.extract_hash>`. source Source file, as used in :py:mod:`file <salt.states.file>` and other states. If ``source_hash`` refers to a file containing hashes, then this filename will be used to match a filename in that file. If the ``source_hash`` is a hash expression, then this argument will be ignored. source_hash Hash file/expression, as used in :py:mod:`file <salt.states.file>` and other states. If this value refers to a remote URL or absolute path to a local file, it will be cached and :py:func:`file.extract_hash <salt.modules.file.extract_hash>` will be used to obtain a hash from it. source_hash_name Specific file name to look for when ``source_hash`` refers to a remote file, used to disambiguate ambiguous matches. saltenv : base Salt fileserver environment from which to retrieve the source_hash. This value will only be used when ``source_hash`` refers to a file on the Salt fileserver (i.e. one beginning with ``salt://``). CLI Example: .. code-block:: bash salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=499ae16dcae71eeb7c3a30c75ea7a1a6 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 source_hash_name=./dir2/foo.tar.gz ''' def _invalid_source_hash_format(): ''' DRY helper for reporting invalid source_hash input ''' raise CommandExecutionError( 'Source hash {0} format is invalid. The supported formats are: ' '1) a hash, 2) an expression in the format <hash_type>=<hash>, or ' '3) either a path to a local file containing hashes, or a URI of ' 'a remote hash file. Supported protocols for remote hash files ' 'are: {1}. The hash may also not be of a valid length, the ' 'following are supported hash types and lengths: {2}.'.format( source_hash, ', '.join(salt.utils.files.VALID_PROTOS), ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) hash_fn = None if os.path.isabs(source_hash): hash_fn = source_hash else: try: proto = _urlparse(source_hash).scheme if proto in salt.utils.files.VALID_PROTOS: hash_fn = __salt__['cp.cache_file'](source_hash, saltenv) if not hash_fn: raise CommandExecutionError( 'Source hash file {0} not found'.format(source_hash) ) else: if proto != '': # Some unsupported protocol (e.g. foo://) is being used. # We'll get into this else block if a hash expression # (like md5=<md5 checksum here>), but in those cases, the # protocol will be an empty string, in which case we avoid # this error condition. _invalid_source_hash_format() except (AttributeError, TypeError): _invalid_source_hash_format() if hash_fn is not None: ret = extract_hash(hash_fn, '', file_name, source, source_hash_name) if ret is None: _invalid_source_hash_format() ret['hsum'] = ret['hsum'].lower() return ret else: # The source_hash is a hash expression ret = {} try: ret['hash_type'], ret['hsum'] = \ [x.strip() for x in source_hash.split('=', 1)] except AttributeError: _invalid_source_hash_format() except ValueError: # No hash type, try to figure out by hash length if not re.match('^[{0}]+$'.format(string.hexdigits), source_hash): _invalid_source_hash_format() ret['hsum'] = source_hash source_hash_len = len(source_hash) if source_hash_len in HASHES_REVMAP: ret['hash_type'] = HASHES_REVMAP[source_hash_len] else: _invalid_source_hash_format() if ret['hash_type'] not in HASHES: raise CommandExecutionError( 'Invalid hash type \'{0}\'. Supported hash types are: {1}. ' 'Either remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to a supported type.' .format(ret['hash_type'], ', '.join(HASHES), ret['hsum']) ) else: hsum_len = len(ret['hsum']) if hsum_len not in HASHES_REVMAP: _invalid_source_hash_format() elif hsum_len != HASHES[ret['hash_type']]: raise CommandExecutionError( 'Invalid length ({0}) for hash type \'{1}\'. Either ' 'remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to \'{3}\''.format( hsum_len, ret['hash_type'], ret['hsum'], HASHES_REVMAP[hsum_len], ) ) ret['hsum'] = ret['hsum'].lower() return ret def check_hash(path, file_hash): ''' Check if a file matches the given hash string Returns ``True`` if the hash matches, otherwise ``False``. path Path to a file local to the minion. hash The hash to check against the file specified in the ``path`` argument. .. versionchanged:: 2016.11.4 For this and newer versions the hash can be specified without an accompanying hash type (e.g. ``e138491e9d5b97023cea823fe17bac22``), but for earlier releases it is necessary to also specify the hash type in the format ``<hash_type>=<hash_value>`` (e.g. ``md5=e138491e9d5b97023cea823fe17bac22``). CLI Example: .. code-block:: bash salt '*' file.check_hash /etc/fstab e138491e9d5b97023cea823fe17bac22 salt '*' file.check_hash /etc/fstab md5=e138491e9d5b97023cea823fe17bac22 ''' path = os.path.expanduser(path) if not isinstance(file_hash, six.string_types): raise SaltInvocationError('hash must be a string') for sep in (':', '='): if sep in file_hash: hash_type, hash_value = file_hash.split(sep, 1) break else: hash_value = file_hash hash_len = len(file_hash) hash_type = HASHES_REVMAP.get(hash_len) if hash_type is None: raise SaltInvocationError( 'Hash {0} (length: {1}) could not be matched to a supported ' 'hash type. The supported hash types and lengths are: ' '{2}'.format( file_hash, hash_len, ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) return get_hash(path, hash_type) == hash_value def find(path, *args, **kwargs): ''' Approximate the Unix ``find(1)`` command and return a list of paths that meet the specified criteria. The options include match criteria: .. code-block:: text name = path-glob # case sensitive iname = path-glob # case insensitive regex = path-regex # case sensitive iregex = path-regex # case insensitive type = file-types # match any listed type user = users # match any listed user group = groups # match any listed group size = [+-]number[size-unit] # default unit = byte mtime = interval # modified since date grep = regex # search file contents and/or actions: .. code-block:: text delete [= file-types] # default type = 'f' exec = command [arg ...] # where {} is replaced by pathname print [= print-opts] and/or depth criteria: .. code-block:: text maxdepth = maximum depth to transverse in path mindepth = minimum depth to transverse before checking files or directories The default action is ``print=path`` ``path-glob``: .. code-block:: text * = match zero or more chars ? = match any char [abc] = match a, b, or c [!abc] or [^abc] = match anything except a, b, and c [x-y] = match chars x through y [!x-y] or [^x-y] = match anything except chars x through y {a,b,c} = match a or b or c ``path-regex``: a Python Regex (regular expression) pattern to match pathnames ``file-types``: a string of one or more of the following: .. code-block:: text a: all file types b: block device c: character device d: directory p: FIFO (named pipe) f: plain file l: symlink s: socket ``users``: a space and/or comma separated list of user names and/or uids ``groups``: a space and/or comma separated list of group names and/or gids ``size-unit``: .. code-block:: text b: bytes k: kilobytes m: megabytes g: gigabytes t: terabytes interval: .. code-block:: text [<num>w] [<num>d] [<num>h] [<num>m] [<num>s] where: w: week d: day h: hour m: minute s: second print-opts: a comma and/or space separated list of one or more of the following: .. code-block:: text group: group name md5: MD5 digest of file contents mode: file permissions (as integer) mtime: last modification time (as time_t) name: file basename path: file absolute path size: file size in bytes type: file type user: user name CLI Examples: .. code-block:: bash salt '*' file.find / type=f name=\\*.bak size=+10m salt '*' file.find /var mtime=+30d size=+10m print=path,size,mtime salt '*' file.find /var/log name=\\*.[0-9] mtime=+30d size=+10m delete ''' if 'delete' in args: kwargs['delete'] = 'f' elif 'print' in args: kwargs['print'] = 'path' try: finder = salt.utils.find.Finder(kwargs) except ValueError as ex: return 'error: {0}'.format(ex) ret = [item for i in [finder.find(p) for p in glob.glob(os.path.expanduser(path))] for item in i] ret.sort() return ret def _sed_esc(string, escape_all=False): ''' Escape single quotes and forward slashes ''' special_chars = "^.[$()|*+?{" string = string.replace("'", "'\"'\"'").replace("/", "\\/") if escape_all is True: for char in special_chars: string = string.replace(char, "\\" + char) return string def sed(path, before, after, limit='', backup='.bak', options='-r -e', flags='g', escape_all=False, negate_match=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup options : ``-r -e`` Options to pass to sed flags : ``g`` Flags to modify the sed search; e.g., ``i`` for case-insensitive pattern matching negate_match : False Negate the search command (``!``) .. versionadded:: 0.17.0 Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # path = os.path.expanduser(path) if not os.path.exists(path): return False # Mandate that before and after are strings before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.append('-i{0}'.format(backup) if backup else '-i') cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}{negate_match}s/{before}/{after}/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', negate_match='!' if negate_match else '', before=before, after=after, flags=flags ) ) cmd.append(path) return __salt__['cmd.run_all'](cmd, python_shell=False) def sed_contains(path, text, limit='', flags='g'): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the file at ``path`` contains ``text``. Utilizes sed to perform the search (line-wise search). Note: the ``p`` flag will be added to any flags you pass in. CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' # Largely inspired by Fabric's contrib.files.contains() path = os.path.expanduser(path) if not os.path.exists(path): return False before = _sed_esc(six.text_type(text), False) limit = _sed_esc(six.text_type(limit), False) options = '-n -r -e' if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}s/{before}/$/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', before=before, flags='p{0}'.format(flags) ) ) cmd.append(path) result = __salt__['cmd.run'](cmd, python_shell=False) return bool(result) def psed(path, before, after, limit='', backup='.bak', flags='gMS', escape_all=False, multi=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file (pure Python version) Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup flags : ``gMS`` Flags to modify the search. Valid values are: - ``g``: Replace all occurrences of the pattern, not just the first. - ``I``: Ignore case. - ``L``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\s`` and ``\\S`` dependent on the locale. - ``M``: Treat multiple lines as a single line. - ``S``: Make `.` match all characters, including newlines. - ``U``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\d``, ``\\D``, ``\\s`` and ``\\S`` dependent on Unicode. - ``X``: Verbose (whitespace is ignored). multi: ``False`` If True, treat the entire file as a single line Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # # Mandate that before and after are strings path = os.path.expanduser(path) multi = bool(multi) before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) # The pattern to replace with does not need to be escaped!!! # after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) shutil.copy2(path, '{0}{1}'.format(path, backup)) with salt.utils.files.fopen(path, 'w') as ofile: with salt.utils.files.fopen('{0}{1}'.format(path, backup), 'r') as ifile: if multi is True: for line in ifile.readline(): ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(line), before, after, limit, flags ) ) ) else: ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(ifile.read()), before, after, limit, flags ) ) ) RE_FLAG_TABLE = {'I': re.I, 'L': re.L, 'M': re.M, 'S': re.S, 'U': re.U, 'X': re.X} def _psed(text, before, after, limit, flags): ''' Does the actual work for file.psed, so that single lines can be passed in ''' atext = text if limit: limit = re.compile(limit) comps = text.split(limit) atext = ''.join(comps[1:]) count = 1 if 'g' in flags: count = 0 flags = flags.replace('g', '') aflags = 0 for flag in flags: aflags |= RE_FLAG_TABLE[flag] before = re.compile(before, flags=aflags) text = re.sub(before, after, atext, count=count) return text def uncomment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Uncomment specified commented lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be uncommented. This regex should not include the comment character. A leading ``^`` character will be stripped for convenience (for easily switching between comment() and uncomment()). char : ``#`` The character to remove in order to uncomment a line backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup CLI Example: .. code-block:: bash salt '*' file.uncomment /etc/hosts.deny 'ALL: PARANOID' ''' return comment_line(path=path, regex=regex, char=char, cmnt=False, backup=backup) def comment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Comment out specified lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be commented; this pattern will be wrapped in parenthesis and will move any preceding/trailing ``^`` or ``$`` characters outside the parenthesis (e.g., the pattern ``^foo$`` will be rewritten as ``^(foo)$``) char : ``#`` The character to be inserted at the beginning of a line in order to comment it out backup : ``.bak`` The file will be backed up before edit with this file extension .. warning:: This backup will be overwritten each time ``sed`` / ``comment`` / ``uncomment`` is called. Meaning the backup will only be useful after the first invocation. CLI Example: .. code-block:: bash salt '*' file.comment /etc/modules pcspkr ''' return comment_line(path=path, regex=regex, char=char, cmnt=True, backup=backup) def comment_line(path, regex, char='#', cmnt=True, backup='.bak'): r''' Comment or Uncomment a line in a text file. :param path: string The full path to the text file. :param regex: string A regex expression that begins with ``^`` that will find the line you wish to comment. Can be as simple as ``^color =`` :param char: string The character used to comment a line in the type of file you're referencing. Default is ``#`` :param cmnt: boolean True to comment the line. False to uncomment the line. Default is True. :param backup: string The file extension to give the backup file. Default is ``.bak`` Set to False/None to not keep a backup. :return: boolean Returns True if successful, False if not CLI Example: The following example will comment out the ``pcspkr`` line in the ``/etc/modules`` file using the default ``#`` character and create a backup file named ``modules.bak`` .. code-block:: bash salt '*' file.comment_line '/etc/modules' '^pcspkr' CLI Example: The following example will uncomment the ``log_level`` setting in ``minion`` config file if it is set to either ``warning``, ``info``, or ``debug`` using the ``#`` character and create a backup file named ``minion.bk`` .. code-block:: bash salt '*' file.comment_line 'C:\salt\conf\minion' '^log_level: (warning|info|debug)' '#' False '.bk' ''' # Get the regex for comment or uncomment if cmnt: regex = '{0}({1}){2}'.format( '^' if regex.startswith('^') else '', regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') else: regex = r'^{0}\s*({1}){2}'.format( char, regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') # Load the real path to the file path = os.path.realpath(os.path.expanduser(path)) # Make sure the file exists if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) # Make sure it is a text file if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}'.format(path)) # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes found = False # Dictionaries for comparing changes orig_file = [] new_file = [] # Buffer size for fopen bufsize = os.path.getsize(path) try: # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: # Is it in this line line = salt.utils.stringutils.to_unicode(line) if re.match(regex, line): # Load lines into dictionaries, set found to True orig_file.append(line) if cmnt: new_file.append('{0}{1}'.format(char, line)) else: new_file.append(line.lstrip(char)) found = True except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) # We've searched the whole file. If we didn't find anything, return False if not found: return False if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Create a copy to read from and to use as a backup later try: temp_file = _mkstemp_copy(path=path, preserve_inode=False) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) try: # Open the file in write mode mode = 'wb' if six.PY2 and salt.utils.platform.is_windows() else 'w' with salt.utils.files.fopen(path, mode=mode, buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: line = salt.utils.stringutils.to_unicode(line) try: # Is it in this line if re.match(regex, line): # Write the new line if cmnt: wline = '{0}{1}'.format(char, line) else: wline = line.lstrip(char) else: # Write the existing line (no change) wline = line wline = salt.utils.stringutils.to_bytes(wline) \ if six.PY2 and salt.utils.platform.is_windows() \ else salt.utils.stringutils.to_str(wline) w_file.write(wline) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if backup: # Move the backup file to the original directory backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: os.remove(temp_file) if not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) # Return a diff using the two dictionaries return __utils__['stringutils.get_diff'](orig_file, new_file) def _get_flags(flags): ''' Return an integer appropriate for use as a flag for the re module from a list of human-readable strings .. code-block:: python >>> _get_flags(['MULTILINE', 'IGNORECASE']) 10 >>> _get_flags('MULTILINE') 8 >>> _get_flags(2) 2 ''' if isinstance(flags, six.string_types): flags = [flags] if isinstance(flags, Iterable) and not isinstance(flags, Mapping): _flags_acc = [] for flag in flags: _flag = getattr(re, six.text_type(flag).upper()) if not isinstance(_flag, six.integer_types): raise SaltInvocationError( 'Invalid re flag given: {0}'.format(flag) ) _flags_acc.append(_flag) return reduce(operator.__or__, _flags_acc) elif isinstance(flags, six.integer_types): return flags else: raise SaltInvocationError( 'Invalid re flags: "{0}", must be given either as a single flag ' 'string, a list of strings, or as an integer'.format(flags) ) def _add_flags(flags, new_flags): ''' Combine ``flags`` and ``new_flags`` ''' flags = _get_flags(flags) new_flags = _get_flags(new_flags) return flags | new_flags def _mkstemp_copy(path, preserve_inode=True): ''' Create a temp file and move/copy the contents of ``path`` to the temp file. Return the path to the temp file. path The full path to the file whose contents will be moved/copied to a temp file. Whether it's moved or copied depends on the value of ``preserve_inode``. preserve_inode Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). Default is ``True``. ''' temp_file = None # Create the temp file try: temp_file = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to create temp file. " "Exception: {0}".format(exc) ) # use `copy` to preserve the inode of the # original file, and thus preserve hardlinks # to the inode. otherwise, use `move` to # preserve prior behavior, which results in # writing the file to a new inode. if preserve_inode: try: shutil.copy2(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to copy file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: try: shutil.move(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) return temp_file def _starts_till(src, probe, strip_comments=True): ''' Returns True if src and probe at least matches at the beginning till some point. ''' def _strip_comments(txt): ''' Strip possible comments. Usually comments are one or two symbols at the beginning of the line, separated with space ''' buff = txt.split(" ", 1) return len(buff) == 2 and len(buff[0]) < 2 and buff[1] or txt def _to_words(txt): ''' Split by words ''' return txt and [w for w in txt.strip().split(" ") if w.strip()] or txt no_match = -1 equal = 0 if not src or not probe: return no_match src = src.rstrip('\n\r') probe = probe.rstrip('\n\r') if src == probe: return equal src = _to_words(strip_comments and _strip_comments(src) or src) probe = _to_words(strip_comments and _strip_comments(probe) or probe) a_buff, b_buff = len(src) < len(probe) and (src, probe) or (probe, src) b_buff = ' '.join(b_buff) for idx in range(len(a_buff)): prb = ' '.join(a_buff[:-(idx + 1)]) if prb and b_buff.startswith(prb): return idx return no_match def _regex_to_static(src, regex): ''' Expand regular expression to static match. ''' if not src or not regex: return None try: compiled = re.compile(regex, re.DOTALL) src = [line for line in src if compiled.search(line) or line.count(regex)] except Exception as ex: raise CommandExecutionError("{0}: '{1}'".format(_get_error_message(ex), regex)) return src and src or [] def _assert_occurrence(probe, target, amount=1): ''' Raise an exception, if there are different amount of specified occurrences in src. ''' occ = len(probe) if occ > amount: msg = 'more than' elif occ < amount: msg = 'less than' elif not occ: msg = 'no' else: msg = None if msg: raise CommandExecutionError('Found {0} expected occurrences in "{1}" expression'.format(msg, target)) return occ def _set_line_indent(src, line, indent): ''' Indent the line with the source line. ''' if not indent: return line idt = [] for c in src: if c not in ['\t', ' ']: break idt.append(c) return ''.join(idt) + line.lstrip() def _get_eol(line): match = re.search('((?<!\r)\n|\r(?!\n)|\r\n)$', line) return match and match.group() or '' def _set_line_eol(src, line): ''' Add line ending ''' line_ending = _get_eol(src) or os.linesep return line.rstrip() + line_ending def _insert_line_before(idx, body, content, indent): if not idx or (idx and _starts_till(body[idx - 1], content) < 0): cnd = _set_line_indent(body[idx], content, indent) body.insert(idx, cnd) return body def _insert_line_after(idx, body, content, indent): # No duplicates or append, if "after" is the last line next_line = idx + 1 < len(body) and body[idx + 1] or None if next_line is None or _starts_till(next_line, content) < 0: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) return body def line(path, content=None, match=None, mode=None, location=None, before=None, after=None, show_changes=True, backup=False, quiet=False, indent=True): ''' .. versionadded:: 2015.8.0 Edit a line in the configuration file. The ``path`` and ``content`` arguments are required, as well as passing in one of the ``mode`` options. path Filesystem path to the file to be edited. content Content of the line. Allowed to be empty if mode=delete. match Match the target line for an action by a fragment of a string or regular expression. If neither ``before`` nor ``after`` are provided, and ``match`` is also ``None``, match becomes the ``content`` value. mode Defines how to edit a line. One of the following options is required: - ensure If line does not exist, it will be added. This is based on the ``content`` argument. - replace If line already exists, it will be replaced. - delete Delete the line, once found. - insert Insert a line. .. note:: If ``mode=insert`` is used, at least one of the following options must also be defined: ``location``, ``before``, or ``after``. If ``location`` is used, it takes precedence over the other two options. location Defines where to place content in the line. Note this option is only used when ``mode=insert`` is specified. If a location is passed in, it takes precedence over both the ``before`` and ``after`` kwargs. Valid locations are: - start Place the content at the beginning of the file. - end Place the content at the end of the file. before Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. after Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. show_changes Output a unified diff of the old file and the new file. If ``False`` return a boolean if any changes were made. Default is ``True`` .. note:: Using this option will store two copies of the file in-memory (the original version and the edited version) in order to generate the diff. backup Create a backup of the original file with the extension: "Year-Month-Day-Hour-Minutes-Seconds". quiet Do not raise any exceptions. E.g. ignore the fact that the file that is tried to be edited does not exist and nothing really happened. indent Keep indentation with the previous line. This option is not considered when the ``delete`` mode is specified. CLI Example: .. code-block:: bash salt '*' file.line /etc/nsswitch.conf "networks:\tfiles dns" after="hosts:.*?" mode='ensure' .. note:: If an equal sign (``=``) appears in an argument to a Salt command, it is interpreted as a keyword argument in the format of ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.line /path/to/file content="CREATEMAIL_SPOOL=no" match="CREATE_MAIL_SPOOL=yes" mode="replace" ''' path = os.path.realpath(os.path.expanduser(path)) if not os.path.isfile(path): if not quiet: raise CommandExecutionError('File "{0}" does not exists or is not a file.'.format(path)) return False # No changes had happened mode = mode and mode.lower() or mode if mode not in ['insert', 'ensure', 'delete', 'replace']: if mode is None: raise CommandExecutionError('Mode was not defined. How to process the file?') else: raise CommandExecutionError('Unknown mode: "{0}"'.format(mode)) # We've set the content to be empty in the function params but we want to make sure # it gets passed when needed. Feature #37092 empty_content_modes = ['delete'] if mode not in empty_content_modes and content is None: raise CommandExecutionError('Content can only be empty if mode is "{0}"'.format(', '.join(empty_content_modes))) del empty_content_modes # Before/after has privilege. If nothing defined, match is used by content. if before is None and after is None and not match: match = content with salt.utils.files.fopen(path, mode='r') as fp_: body = salt.utils.data.decode_list(fp_.readlines()) body_before = hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() # Add empty line at the end if last line ends with eol. # Allows simpler code if body and _get_eol(body[-1]): body.append('') after = _regex_to_static(body, after) before = _regex_to_static(body, before) match = _regex_to_static(body, match) if os.stat(path).st_size == 0 and mode in ('delete', 'replace'): log.warning('Cannot find text to %s. File \'%s\' is empty.', mode, path) body = [] elif mode == 'delete' and match: body = [line for line in body if line != match[0]] elif mode == 'replace' and match: idx = body.index(match[0]) file_line = body.pop(idx) body.insert(idx, _set_line_indent(file_line, content, indent)) elif mode == 'insert': if not location and not before and not after: raise CommandExecutionError('On insert must be defined either "location" or "before/after" conditions.') if not location: if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') out = [] in_range = False for line in body: if line == after[0]: in_range = True elif line == before[0] and in_range: cnd = _set_line_indent(line, content, indent) out.append(cnd) out.append(line) body = out if before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif after and not before: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: if location == 'start': if body: body.insert(0, _set_line_eol(body[0], content)) else: body.append(content + os.linesep) elif location == 'end': body.append(_set_line_indent(body[-1], content, indent) if body else content) elif mode == 'ensure': if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') is_there = bool([l for l in body if l.count(content)]) if not is_there: idx = body.index(after[0]) if idx < (len(body) - 1) and body[idx + 1] == before[0]: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) else: raise CommandExecutionError('Found more than one line between ' 'boundaries "before" and "after".') elif before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif not before and after: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: raise CommandExecutionError("Wrong conditions? " "Unable to ensure line without knowing " "where to put it before and/or after.") if body: for idx, line in enumerate(body): if not _get_eol(line) and idx+1 < len(body): prev = idx and idx-1 or 1 body[idx] = _set_line_eol(body[prev], line) # We do not need empty line at the end anymore if '' == body[-1]: body.pop() changed = body_before != hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() if backup and changed and __opts__['test'] is False: try: temp_file = _mkstemp_copy(path=path, preserve_inode=True) shutil.move(temp_file, '{0}.{1}'.format(path, time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime()))) except (OSError, IOError) as exc: raise CommandExecutionError("Unable to create the backup file of {0}. Exception: {1}".format(path, exc)) changes_diff = None if changed: if show_changes: with salt.utils.files.fopen(path, 'r') as fp_: path_content = salt.utils.data.decode_list(fp_.read().splitlines(True)) changes_diff = __utils__['stringutils.get_diff'](path_content, body) if __opts__['test'] is False: fh_ = None try: # Make sure we match the file mode from salt.utils.files.fopen if six.PY2 and salt.utils.platform.is_windows(): mode = 'wb' body = salt.utils.data.encode_list(body) else: mode = 'w' body = salt.utils.data.decode_list(body, to_str=True) fh_ = salt.utils.atomicfile.atomic_open(path, mode) fh_.writelines(body) finally: if fh_: fh_.close() return show_changes and changes_diff or changed def replace(path, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, backup='.bak', dry_run=False, search_only=False, show_changes=True, ignore_if_missing=False, preserve_inode=True, backslash_literal=False, ): ''' .. versionadded:: 0.17.0 Replace occurrences of a pattern in a file. If ``show_changes`` is ``True``, then a diff of what changed will be returned, otherwise a ``True`` will be returned when changes are made, and ``False`` when no changes are made. This is a pure Python implementation that wraps Python's :py:func:`~re.sub`. path Filesystem path to the file to be edited. If a symlink is specified, it will be resolved to its target. pattern A regular expression, to be matched using Python's :py:func:`~re.search`. repl The replacement text count : 0 Maximum number of pattern occurrences to be replaced. If count is a positive integer ``n``, only ``n`` occurrences will be replaced, otherwise all occurrences will be replaced. flags (list or int) A list of flags defined in the ``re`` module documentation from the Python standard library. Each list item should be a string that will correlate to the human-friendly flag name. E.g., ``['IGNORECASE', 'MULTILINE']``. Optionally, ``flags`` may be an int, with a value corresponding to the XOR (``|``) of all the desired flags. Defaults to 8 (which supports 'MULTILINE'). bufsize (int or str) How much of the file to buffer into memory at once. The default value ``1`` processes one line at a time. The special value ``file`` may be specified which will read the entire file into memory before processing. append_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True``, and pattern is not found, then the content will be appended to the file. prepend_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True`` and pattern is not found, then the content will be prepended to the file. not_found_content .. versionadded:: 2014.7.0 Content to use for append/prepend if not found. If None (default), uses ``repl``. Useful when ``repl`` uses references to group in pattern. backup : .bak The file extension to use for a backup of the file before editing. Set to ``False`` to skip making a backup. dry_run : False If set to ``True``, no changes will be made to the file, the function will just return the changes that would have been made (or a ``True``/``False`` value if ``show_changes`` is set to ``False``). search_only : False If set to true, this no changes will be performed on the file, and this function will simply return ``True`` if the pattern was matched, and ``False`` if not. show_changes : True If ``True``, return a diff of changes made. Otherwise, return ``True`` if changes were made, and ``False`` if not. .. note:: Using this option will store two copies of the file in memory (the original version and the edited version) in order to generate the diff. This may not normally be a concern, but could impact performance if used with large files. ignore_if_missing : False .. versionadded:: 2015.8.0 If set to ``True``, this function will simply return ``False`` if the file doesn't exist. Otherwise, an error will be thrown. preserve_inode : True .. versionadded:: 2015.8.0 Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). backslash_literal : False .. versionadded:: 2016.11.7 Interpret backslashes as literal backslashes for the repl and not escape characters. This will help when using append/prepend so that the backslashes are not interpreted for the repl on the second run of the state. If an equal sign (``=``) appears in an argument to a Salt command it is interpreted as a keyword argument in the format ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.replace /path/to/file pattern='=' repl=':' salt '*' file.replace /path/to/file pattern="bind-address\\s*=" repl='bind-address:' CLI Examples: .. code-block:: bash salt '*' file.replace /etc/httpd/httpd.conf pattern='LogLevel warn' repl='LogLevel info' salt '*' file.replace /some/file pattern='before' repl='after' flags='[MULTILINE, IGNORECASE]' ''' symlink = False if is_link(path): symlink = True target_path = os.readlink(path) given_path = os.path.expanduser(path) path = os.path.realpath(os.path.expanduser(path)) if not os.path.exists(path): if ignore_if_missing: return False else: raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if search_only and (append_if_not_found or prepend_if_not_found): raise SaltInvocationError( 'search_only cannot be used with append/prepend_if_not_found' ) if append_if_not_found and prepend_if_not_found: raise SaltInvocationError( 'Only one of append and prepend_if_not_found is permitted' ) flags_num = _get_flags(flags) cpattern = re.compile(salt.utils.stringutils.to_bytes(pattern), flags_num) filesize = os.path.getsize(path) if bufsize == 'file': bufsize = filesize # Search the file; track if any changes have been made for the return val has_changes = False orig_file = [] # used for show_changes and change detection new_file = [] # used for show_changes and change detection if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Avoid TypeErrors by forcing repl to be bytearray related to mmap # Replacement text may contains integer: 123 for example repl = salt.utils.stringutils.to_bytes(six.text_type(repl)) if not_found_content: not_found_content = salt.utils.stringutils.to_bytes(not_found_content) found = False temp_file = None content = salt.utils.stringutils.to_unicode(not_found_content) \ if not_found_content and (prepend_if_not_found or append_if_not_found) \ else salt.utils.stringutils.to_unicode(repl) try: # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes r_data = None # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: try: # mmap throws a ValueError if the file is empty. r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) except (ValueError, mmap.error): # size of file in /proc is 0, but contains data r_data = salt.utils.stringutils.to_bytes("".join(r_file)) if search_only: # Just search; bail as early as a match is found if re.search(cpattern, r_data): return True # `with` block handles file closure else: return False else: result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) # found anything? (even if no change) if nrepl > 0: found = True # Identity check the potential change has_changes = True if pattern != repl else has_changes if prepend_if_not_found or append_if_not_found: # Search for content, to avoid pre/appending the # content if it was pre/appended in a previous run. if re.search(salt.utils.stringutils.to_bytes('^{0}($|(?=\r\n))'.format(re.escape(content))), r_data, flags=flags_num): # Content was found, so set found. found = True orig_file = r_data.read(filesize).splitlines(True) \ if isinstance(r_data, mmap.mmap) \ else r_data.splitlines(True) new_file = result.splitlines(True) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() if has_changes and not dry_run: # Write the replacement text in this block. try: # Create a copy to read from and to use as a backup later temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) r_data = None try: # Open the file in write mode with salt.utils.files.fopen(path, mode='w', buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='r', buffering=bufsize) as r_file: r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) try: w_file.write(salt.utils.stringutils.to_str(result)) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if not found and (append_if_not_found or prepend_if_not_found): if not_found_content is None: not_found_content = repl if prepend_if_not_found: new_file.insert(0, not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) else: # append_if_not_found # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(salt.utils.stringutils.to_bytes(os.linesep)): new_file[-1] += salt.utils.stringutils.to_bytes(os.linesep) new_file.append(not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) has_changes = True if not dry_run: try: # Create a copy to read from and for later use as a backup temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line)) finally: fh_.close() if backup and has_changes and not dry_run: # keep the backup only if it was requested # and only if there were any changes backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) if symlink: symlink_backup = '{0}{1}'.format(given_path, backup) target_backup = '{0}{1}'.format(target_path, backup) # Always clobber any existing symlink backup # to match the behaviour of the 'backup' option try: os.symlink(target_backup, symlink_backup) except OSError: os.remove(symlink_backup) os.symlink(target_backup, symlink_backup) except Exception: raise CommandExecutionError( "Unable create backup symlink '{0}'. " "Target was '{1}'. " "Exception: {2}".format(symlink_backup, target_backup, exc) ) elif temp_file: try: os.remove(temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to delete temp file '{0}'. " "Exception: {1}".format(temp_file, exc) ) if not dry_run and not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) differences = __utils__['stringutils.get_diff'](orig_file, new_file) if show_changes: return differences # We may have found a regex line match but don't need to change the line # (for situations where the pattern also matches the repl). Revert the # has_changes flag to False if the final result is unchanged. if not differences: has_changes = False return has_changes def blockreplace(path, marker_start='#-- start managed zone --', marker_end='#-- end managed zone --', content='', append_if_not_found=False, prepend_if_not_found=False, backup='.bak', dry_run=False, show_changes=True, append_newline=False, insert_before_match=None, insert_after_match=None): ''' .. versionadded:: 2014.1.0 Replace content of a text block in a file, delimited by line markers A block of content delimited by comments can help you manage several lines entries without worrying about old entries removal. .. note:: This function will store two copies of the file in-memory (the original version and the edited version) in order to detect changes and only edit the targeted file if necessary. path Filesystem path to the file to be edited marker_start The line content identifying a line as the start of the content block. Note that the whole line containing this marker will be considered, so whitespace or extra content before or after the marker is included in final output marker_end The line content identifying the end of the content block. As of versions 2017.7.5 and 2018.3.1, everything up to the text matching the marker will be replaced, so it's important to ensure that your marker includes the beginning of the text you wish to replace. content The content to be used between the two lines identified by marker_start and marker_stop. append_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be appended to the file. prepend_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be prepended to the file. insert_before_match If markers are not found, this parameter can be set to a regex which will insert the block before the first found occurrence in the file. .. versionadded:: Neon insert_after_match If markers are not found, this parameter can be set to a regex which will insert the block after the first found occurrence in the file. .. versionadded:: Neon backup The file extension to use for a backup of the file if any edit is made. Set to ``False`` to skip making a backup. dry_run : False If ``True``, do not make any edits to the file and simply return the changes that *would* be made. show_changes : True Controls how changes are presented. If ``True``, this function will return a unified diff of the changes made. If False, then it will return a boolean (``True`` if any changes were made, otherwise ``False``). append_newline : False Controls whether or not a newline is appended to the content block. If the value of this argument is ``True`` then a newline will be added to the content block. If it is ``False``, then a newline will *not* be added to the content block. If it is ``None`` then a newline will only be added to the content block if it does not already end in a newline. .. versionadded:: 2016.3.4 .. versionchanged:: 2017.7.5,2018.3.1 New behavior added when value is ``None``. .. versionchanged:: 2019.2.0 The default value of this argument will change to ``None`` to match the behavior of the :py:func:`file.blockreplace state <salt.states.file.blockreplace>` CLI Example: .. code-block:: bash salt '*' file.blockreplace /etc/hosts '#-- start managed zone foobar : DO NOT EDIT --' \\ '#-- end managed zone foobar --' $'10.0.1.1 foo.foobar\\n10.0.1.2 bar.foobar' True ''' exclusive_params = [append_if_not_found, prepend_if_not_found, bool(insert_before_match), bool(insert_after_match)] if sum(exclusive_params) > 1: raise SaltInvocationError( 'Only one of append_if_not_found, prepend_if_not_found,' ' insert_before_match, and insert_after_match is permitted' ) path = os.path.expanduser(path) if not os.path.exists(path): raise SaltInvocationError('File not found: {0}'.format(path)) try: file_encoding = __utils__['files.get_encoding'](path) except CommandExecutionError: file_encoding = None if __utils__['files.is_binary'](path): if not file_encoding: raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if insert_before_match or insert_after_match: if insert_before_match: if not isinstance(insert_before_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_before_match parameter.' ) elif insert_after_match: if not isinstance(insert_after_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_after_match parameter.' ) if append_newline is None and not content.endswith((os.linesep, '\n')): append_newline = True # Split the content into a list of lines, removing newline characters. To # ensure that we handle both Windows and POSIX newlines, first split on # Windows newlines, and then split on POSIX newlines. split_content = [] for win_line in content.split('\r\n'): for content_line in win_line.split('\n'): split_content.append(content_line) line_count = len(split_content) has_changes = False orig_file = [] new_file = [] in_block = False block_found = False linesep = None def _add_content(linesep, lines=None, include_marker_start=True, end_line=None): if lines is None: lines = [] include_marker_start = True if end_line is None: end_line = marker_end end_line = end_line.rstrip('\r\n') + linesep if include_marker_start: lines.append(marker_start + linesep) if split_content: for index, content_line in enumerate(split_content, 1): if index != line_count: lines.append(content_line + linesep) else: # We're on the last line of the content block if append_newline: lines.append(content_line + linesep) lines.append(end_line) else: lines.append(content_line + end_line) else: lines.append(end_line) return lines # We do not use in-place editing to avoid file attrs modifications when # no changes are required and to avoid any file access on a partially # written file. try: fi_file = io.open(path, mode='r', encoding=file_encoding, newline='') for line in fi_file: write_line_to_new_file = True if linesep is None: # Auto-detect line separator if line.endswith('\r\n'): linesep = '\r\n' elif line.endswith('\n'): linesep = '\n' else: # No newline(s) in file, fall back to system's linesep linesep = os.linesep if marker_start in line: # We've entered the content block in_block = True else: if in_block: # We're not going to write the lines from the old file to # the new file until we have exited the block. write_line_to_new_file = False marker_end_pos = line.find(marker_end) if marker_end_pos != -1: # End of block detected in_block = False # We've found and exited the block block_found = True _add_content(linesep, lines=new_file, include_marker_start=False, end_line=line[marker_end_pos:]) # Save the line from the original file orig_file.append(line) if write_line_to_new_file: new_file.append(line) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read from {0}: {1}'.format(path, exc) ) finally: if linesep is None: # If the file was empty, we will not have set linesep yet. Assume # the system's line separator. This is needed for when we # prepend/append later on. linesep = os.linesep try: fi_file.close() except Exception: pass if in_block: # unterminated block => bad, always fail raise CommandExecutionError( 'Unterminated marked block. End of file reached before marker_end.' ) if not block_found: if prepend_if_not_found: # add the markers and content at the beginning of file prepended_content = _add_content(linesep) prepended_content.extend(new_file) new_file = prepended_content block_found = True elif append_if_not_found: # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(linesep): new_file[-1] += linesep # add the markers and content at the end of file _add_content(linesep, lines=new_file) block_found = True elif insert_before_match or insert_after_match: match_regex = insert_before_match or insert_after_match match_idx = [i for i, item in enumerate(orig_file) if re.search(match_regex, item)] if match_idx: match_idx = match_idx[0] for line in _add_content(linesep): if insert_after_match: match_idx += 1 new_file.insert(match_idx, line) if insert_before_match: match_idx += 1 block_found = True if not block_found: raise CommandExecutionError( 'Cannot edit marked block. Markers were not found in file.' ) diff = __utils__['stringutils.get_diff'](orig_file, new_file) has_changes = diff is not '' if has_changes and not dry_run: # changes detected # backup file attrs perms = {} perms['user'] = get_user(path) perms['group'] = get_group(path) perms['mode'] = salt.utils.files.normalize_mode(get_mode(path)) # backup old content if backup is not False: backup_path = '{0}{1}'.format(path, backup) shutil.copy2(path, backup_path) # copy2 does not preserve ownership check_perms(backup_path, None, perms['user'], perms['group'], perms['mode']) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line, encoding=file_encoding)) finally: fh_.close() # this may have overwritten file attrs check_perms(path, None, perms['user'], perms['group'], perms['mode']) if show_changes: return diff return has_changes def search(path, pattern, flags=8, bufsize=1, ignore_if_missing=False, multiline=False ): ''' .. versionadded:: 0.17.0 Search for occurrences of a pattern in a file Except for multiline, params are identical to :py:func:`~salt.modules.file.replace`. multiline If true, inserts 'MULTILINE' into ``flags`` and sets ``bufsize`` to 'file'. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' file.search /etc/crontab 'mymaintenance.sh' ''' if multiline: flags = _add_flags(flags, 'MULTILINE') bufsize = 'file' # This function wraps file.replace on purpose in order to enforce # consistent usage, compatible regex's, expected behavior, *and* bugs. :) # Any enhancements or fixes to one should affect the other. return replace(path, pattern, '', flags=flags, bufsize=bufsize, dry_run=True, search_only=True, show_changes=False, ignore_if_missing=ignore_if_missing) def patch(originalfile, patchfile, options='', dry_run=False): ''' .. versionadded:: 0.10.4 Apply a patch to a file or directory. Equivalent to: .. code-block:: bash patch <options> -i <patchfile> <originalfile> Or, when a directory is patched: .. code-block:: bash patch <options> -i <patchfile> -d <originalfile> -p0 originalfile The full path to the file or directory to be patched patchfile A patch file to apply to ``originalfile`` options Options to pass to patch. CLI Example: .. code-block:: bash salt '*' file.patch /opt/file.txt /tmp/file.txt.patch ''' patchpath = salt.utils.path.which('patch') if not patchpath: raise CommandExecutionError( 'patch executable not found. Is the distribution\'s patch ' 'package installed?' ) cmd = [patchpath] cmd.extend(salt.utils.args.shlex_split(options)) if dry_run: if __grains__['kernel'] in ('FreeBSD', 'OpenBSD'): cmd.append('-C') else: cmd.append('--dry-run') # this argument prevents interactive prompts when the patch fails to apply. # the exit code will still be greater than 0 if that is the case. if '-N' not in cmd and '--forward' not in cmd: cmd.append('--forward') has_rejectfile_option = False for option in cmd: if option == '-r' or option.startswith('-r ') \ or option.startswith('--reject-file'): has_rejectfile_option = True break # by default, patch will write rejected patch files to <filename>.rej. # this option prevents that. if not has_rejectfile_option: cmd.append('--reject-file=-') cmd.extend(['-i', patchfile]) if os.path.isdir(originalfile): cmd.extend(['-d', originalfile]) has_strip_option = False for option in cmd: if option.startswith('-p') or option.startswith('--strip='): has_strip_option = True break if not has_strip_option: cmd.append('--strip=0') else: cmd.append(originalfile) return __salt__['cmd.run_all'](cmd, python_shell=False) def contains(path, text): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the file at ``path`` contains ``text`` CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False stripped_text = six.text_type(text).strip() try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if stripped_text in chunk: return True return False except (IOError, OSError): return False def contains_regex(path, regex, lchar=''): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the given regular expression matches on any line in the text of a given file. If the lchar argument (leading char) is specified, it will strip `lchar` from the left side of each line before trying to match CLI Example: .. code-block:: bash salt '*' file.contains_regex /etc/crontab ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.files.fopen(path, 'r') as target: for line in target: line = salt.utils.stringutils.to_unicode(line) if lchar: line = line.lstrip(lchar) if re.search(regex, line): return True return False except (IOError, OSError): return False def contains_glob(path, glob_expr): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the given glob matches a string in the named file CLI Example: .. code-block:: bash salt '*' file.contains_glob /etc/foobar '*cheese*' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if fnmatch.fnmatch(chunk, glob_expr): return True return False except (IOError, OSError): return False def append(path, *args, **kwargs): ''' .. versionadded:: 0.9.5 Append text to the end of a file path path to file `*args` strings to append to file CLI Example: .. code-block:: bash salt '*' file.append /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.append /etc/motd args='cheese=spam' salt '*' file.append /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) # Largely inspired by Fabric's contrib.files.append() if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] # Make sure we have a newline at the end of the file. Do this in binary # mode so SEEK_END with nonzero offset will work. with salt.utils.files.fopen(path, 'rb+') as ofile: linesep = salt.utils.stringutils.to_bytes(os.linesep) try: ofile.seek(-len(linesep), os.SEEK_END) except IOError as exc: if exc.errno in (errno.EINVAL, errno.ESPIPE): # Empty file, simply append lines at the beginning of the file pass else: raise else: if ofile.read(len(linesep)) != linesep: ofile.seek(0, os.SEEK_END) ofile.write(linesep) # Append lines in text mode with salt.utils.files.fopen(path, 'a') as ofile: for new_line in args: ofile.write( salt.utils.stringutils.to_str( '{0}{1}'.format(new_line, os.linesep) ) ) return 'Wrote {0} lines to "{1}"'.format(len(args), path) def prepend(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Prepend text to the beginning of a file path path to file `*args` strings to prepend to the file CLI Example: .. code-block:: bash salt '*' file.prepend /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.prepend /etc/motd args='cheese=spam' salt '*' file.prepend /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] try: with salt.utils.files.fopen(path) as fhr: contents = [salt.utils.stringutils.to_unicode(line) for line in fhr.readlines()] except IOError: contents = [] preface = [] for line in args: preface.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, 'w') as ofile: contents = preface + contents ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Prepended {0} lines to "{1}"'.format(len(args), path) def write(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Write text to a file, overwriting any existing contents. path path to file `*args` strings to write to the file CLI Example: .. code-block:: bash salt '*' file.write /etc/motd \\ "With all thine offerings thou shalt offer salt." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.write /etc/motd args='cheese=spam' salt '*' file.write /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] contents = [] for line in args: contents.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, "w") as ofile: ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Wrote {0} lines to "{1}"'.format(len(contents), path) def touch(name, atime=None, mtime=None): ''' .. versionadded:: 0.9.5 Just like the ``touch`` command, create a file if it doesn't exist or simply update the atime and mtime if it already does. atime: Access time in Unix epoch time. Set it to 0 to set atime of the file with Unix date of birth. If this parameter isn't set, atime will be set with current time. mtime: Last modification in Unix epoch time. Set it to 0 to set mtime of the file with Unix date of birth. If this parameter isn't set, mtime will be set with current time. CLI Example: .. code-block:: bash salt '*' file.touch /var/log/emptyfile ''' name = os.path.expanduser(name) if atime and atime.isdigit(): atime = int(atime) if mtime and mtime.isdigit(): mtime = int(mtime) try: if not os.path.exists(name): with salt.utils.files.fopen(name, 'a'): pass if atime is None and mtime is None: times = None elif mtime is None and atime is not None: times = (atime, time.time()) elif atime is None and mtime is not None: times = (time.time(), mtime) else: times = (atime, mtime) os.utime(name, times) except TypeError: raise SaltInvocationError('atime and mtime must be integers') except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return os.path.exists(name) def tail(path, lines): ''' .. versionadded:: Neon Read the last n lines from a file path path to file lines number of lines to read CLI Example: .. code-block:: bash salt '*' file.tail /path/to/file 10 ''' path = os.path.expanduser(path) lines_found = [] buffer_size = 4098 if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot tail a binary file: {0}'.format(path)) try: lines = int(lines) except ValueError: raise SaltInvocationError('file.tail: \'lines\' value must be an integer') try: with salt.utils.fopen(path) as tail_fh: blk_cnt = 1 size = os.stat(path).st_size if size > buffer_size: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size), os.linesep) for i in range(lines): while len(data) == 1 and ((blk_cnt * buffer_size) < size): blk_cnt += 1 line = data[0] try: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size) + line, os.linesep) except IOError: tail_fh.seek(0) data = string.split(tail_fh.read(size - (buffer_size * (blk_cnt - 1))) + line, os.linesep) line = data[-1] data.pop() lines_found.append(line) return lines_found[-lines:] except (OSError, IOError): raise CommandExecutionError('Could not tail \'{0}\''.format(path)) def seek_read(path, size, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and read it path path to file seek amount to read at once offset offset to start into the file CLI Example: .. code-block:: bash salt '*' file.seek_read /path/to/file 4096 0 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_RDONLY) try: os.lseek(seek_fh, int(offset), 0) data = os.read(seek_fh, int(size)) finally: os.close(seek_fh) return data def seek_write(path, data, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and write to it path path to file data data to write to file offset position in file to start writing CLI Example: .. code-block:: bash salt '*' file.seek_write /path/to/file 'some data' 4096 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_WRONLY) try: os.lseek(seek_fh, int(offset), 0) ret = os.write(seek_fh, data) os.fsync(seek_fh) finally: os.close(seek_fh) return ret def truncate(path, length): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and delete everything after that point path path to file length offset into file to truncate CLI Example: .. code-block:: bash salt '*' file.truncate /path/to/file 512 ''' path = os.path.expanduser(path) with salt.utils.files.fopen(path, 'rb+') as seek_fh: seek_fh.truncate(int(length)) def link(src, path): ''' .. versionadded:: 2014.1.0 Create a hard link to a file CLI Example: .. code-block:: bash salt '*' file.link /path/to/file /path/to/link ''' src = os.path.expanduser(src) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.link(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def is_link(path): ''' Check if the path is a symbolic link CLI Example: .. code-block:: bash salt '*' file.is_link /path/to/link ''' # This function exists because os.path.islink does not support Windows, # therefore a custom function will need to be called. This function # therefore helps API consistency by providing a single function to call for # both operating systems. return os.path.islink(os.path.expanduser(path)) def symlink(src, path): ''' Create a symbolic link (symlink, soft link) to a file CLI Example: .. code-block:: bash salt '*' file.symlink /path/to/file /path/to/link ''' path = os.path.expanduser(path) try: if os.path.normpath(os.readlink(path)) == os.path.normpath(src): log.debug('link already in correct state: %s -> %s', path, src) return True except OSError: pass if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: os.symlink(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def rename(src, dst): ''' Rename a file or directory CLI Example: .. code-block:: bash salt '*' file.rename /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.rename(src, dst) return True except OSError: raise CommandExecutionError( 'Could not rename \'{0}\' to \'{1}\''.format(src, dst) ) return False def copy(src, dst, recurse=False, remove_existing=False): ''' Copy a file or directory from source to dst In order to copy a directory, the recurse flag is required, and will by default overwrite files in the destination with the same path, and retain all other existing files. (similar to cp -r on unix) remove_existing will remove all files in the target directory, and then copy files from the source. .. note:: The copy function accepts paths that are local to the Salt minion. This function does not support salt://, http://, or the other additional file paths that are supported by :mod:`states.file.managed <salt.states.file.managed>` and :mod:`states.file.recurse <salt.states.file.recurse>`. CLI Example: .. code-block:: bash salt '*' file.copy /path/to/src /path/to/dst salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True remove_existing=True ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') if not os.path.exists(src): raise CommandExecutionError('No such file or directory \'{0}\''.format(src)) if not salt.utils.platform.is_windows(): pre_user = get_user(src) pre_group = get_group(src) pre_mode = salt.utils.files.normalize_mode(get_mode(src)) try: if (os.path.exists(dst) and os.path.isdir(dst)) or os.path.isdir(src): if not recurse: raise SaltInvocationError( "Cannot copy overwriting a directory without recurse flag set to true!") if remove_existing: if os.path.exists(dst): shutil.rmtree(dst) shutil.copytree(src, dst) else: salt.utils.files.recursive_copy(src, dst) else: shutil.copyfile(src, dst) except OSError: raise CommandExecutionError( 'Could not copy \'{0}\' to \'{1}\''.format(src, dst) ) if not salt.utils.platform.is_windows(): check_perms(dst, None, pre_user, pre_group, pre_mode) return True def lstat(path): ''' .. versionadded:: 2014.1.0 Returns the lstat attributes for the given file or dir. Does not support symbolic links. CLI Example: .. code-block:: bash salt '*' file.lstat /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to file must be absolute.') try: lst = os.lstat(path) return dict((key, getattr(lst, key)) for key in ('st_atime', 'st_ctime', 'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid')) except Exception: return {} def access(path, mode): ''' .. versionadded:: 2014.1.0 Test whether the Salt process has the specified access to the file. One of the following modes must be specified: .. code-block::text f: Test the existence of the path r: Test the readability of the path w: Test the writability of the path x: Test whether the path can be executed CLI Example: .. code-block:: bash salt '*' file.access /path/to/file f salt '*' file.access /path/to/file x ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') modes = {'f': os.F_OK, 'r': os.R_OK, 'w': os.W_OK, 'x': os.X_OK} if mode in modes: return os.access(path, modes[mode]) elif mode in six.itervalues(modes): return os.access(path, mode) else: raise SaltInvocationError('Invalid mode specified.') def read(path, binary=False): ''' .. versionadded:: 2017.7.0 Return the content of the file. CLI Example: .. code-block:: bash salt '*' file.read /path/to/file ''' access_mode = 'r' if binary is True: access_mode += 'b' with salt.utils.files.fopen(path, access_mode) as file_obj: return salt.utils.stringutils.to_unicode(file_obj.read()) def readlink(path, canonicalize=False): ''' .. versionadded:: 2014.1.0 Return the path that a symlink points to If canonicalize is set to True, then it return the final target CLI Example: .. code-block:: bash salt '*' file.readlink /path/to/link ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') if not os.path.islink(path): raise SaltInvocationError('A valid link was not specified.') if canonicalize: return os.path.realpath(path) else: return os.readlink(path) def readdir(path): ''' .. versionadded:: 2014.1.0 Return a list containing the contents of a directory CLI Example: .. code-block:: bash salt '*' file.readdir /path/to/dir/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Dir path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') dirents = ['.', '..'] dirents.extend(os.listdir(path)) return dirents def statvfs(path): ''' .. versionadded:: 2014.1.0 Perform a statvfs call against the filesystem that the file resides on CLI Example: .. code-block:: bash salt '*' file.statvfs /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: stv = os.statvfs(path) return dict((key, getattr(stv, key)) for key in ('f_bavail', 'f_bfree', 'f_blocks', 'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag', 'f_frsize', 'f_namemax')) except (OSError, IOError): raise CommandExecutionError('Could not statvfs \'{0}\''.format(path)) return False def stats(path, hash_type=None, follow_symlinks=True): ''' Return a dict containing the stats for a given file CLI Example: .. code-block:: bash salt '*' file.stats /etc/passwd ''' path = os.path.expanduser(path) ret = {} if not os.path.exists(path): try: # Broken symlinks will return False for os.path.exists(), but still # have a uid and gid pstat = os.lstat(path) except OSError: # Not a broken symlink, just a nonexistent path # NOTE: The file.directory state checks the content of the error # message in this exception. Any changes made to the message for this # exception will reflect the file.directory state as well, and will # likely require changes there. raise CommandExecutionError('Path not found: {0}'.format(path)) else: if follow_symlinks: pstat = os.stat(path) else: pstat = os.lstat(path) ret['inode'] = pstat.st_ino ret['uid'] = pstat.st_uid ret['gid'] = pstat.st_gid ret['group'] = gid_to_group(pstat.st_gid) ret['user'] = uid_to_user(pstat.st_uid) ret['atime'] = pstat.st_atime ret['mtime'] = pstat.st_mtime ret['ctime'] = pstat.st_ctime ret['size'] = pstat.st_size ret['mode'] = six.text_type(oct(stat.S_IMODE(pstat.st_mode))) if hash_type: ret['sum'] = get_hash(path, hash_type) ret['type'] = 'file' if stat.S_ISDIR(pstat.st_mode): ret['type'] = 'dir' if stat.S_ISCHR(pstat.st_mode): ret['type'] = 'char' if stat.S_ISBLK(pstat.st_mode): ret['type'] = 'block' if stat.S_ISREG(pstat.st_mode): ret['type'] = 'file' if stat.S_ISLNK(pstat.st_mode): ret['type'] = 'link' if stat.S_ISFIFO(pstat.st_mode): ret['type'] = 'pipe' if stat.S_ISSOCK(pstat.st_mode): ret['type'] = 'socket' ret['target'] = os.path.realpath(path) return ret def rmdir(path): ''' .. versionadded:: 2014.1.0 Remove the specified directory. Fails if a directory is not empty. CLI Example: .. code-block:: bash salt '*' file.rmdir /tmp/foo/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') try: os.rmdir(path) return True except OSError as exc: return exc.strerror def remove(path, **kwargs): ''' Remove the named file. If a directory is supplied, it will be recursively deleted. CLI Example: .. code-block:: bash salt '*' file.remove /tmp/foo ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute: {0}'.format(path)) try: if os.path.isfile(path) or os.path.islink(path): os.remove(path) return True elif os.path.isdir(path): shutil.rmtree(path) return True except (OSError, IOError) as exc: raise CommandExecutionError( 'Could not remove \'{0}\': {1}'.format(path, exc) ) return False def directory_exists(path): ''' Tests to see if path is a valid directory. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.directory_exists /etc ''' return os.path.isdir(os.path.expanduser(path)) def file_exists(path): ''' Tests to see if path is a valid file. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.file_exists /etc/passwd ''' return os.path.isfile(os.path.expanduser(path)) def path_exists_glob(path): ''' Tests to see if path after expansion is a valid path (file or directory). Expansion allows usage of ? * and character ranges []. Tilde expansion is not supported. Returns True/False. .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' file.path_exists_glob /etc/pam*/pass* ''' return True if glob.glob(os.path.expanduser(path)) else False def restorecon(path, recursive=False): ''' Reset the SELinux context on a given path CLI Example: .. code-block:: bash salt '*' file.restorecon /home/user/.ssh/authorized_keys ''' if recursive: cmd = ['restorecon', '-FR', path] else: cmd = ['restorecon', '-F', path] return not __salt__['cmd.retcode'](cmd, python_shell=False) def get_selinux_context(path): ''' Get an SELinux context from a given path CLI Example: .. code-block:: bash salt '*' file.get_selinux_context /etc/hosts ''' out = __salt__['cmd.run'](['ls', '-Z', path], python_shell=False) try: ret = re.search(r'\w+:\w+:\w+:\w+', out).group(0) except AttributeError: ret = ( 'No selinux context information is available for {0}'.format(path) ) return ret def set_selinux_context(path, user=None, role=None, type=None, # pylint: disable=W0622 range=None, # pylint: disable=W0622 persist=False): ''' .. versionchanged:: Neon Added persist option Set a specific SELinux label on a given path CLI Example: .. code-block:: bash salt '*' file.set_selinux_context path <user> <role> <type> <range> salt '*' file.set_selinux_context /etc/yum.repos.d/epel.repo system_u object_r system_conf_t s0 ''' if not any((user, role, type, range)): return False if persist: fcontext_result = __salt__['selinux.fcontext_add_policy'](path, sel_type=type, sel_user=user, sel_level=range) if fcontext_result.get('retcode', None) is not 0: # Problem setting fcontext policy raise CommandExecutionError( 'Problem setting fcontext: {0}'.format(fcontext_result) ) cmd = ['chcon'] if user: cmd.extend(['-u', user]) if role: cmd.extend(['-r', role]) if type: cmd.extend(['-t', type]) if range: cmd.extend(['-l', range]) cmd.append(path) ret = not __salt__['cmd.retcode'](cmd, python_shell=False) if ret: return get_selinux_context(path) else: return ret def source_list(source, source_hash, saltenv): ''' Check the source list and return the source to use CLI Example: .. code-block:: bash salt '*' file.source_list salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' base ''' contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv) if contextkey in __context__: return __context__[contextkey] # get the master file list if isinstance(source, list): mfiles = [(f, saltenv) for f in __salt__['cp.list_master'](saltenv)] mdirs = [(d, saltenv) for d in __salt__['cp.list_master_dirs'](saltenv)] for single in source: if isinstance(single, dict): single = next(iter(single)) path, senv = salt.utils.url.parse(single) if senv: mfiles += [(f, senv) for f in __salt__['cp.list_master'](senv)] mdirs += [(d, senv) for d in __salt__['cp.list_master_dirs'](senv)] ret = None for single in source: if isinstance(single, dict): # check the proto, if it is http or ftp then download the file # to check, if it is salt then check the master list # if it is a local file, check if the file exists if len(single) != 1: continue single_src = next(iter(single)) single_hash = single[single_src] if single[single_src] else source_hash urlparsed_single_src = _urlparse(single_src) # Fix this for Windows if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_single_src.scheme.lower() in string.ascii_lowercase: urlparsed_single_src = _urlparse('file://' + single_src) proto = urlparsed_single_src.scheme if proto == 'salt': path, senv = salt.utils.url.parse(single_src) if not senv: senv = saltenv if (path, saltenv) in mfiles or (path, saltenv) in mdirs: ret = (single_src, single_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single_src, single_hash) break elif proto == 'file' and ( os.path.exists(urlparsed_single_src.netloc) or os.path.exists(urlparsed_single_src.path) or os.path.exists(os.path.join( urlparsed_single_src.netloc, urlparsed_single_src.path))): ret = (single_src, single_hash) break elif single_src.startswith(os.sep) and os.path.exists(single_src): ret = (single_src, single_hash) break elif isinstance(single, six.string_types): path, senv = salt.utils.url.parse(single) if not senv: senv = saltenv if (path, senv) in mfiles or (path, senv) in mdirs: ret = (single, source_hash) break urlparsed_src = _urlparse(single) if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_src.scheme.lower() in string.ascii_lowercase: urlparsed_src = _urlparse('file://' + single) proto = urlparsed_src.scheme if proto == 'file' and ( os.path.exists(urlparsed_src.netloc) or os.path.exists(urlparsed_src.path) or os.path.exists(os.path.join( urlparsed_src.netloc, urlparsed_src.path))): ret = (single, source_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single, source_hash) break elif single.startswith(os.sep) and os.path.exists(single): ret = (single, source_hash) break if ret is None: # None of the list items matched raise CommandExecutionError( 'none of the specified sources were found' ) else: ret = (source, source_hash) __context__[contextkey] = ret return ret def apply_template_on_contents( contents, template, context, defaults, saltenv): ''' Return the contents after applying the templating engine contents template string template template format context Overrides default context variables passed to the template. defaults Default context passed to the template. CLI Example: .. code-block:: bash salt '*' file.apply_template_on_contents \\ contents='This is a {{ template }} string.' \\ template=jinja \\ "context={}" "defaults={'template': 'cool'}" \\ saltenv=base ''' if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) # Apply templating contents = salt.utils.templates.TEMPLATE_REGISTRY[template]( contents, from_str=True, to_str=True, context=context_dict, saltenv=saltenv, grains=__opts__['grains'], pillar=__pillar__, salt=__salt__, opts=__opts__)['data'] if six.PY2: contents = contents.encode('utf-8') elif six.PY3 and isinstance(contents, bytes): # bytes -> str contents = contents.decode('utf-8') else: ret = {} ret['result'] = False ret['comment'] = ('Specified template format {0} is not supported' ).format(template) return ret return contents def get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify=False, **kwargs): ''' Return the managed file data for file.managed name location where the file lives on the server template template format source managed source file source_hash hash of the source file source_hash_name When ``source_hash`` refers to a remote file, this specifies the filename to look for in that file. .. versionadded:: 2016.3.5 user Owner of file group Group owner of file mode Permissions of file attrs Attributes of file .. versionadded:: 2018.3.0 context Variables to add to the template context defaults Default values of for context_dict skip_verify If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' file.get_managed /etc/httpd/conf.d/httpd.conf jinja salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' None root root '755' base None None ''' # Copy the file to the minion and templatize it sfn = '' source_sum = {} def _get_local_file_source_sum(path): ''' DRY helper for getting the source_sum value from a locally cached path. ''' return {'hsum': get_hash(path, form='sha256'), 'hash_type': 'sha256'} # If we have a source defined, let's figure out what the hash is if source: urlparsed_source = _urlparse(source) if urlparsed_source.scheme in salt.utils.files.VALID_PROTOS: parsed_scheme = urlparsed_source.scheme else: parsed_scheme = '' parsed_path = os.path.join( urlparsed_source.netloc, urlparsed_source.path).rstrip(os.sep) unix_local_source = parsed_scheme in ('file', '') if parsed_scheme == '': parsed_path = sfn = source if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg elif parsed_scheme == 'file': sfn = parsed_path if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg if parsed_scheme and parsed_scheme.lower() in string.ascii_lowercase: parsed_path = ':'.join([parsed_scheme, parsed_path]) parsed_scheme = 'file' if parsed_scheme == 'salt': source_sum = __salt__['cp.hash_file'](source, saltenv) if not source_sum: return '', {}, 'Source file {0} not found in saltenv \'{1}\''.format(source, saltenv) elif not source_hash and unix_local_source: source_sum = _get_local_file_source_sum(parsed_path) elif not source_hash and source.startswith(os.sep): # This should happen on Windows source_sum = _get_local_file_source_sum(source) else: if not skip_verify: if source_hash: try: source_sum = get_source_sum(name, source, source_hash, source_hash_name, saltenv) except CommandExecutionError as exc: return '', {}, exc.strerror else: msg = ( 'Unable to verify upstream hash of source file {0}, ' 'please set source_hash or set skip_verify to True' .format(salt.utils.url.redact_http_basic_auth(source)) ) return '', {}, msg if source and (template or parsed_scheme in salt.utils.files.REMOTE_PROTOS): # Check if we have the template or remote file cached cache_refetch = False cached_dest = __salt__['cp.is_cached'](source, saltenv) if cached_dest and (source_hash or skip_verify): htype = source_sum.get('hash_type', 'sha256') cached_sum = get_hash(cached_dest, form=htype) if skip_verify: # prev: if skip_verify or cached_sum == source_sum['hsum']: # but `cached_sum == source_sum['hsum']` is elliptical as prev if sfn = cached_dest source_sum = {'hsum': cached_sum, 'hash_type': htype} elif cached_sum != source_sum.get('hsum', __opts__['hash_type']): cache_refetch = True else: sfn = cached_dest # If we didn't have the template or remote file, or the file has been # updated and the cache has to be refreshed, download the file. if not sfn or cache_refetch: try: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum.get('hsum')) except Exception as exc: # A 404 or other error code may raise an exception, catch it # and return a comment that will fail the calling state. _source = salt.utils.url.redact_http_basic_auth(source) return '', {}, 'Failed to cache {0}: {1}'.format(_source, exc) # If cache failed, sfn will be False, so do a truth check on sfn first # as invoking os.path.exists() on a bool raises a TypeError. if not sfn or not os.path.exists(sfn): _source = salt.utils.url.redact_http_basic_auth(source) return sfn, {}, 'Source file \'{0}\' not found'.format(_source) if sfn == name: raise SaltInvocationError( 'Source file cannot be the same as destination' ) if template: if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, name=name, source=source, user=user, group=group, mode=mode, attrs=attrs, saltenv=saltenv, context=context_dict, salt=__salt__, pillar=__pillar__, grains=__opts__['grains'], opts=__opts__, **kwargs) else: return sfn, {}, ('Specified template format {0} is not supported' ).format(template) if data['result']: sfn = data['data'] hsum = get_hash(sfn, form='sha256') source_sum = {'hash_type': 'sha256', 'hsum': hsum} else: __clean_tmp(sfn) return sfn, {}, data['data'] return sfn, source_sum, '' def extract_hash(hash_fn, hash_type='sha256', file_name='', source='', source_hash_name=None): ''' .. versionchanged:: 2016.3.5 Prior to this version, only the ``file_name`` argument was considered for filename matches in the hash file. This would be problematic for cases in which the user was relying on a remote checksum file that they do not control, and they wished to use a different name for that file on the minion from the filename on the remote server (and in the checksum file). For example, managing ``/tmp/myfile.tar.gz`` when the remote file was at ``https://mydomain.tld/different_name.tar.gz``. The :py:func:`file.managed <salt.states.file.managed>` state now also passes this function the source URI as well as the ``source_hash_name`` (if specified). In cases where ``source_hash_name`` is specified, it takes precedence over both the ``file_name`` and ``source``. When it is not specified, ``file_name`` takes precedence over ``source``. This allows for better capability for matching hashes. .. versionchanged:: 2016.11.0 File name and source URI matches are no longer disregarded when ``source_hash_name`` is specified. They will be used as fallback matches if there is no match to the ``source_hash_name`` value. This routine is called from the :mod:`file.managed <salt.states.file.managed>` state to pull a hash from a remote file. Regular expressions are used line by line on the ``source_hash`` file, to find a potential candidate of the indicated hash type. This avoids many problems of arbitrary file layout rules. It specifically permits pulling hash codes from debian ``*.dsc`` files. If no exact match of a hash and filename are found, then the first hash found (if any) will be returned. If no hashes at all are found, then ``None`` will be returned. For example: .. code-block:: yaml openerp_7.0-latest-1.tar.gz: file.managed: - name: /tmp/openerp_7.0-20121227-075624-1_all.deb - source: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.tar.gz - source_hash: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.dsc CLI Example: .. code-block:: bash salt '*' file.extract_hash /path/to/hash/file sha512 /etc/foo ''' hash_len = HASHES.get(hash_type) if hash_len is None: if hash_type: log.warning( 'file.extract_hash: Unsupported hash_type \'%s\', falling ' 'back to matching any supported hash_type', hash_type ) hash_type = '' hash_len_expr = '{0},{1}'.format(min(HASHES_REVMAP), max(HASHES_REVMAP)) else: hash_len_expr = six.text_type(hash_len) filename_separators = string.whitespace + r'\/' if source_hash_name: if not isinstance(source_hash_name, six.string_types): source_hash_name = six.text_type(source_hash_name) source_hash_name_idx = (len(source_hash_name) + 1) * -1 log.debug( 'file.extract_hash: Extracting %s hash for file matching ' 'source_hash_name \'%s\'', 'any supported' if not hash_type else hash_type, source_hash_name ) if file_name: if not isinstance(file_name, six.string_types): file_name = six.text_type(file_name) file_name_basename = os.path.basename(file_name) file_name_idx = (len(file_name_basename) + 1) * -1 if source: if not isinstance(source, six.string_types): source = six.text_type(source) urlparsed_source = _urlparse(source) source_basename = os.path.basename( urlparsed_source.path or urlparsed_source.netloc ) source_idx = (len(source_basename) + 1) * -1 basename_searches = [x for x in (file_name, source) if x] if basename_searches: log.debug( 'file.extract_hash: %s %s hash for file matching%s: %s', 'If no source_hash_name match found, will extract' if source_hash_name else 'Extracting', 'any supported' if not hash_type else hash_type, '' if len(basename_searches) == 1 else ' either of the following', ', '.join(basename_searches) ) partial = None found = {} with salt.utils.files.fopen(hash_fn, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line.strip()) hash_re = r'(?i)(?<![a-z0-9])([a-f0-9]{' + hash_len_expr + '})(?![a-z0-9])' hash_match = re.search(hash_re, line) matched = None if hash_match: matched_hsum = hash_match.group(1) if matched_hsum is not None: matched_type = HASHES_REVMAP.get(len(matched_hsum)) if matched_type is None: # There was a match, but it's not of the correct length # to match one of the supported hash types. matched = None else: matched = {'hsum': matched_hsum, 'hash_type': matched_type} if matched is None: log.debug( 'file.extract_hash: In line \'%s\', no %shash found', line, '' if not hash_type else hash_type + ' ' ) continue if partial is None: partial = matched def _add_to_matches(found, line, match_type, value, matched): log.debug( 'file.extract_hash: Line \'%s\' matches %s \'%s\'', line, match_type, value ) found.setdefault(match_type, []).append(matched) hash_matched = False if source_hash_name: if line.endswith(source_hash_name): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[source_hash_name_idx] in string.whitespace: _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source_hash_name) + r'\s+', line): _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True if file_name: if line.endswith(file_name_basename): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[file_name_idx] in filename_separators: _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(file_name) + r'\s+', line): _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True if source: if line.endswith(source_basename): # Same as above, we can't just do an rsplit here. try: if line[source_idx] in filename_separators: _add_to_matches(found, line, 'source', source, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source) + r'\s+', line): _add_to_matches(found, line, 'source', source, matched) hash_matched = True if not hash_matched: log.debug( 'file.extract_hash: Line \'%s\' contains %s hash ' '\'%s\', but line did not meet the search criteria', line, matched['hash_type'], matched['hsum'] ) for found_type, found_str in (('source_hash_name', source_hash_name), ('file_name', file_name), ('source', source)): if found_type in found: if len(found[found_type]) > 1: log.debug( 'file.extract_hash: Multiple %s matches for %s: %s', found_type, found_str, ', '.join( ['{0} ({1})'.format(x['hsum'], x['hash_type']) for x in found[found_type]] ) ) ret = found[found_type][0] log.debug( 'file.extract_hash: Returning %s hash \'%s\' as a match of %s', ret['hash_type'], ret['hsum'], found_str ) return ret if partial: log.debug( 'file.extract_hash: Returning the partially identified %s hash ' '\'%s\'', partial['hash_type'], partial['hsum'] ) return partial log.debug('file.extract_hash: No matches, returning None') return None def check_perms(name, ret, user, group, mode, attrs=None, follow_symlinks=False, seuser=None, serole=None, setype=None, serange=None): ''' .. versionchanged:: Neon Added selinux options Check the permissions on files, modify attributes and chown if needed. File attributes are only verified if lsattr(1) is installed. CLI Example: .. code-block:: bash salt '*' file.check_perms /etc/sudoers '{}' root root 400 ai .. versionchanged:: 2014.1.3 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': [], 'result': True} orig_comment = '' else: orig_comment = ret['comment'] ret['comment'] = [] # Check permissions perms = {} cur = stats(name, follow_symlinks=follow_symlinks) perms['luser'] = cur['user'] perms['lgroup'] = cur['group'] perms['lmode'] = salt.utils.files.normalize_mode(cur['mode']) is_dir = os.path.isdir(name) is_link = os.path.islink(name) if attrs is not None \ and not salt.utils.platform.is_windows() \ and not is_dir and not is_link: try: lattrs = lsattr(name) except SaltInvocationError: lattrs = None if lattrs is not None: # List attributes on file perms['lattrs'] = ''.join(lattrs.get(name, '')) # Remove attributes on file so changes can be enforced. if perms['lattrs']: chattr(name, operator='remove', attributes=perms['lattrs']) # user/group changes if needed, then check if it worked if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid(perms['luser']) ) or ( not salt.utils.platform.is_windows() and user != perms['luser'] ): perms['cuser'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid(perms['lgroup']) ) or ( not salt.utils.platform.is_windows() and group != perms['lgroup'] ): perms['cgroup'] = group if 'cuser' in perms or 'cgroup' in perms: if not __opts__['test']: if os.path.islink(name) and not follow_symlinks: chown_func = lchown else: chown_func = chown if user is None: user = perms['luser'] if group is None: group = perms['lgroup'] try: chown_func(name, user, group) # Python os.chown() does reset the suid and sgid, # that's why setting the right mode again is needed here. set_mode(name, mode) except OSError: ret['result'] = False if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid( get_user(name, follow_symlinks=follow_symlinks)) and user != '' ) or ( not salt.utils.platform.is_windows() and user != get_user(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['user'] = user else: ret['result'] = False ret['comment'].append('Failed to change user to {0}' .format(user)) elif 'cuser' in perms and user != '': ret['changes']['user'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid( get_group(name, follow_symlinks=follow_symlinks)) and user != '') or ( not salt.utils.platform.is_windows() and group != get_group(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['group'] = group else: ret['result'] = False ret['comment'].append('Failed to change group to {0}' .format(group)) elif 'cgroup' in perms and user != '': ret['changes']['group'] = group if not salt.utils.platform.is_windows() and not is_dir: # Replace attributes on file if it had been removed if perms.get('lattrs', ''): chattr(name, operator='add', attributes=perms['lattrs']) # Mode changes if needed if mode is not None: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: mode = salt.utils.files.normalize_mode(mode) if mode != perms['lmode']: if __opts__['test'] is True: ret['changes']['mode'] = mode else: set_mode(name, mode) if mode != salt.utils.files.normalize_mode(get_mode(name)): ret['result'] = False ret['comment'].append( 'Failed to change mode to {0}'.format(mode) ) else: ret['changes']['mode'] = mode # Modify attributes of file if needed if attrs is not None and not is_dir: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if diff_attrs[0] is not None or diff_attrs[1] is not None: if __opts__['test'] is True: ret['changes']['attrs'] = attrs else: if diff_attrs[0] is not None: chattr(name, operator="add", attributes=diff_attrs[0]) if diff_attrs[1] is not None: chattr(name, operator="remove", attributes=diff_attrs[1]) cmp_attrs = _cmp_attrs(name, attrs) if cmp_attrs[0] is not None or cmp_attrs[1] is not None: ret['result'] = False ret['comment'].append( 'Failed to change attributes to {0}'.format(attrs) ) else: ret['changes']['attrs'] = attrs # Set selinux attributes if needed if salt.utils.platform.is_linux() and (seuser or serole or setype or serange): selinux_error = False try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError: log.error('Unable to get current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to get selinux attributes' ) selinux_error = True if not selinux_error: requested_seuser = None requested_serole = None requested_setype = None requested_serange = None # Only set new selinux variables if updates are needed if seuser and seuser != current_seuser: requested_seuser = seuser if serole and serole != current_serole: requested_serole = serole if setype and setype != current_setype: requested_setype = setype if serange and serange != current_serange: requested_serange = serange if requested_seuser or requested_serole or requested_setype or requested_serange: # selinux updates needed, prep changes output selinux_change_new = '' selinux_change_orig = '' if requested_seuser: selinux_change_new += "User: {0} ".format(requested_seuser) selinux_change_orig += "User: {0} ".format(current_seuser) if requested_serole: selinux_change_new += "Role: {0} ".format(requested_serole) selinux_change_orig += "Role: {0} ".format(current_serole) if requested_setype: selinux_change_new += "Type: {0} ".format(requested_setype) selinux_change_orig += "Type: {0} ".format(current_setype) if requested_serange: selinux_change_new += "Range: {0} ".format(requested_serange) selinux_change_orig += "Range: {0} ".format(current_serange) if __opts__['test']: ret['comment'] = 'File {0} selinux context to be updated'.format(name) ret['result'] = None ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} else: try: # set_selinux_context requires type to be set on any other change if (requested_seuser or requested_serole or requested_serange) and not requested_setype: requested_setype = current_setype result = set_selinux_context(name, user=requested_seuser, role=requested_serole, type=requested_setype, range=requested_serange, persist=True) log.debug('selinux set result: %s', result) current_seuser, current_serole, current_setype, current_serange = result.split(':') except ValueError: log.error('Unable to set current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to set selinux attributes' ) selinux_error = True if not selinux_error: ret['comment'].append('The file {0} is set to be changed'.format(name)) if requested_seuser: if current_seuser != requested_seuser: ret['comment'].append("Unable to update seuser context") ret['result'] = False if requested_serole: if current_serole != requested_serole: ret['comment'].append("Unable to update serole context") ret['result'] = False if requested_setype: if current_setype != requested_setype: ret['comment'].append("Unable to update setype context") ret['result'] = False if requested_serange: if current_serange != requested_serange: ret['comment'].append("Unable to update serange context") ret['result'] = False ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} # Only combine the comment list into a string # after all comments are added above if isinstance(orig_comment, six.string_types): if orig_comment: ret['comment'].insert(0, orig_comment) ret['comment'] = '; '.join(ret['comment']) # Set result to None at the very end of the function, # after all changes have been recorded above if __opts__['test'] is True and ret['changes']: ret['result'] = None return ret, perms def check_managed( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Check to see what changes need to be made for a file CLI Example: .. code-block:: bash salt '*' file.check_managed /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) if comments: __clean_tmp(sfn) return False, comments changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) # Ignore permission for files written temporary directories # Files in any path will still be set correctly using get_managed() if name.startswith(tempfile.gettempdir()): for key in ['user', 'group', 'mode']: changes.pop(key, None) __clean_tmp(sfn) if changes: log.info(changes) comments = ['The following values are set to be changed:\n'] comments.extend('{0}: {1}\n'.format(key, val) for key, val in six.iteritems(changes)) return None, ''.join(comments) return True, 'The file {0} is in the correct state'.format(name) def check_managed_changes( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, keep_mode=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Return a dictionary of what changes need to be made for a file .. versionchanged:: Neon selinux attributes added CLI Example: .. code-block:: bash salt '*' file.check_managed_changes /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if comments: __clean_tmp(sfn) raise CommandExecutionError(comments) if sfn and source and keep_mode: if _urlparse(source).scheme in ('salt', 'file') \ or source.startswith('/'): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) __clean_tmp(sfn) return changes def check_file_meta( name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents=None, seuser=None, serole=None, setype=None, serange=None): ''' Check for the changes in the file metadata. CLI Example: .. code-block:: bash salt '*' file.check_file_meta /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' base .. note:: Supported hash types include sha512, sha384, sha256, sha224, sha1, and md5. name Path to file destination sfn Template-processed source file contents source URL to file source source_sum File checksum information as a dictionary .. code-block:: yaml {hash_type: md5, hsum: <md5sum>} user Destination file user owner group Destination file group owner mode Destination file permissions mode attrs Destination file attributes .. versionadded:: 2018.3.0 saltenv Salt environment used to resolve source files contents File contents seuser selinux user attribute .. versionadded:: Neon serole selinux role attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon ''' changes = {} if not source_sum: source_sum = dict() try: lstats = stats(name, hash_type=source_sum.get('hash_type', None), follow_symlinks=False) except CommandExecutionError: lstats = {} if not lstats: changes['newfile'] = name return changes if 'hsum' in source_sum: if source_sum['hsum'] != lstats['sum']: if not sfn and source: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum['hsum']) if sfn: try: changes['diff'] = get_diff( name, sfn, template=True, show_filenames=False) except CommandExecutionError as exc: changes['diff'] = exc.strerror else: changes['sum'] = 'Checksum differs' if contents is not None: # Write a tempfile with the static contents tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'w') as tmp_: tmp_.write(salt.utils.stringutils.to_str(contents)) # Compare the static contents with the named file try: differences = get_diff(name, tmp, show_filenames=False) except CommandExecutionError as exc: log.error('Failed to diff files: %s', exc) differences = exc.strerror __clean_tmp(tmp) if differences: if __salt__['config.option']('obfuscate_templates'): changes['diff'] = '<Obfuscated Template>' else: changes['diff'] = differences if not salt.utils.platform.is_windows(): # Check owner if (user is not None and user != lstats['user'] and user != lstats['uid']): changes['user'] = user # Check group if (group is not None and group != lstats['group'] and group != lstats['gid']): changes['group'] = group # Normalize the file mode smode = salt.utils.files.normalize_mode(lstats['mode']) mode = salt.utils.files.normalize_mode(mode) if mode is not None and mode != smode: changes['mode'] = mode if attrs: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if attrs is not None \ and (diff_attrs[0] is not None or diff_attrs[1] is not None): changes['attrs'] = attrs # Check selinux if seuser or serole or setype or serange: try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError as exc: log.error('Unable to get current selinux attributes') changes['selinux'] = exc.strerror if seuser and seuser != current_seuser: changes['selinux'] = {"user": seuser} if serole and serole != current_serole: changes['selinux'] = {"role": serole} if setype and setype != current_setype: changes['selinux'] = {"type": setype} if serange and serange != current_serange: changes['selinux'] = {"range": serange} return changes def get_diff(file1, file2, saltenv='base', show_filenames=True, show_changes=True, template=False, source_hash_file1=None, source_hash_file2=None): ''' Return unified diff of two files file1 The first file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, thuis had to be a file local to the minion. file2 The second file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, this had to be a file on the salt fileserver (i.e. ``salt://somefile.txt``) show_filenames : True Set to ``False`` to hide the filenames in the top two lines of the diff. show_changes : True If set to ``False``, and there are differences, then instead of a diff a simple message stating that show_changes is set to ``False`` will be returned. template : False Set to ``True`` if two templates are being compared. This is not useful except for within states, with the ``obfuscate_templates`` option set to ``True``. .. versionadded:: 2018.3.0 source_hash_file1 If ``file1`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 source_hash_file2 If ``file2`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 CLI Examples: .. code-block:: bash salt '*' file.get_diff /home/fred/.vimrc salt://users/fred/.vimrc salt '*' file.get_diff /tmp/foo.txt /tmp/bar.txt ''' files = (file1, file2) source_hashes = (source_hash_file1, source_hash_file2) paths = [] errors = [] for filename, source_hash in zip(files, source_hashes): try: # Local file paths will just return the same path back when passed # to cp.cache_file. cached_path = __salt__['cp.cache_file'](filename, saltenv, source_hash=source_hash) if cached_path is False: errors.append( 'File {0} not found'.format( salt.utils.stringutils.to_unicode(filename) ) ) continue paths.append(cached_path) except MinionError as exc: errors.append(salt.utils.stringutils.to_unicode(exc.__str__())) continue if errors: raise CommandExecutionError( 'Failed to cache one or more files', info=errors ) args = [] for filename in paths: try: with salt.utils.files.fopen(filename, 'rb') as fp_: args.append(fp_.readlines()) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read {0}: {1}'.format( salt.utils.stringutils.to_unicode(filename), exc.strerror ) ) if args[0] != args[1]: if template and __salt__['config.option']('obfuscate_templates'): ret = '<Obfuscated Template>' elif not show_changes: ret = '<show_changes=False>' else: bdiff = _binary_replace(*paths) # pylint: disable=no-value-for-parameter if bdiff: ret = bdiff else: if show_filenames: args.extend(paths) ret = __utils__['stringutils.get_diff'](*args) return ret return '' def manage_file(name, sfn, ret, source, source_sum, user, group, mode, attrs, saltenv, backup, makedirs=False, template=None, # pylint: disable=W0613 show_changes=True, contents=None, dir_mode=None, follow_symlinks=True, skip_verify=False, keep_mode=False, encoding=None, encoding_errors='strict', seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Checks the destination against what was retrieved with get_managed and makes the appropriate modifications (if necessary). name location to place the file sfn location of cached file on the minion This is the path to the file stored on the minion. This file is placed on the minion using cp.cache_file. If the hash sum of that file matches the source_sum, we do not transfer the file to the minion again. This file is then grabbed and if it has template set, it renders the file to be placed into the correct place on the system using salt.files.utils.copyfile() ret The initial state return data structure. Pass in ``None`` to use the default structure. source file reference on the master source_sum sum hash for source user user owner group group owner backup backup_mode attrs attributes to be set on file: '' means remove all of them .. versionadded:: 2018.3.0 makedirs make directories if they do not exist template format of templating show_changes Include diff in state return contents: contents to be placed in the file dir_mode mode for directories created with makedirs skip_verify : False If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 keep_mode : False If ``True``, and the ``source`` is a file from the Salt fileserver (or a local file on the minion), the mode of the destination file will be set to the mode of the source file. .. note:: keep_mode does not work with salt-ssh. As a consequence of how the files are transferred to the minion, and the inability to connect back to the master with salt-ssh, salt is unable to stat the file as it exists on the fileserver and thus cannot mirror the mode on the salt-ssh minion encoding If specified, then the specified encoding will be used. Otherwise, the file will be encoded using the system locale (usually UTF-8). See https://docs.python.org/3/library/codecs.html#standard-encodings for the list of available encodings. .. versionadded:: 2017.7.0 encoding_errors : 'strict' Default is ```'strict'```. See https://docs.python.org/2/library/codecs.html#codec-base-classes for the error handling schemes. .. versionadded:: 2017.7.0 seuser selinux user attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon CLI Example: .. code-block:: bash salt '*' file.manage_file /etc/httpd/conf.d/httpd.conf '' '{}' salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' '' base '' .. versionchanged:: 2014.7.0 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if source: if not sfn: # File is not present, cache it sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) htype = source_sum.get('hash_type', __opts__['hash_type']) # Recalculate source sum now that file has been cached source_sum = { 'hash_type': htype, 'hsum': get_hash(sfn, form=htype) } if keep_mode: if _urlparse(source).scheme in ('salt', 'file', ''): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) # Check changes if the target file exists if os.path.isfile(name) or os.path.islink(name): if os.path.islink(name) and follow_symlinks: real_name = os.path.realpath(name) else: real_name = name # Only test the checksums on files with managed contents if source and not (not follow_symlinks and os.path.islink(real_name)): name_sum = get_hash(real_name, source_sum.get('hash_type', __opts__['hash_type'])) else: name_sum = None # Check if file needs to be replaced if source and (name_sum is None or source_sum.get('hsum', __opts__['hash_type']) != name_sum): if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server or local # source, and we are not skipping checksum verification, then # verify that it matches the specified checksum. if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3}). If the \'source_hash\' value ' 'refers to a remote file with multiple possible ' 'matches, then it may be necessary to set ' '\'source_hash_name\'.'.format( source_sum['hash_type'], source, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # Print a diff equivalent to diff -u old new if __salt__['config.option']('obfuscate_templates'): ret['changes']['diff'] = '<Obfuscated Template>' elif not show_changes: ret['changes']['diff'] = '<show_changes=False>' else: try: ret['changes']['diff'] = get_diff( real_name, sfn, show_filenames=False) except CommandExecutionError as exc: ret['changes']['diff'] = exc.strerror # Pre requisites are met, and the file needs to be replaced, do it try: salt.utils.files.copyfile(sfn, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) try: differences = get_diff( real_name, tmp, show_filenames=False, show_changes=show_changes, template=True) except CommandExecutionError as exc: ret.setdefault('warnings', []).append( 'Failed to detect changes to file: {0}'.format(exc.strerror) ) differences = '' if differences: ret['changes']['diff'] = differences # Pre requisites are met, the file needs to be replaced, do it try: salt.utils.files.copyfile(tmp, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(tmp) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) __clean_tmp(tmp) # Check for changing symlink to regular file here if os.path.islink(name) and not follow_symlinks: if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret try: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) ret['changes']['diff'] = \ 'Replace symbolic link with regular file' if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, follow_symlinks, seuser=seuser, serole=serole, setype=setype, serange=serange) if ret['changes']: ret['comment'] = 'File {0} updated'.format( salt.utils.data.decode(name) ) elif not ret['changes'] and ret['result']: ret['comment'] = 'File {0} is in the correct state'.format( salt.utils.data.decode(name) ) if sfn: __clean_tmp(sfn) return ret else: # target file does not exist contain_dir = os.path.dirname(name) def _set_mode_and_make_dirs(name, dir_mode, mode, user, group): # check for existence of windows drive letter if salt.utils.platform.is_windows(): drive, _ = os.path.splitdrive(name) if drive and not os.path.exists(drive): __clean_tmp(sfn) return _error(ret, '{0} drive not present'.format(drive)) if dir_mode is None and mode is not None: # Add execute bit to each nonzero digit in the mode, if # dir_mode was not specified. Otherwise, any # directories created with makedirs_() below can't be # listed via a shell. mode_list = [x for x in six.text_type(mode)][-3:] for idx in range(len(mode_list)): if mode_list[idx] != '0': mode_list[idx] = six.text_type(int(mode_list[idx]) | 1) dir_mode = ''.join(mode_list) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 makedirs_( path=name, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: makedirs_(name, user=user, group=group, mode=dir_mode) if source: # Apply the new file if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # It is a new file, set the diff accordingly ret['changes']['diff'] = 'New file' if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') else: # source != True if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') # Create the file, user rw-only if mode will be set to prevent # a small security race problem before the permissions are set with salt.utils.files.set_umask(0o077 if mode else None): # Create a new file when test is False and source is None if contents is None: if not __opts__['test']: if touch(name): ret['changes']['new'] = 'file {0} created'.format(name) ret['comment'] = 'Empty file' else: return _error( ret, 'Empty file {0} not created'.format(name) ) else: if not __opts__['test']: if touch(name): ret['changes']['diff'] = 'New file' else: return _error( ret, 'File {0} not created'.format(name) ) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) # Copy into place salt.utils.files.copyfile(tmp, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(tmp) # Now copy the file contents if there is a source file elif sfn: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(sfn) # This is a new file, if no mode specified, use the umask to figure # out what mode to use for the new file. if mode is None and not salt.utils.platform.is_windows(): # Get current umask mask = salt.utils.files.get_umask() # Calculate the mode value that results from the umask mode = oct((0o777 ^ mask) & 0o666) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, seuser=seuser, serole=serole, setype=setype, serange=serange) if not ret['comment']: ret['comment'] = 'File ' + name + ' updated' if __opts__['test']: ret['comment'] = 'File ' + name + ' not updated' elif not ret['changes'] and ret['result']: ret['comment'] = 'File ' + name + ' is in the correct state' if sfn: __clean_tmp(sfn) return ret def mkdir(dir_path, user=None, group=None, mode=None): ''' Ensure that a directory is available. CLI Example: .. code-block:: bash salt '*' file.mkdir /opt/jetty/context ''' dir_path = os.path.expanduser(dir_path) directory = os.path.normpath(dir_path) if not os.path.isdir(directory): # If a caller such as managed() is invoked with makedirs=True, make # sure that any created dirs are created with the same user and group # to follow the principal of least surprise method. makedirs_perms(directory, user, group, mode) return True def makedirs_(path, user=None, group=None, mode=None): ''' Ensure that the directory containing this path is available. .. note:: The path must end with a trailing slash otherwise the directory/directories will be created up to the parent directory. For example if path is ``/opt/code``, then it would be treated as ``/opt/`` but if the path ends with a trailing slash like ``/opt/code/``, then it would be treated as ``/opt/code/``. CLI Example: .. code-block:: bash salt '*' file.makedirs /opt/code/ ''' path = os.path.expanduser(path) if mode: mode = salt.utils.files.normalize_mode(mode) # walk up the directory structure until we find the first existing # directory dirname = os.path.normpath(os.path.dirname(path)) if os.path.isdir(dirname): # There's nothing for us to do msg = 'Directory \'{0}\' already exists'.format(dirname) log.debug(msg) return msg if os.path.exists(dirname): msg = 'The path \'{0}\' already exists and is not a directory'.format( dirname ) log.debug(msg) return msg directories_to_create = [] while True: if os.path.isdir(dirname): break directories_to_create.append(dirname) current_dirname = dirname dirname = os.path.dirname(dirname) if current_dirname == dirname: raise SaltInvocationError( 'Recursive creation for path \'{0}\' would result in an ' 'infinite loop. Please use an absolute path.'.format(dirname) ) # create parent directories from the topmost to the most deeply nested one directories_to_create.reverse() for directory_to_create in directories_to_create: # all directories have the user, group and mode set!! log.debug('Creating directory: %s', directory_to_create) mkdir(directory_to_create, user=user, group=group, mode=mode) def makedirs_perms(name, user=None, group=None, mode='0755'): ''' Taken and modified from os.makedirs to set user, group and mode for each directory created. CLI Example: .. code-block:: bash salt '*' file.makedirs_perms /opt/code ''' name = os.path.expanduser(name) path = os.path head, tail = path.split(name) if not tail: head, tail = path.split(head) if head and tail and not path.exists(head): try: makedirs_perms(head, user, group, mode) except OSError as exc: # be happy if someone already created the path if exc.errno != errno.EEXIST: raise if tail == os.curdir: # xxx/newdir/. exists if xxx/newdir exists return os.mkdir(name) check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) def get_devmm(name): ''' Get major/minor info from a device CLI Example: .. code-block:: bash salt '*' file.get_devmm /dev/chr ''' name = os.path.expanduser(name) if is_chrdev(name) or is_blkdev(name): stat_structure = os.stat(name) return ( os.major(stat_structure.st_rdev), os.minor(stat_structure.st_rdev)) else: return (0, 0) def is_chrdev(name): ''' Check if a file exists and is a character device. CLI Example: .. code-block:: bash salt '*' file.is_chrdev /dev/chr ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the character device does not exist in the first place return False else: raise return stat.S_ISCHR(stat_structure.st_mode) def mknod_chrdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a character device. CLI Example: .. code-block:: bash salt '*' file.mknod_chrdev /dev/chr 180 31 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating character device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFCHR, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created character device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_blkdev(name): ''' Check if a file exists and is a block device. CLI Example: .. code-block:: bash salt '*' file.is_blkdev /dev/blk ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the block device does not exist in the first place return False else: raise return stat.S_ISBLK(stat_structure.st_mode) def mknod_blkdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a block device. CLI Example: .. code-block:: bash salt '*' file.mknod_blkdev /dev/blk 8 999 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating block device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFBLK, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created block device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_fifo(name): ''' Check if a file exists and is a FIFO. CLI Example: .. code-block:: bash salt '*' file.is_fifo /dev/fifo ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the fifo does not exist in the first place return False else: raise return stat.S_ISFIFO(stat_structure.st_mode) def mknod_fifo(name, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a FIFO pipe. CLI Example: .. code-block:: bash salt '*' file.mknod_fifo /dev/fifo ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating FIFO name: %s', name) try: if __opts__['test']: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = None else: if os.mkfifo(name, int(six.text_type(mode).lstrip('0Oo'), 8)) is None: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created fifo check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def mknod(name, ntype, major=0, minor=0, user=None, group=None, mode='0600'): ''' .. versionadded:: 0.17.0 Create a block device, character device, or fifo pipe. Identical to the gnu mknod. CLI Examples: .. code-block:: bash salt '*' file.mknod /dev/chr c 180 31 salt '*' file.mknod /dev/blk b 8 999 salt '*' file.nknod /dev/fifo p ''' ret = False makedirs_(name, user, group) if ntype == 'c': ret = mknod_chrdev(name, major, minor, user, group, mode) elif ntype == 'b': ret = mknod_blkdev(name, major, minor, user, group, mode) elif ntype == 'p': ret = mknod_fifo(name, user, group, mode) else: raise SaltInvocationError( 'Node type unavailable: \'{0}\'. Available node types are ' 'character (\'c\'), block (\'b\'), and pipe (\'p\').'.format(ntype) ) return ret def list_backups(path, limit=None): ''' .. versionadded:: 0.17.0 Lists the previous versions of a file backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups /foo/bar/baz.txt ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows src_dir = parent_dir.replace(':', '_') else: src_dir = parent_dir[1:] # Figure out full path of location of backup file in minion cache bkdir = os.path.join(bkroot, src_dir) if not os.path.isdir(bkdir): return {} files = {} for fname in [x for x in os.listdir(bkdir) if os.path.isfile(os.path.join(bkdir, x))]: if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows strpfmt = '{0}_%a_%b_%d_%H-%M-%S_%f_%Y'.format(basename) else: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(fname, strpfmt) except ValueError: # File didn't match the strp format string, so it's not a backup # for this file. Move on to the next one. continue if salt.utils.platform.is_windows(): str_format = '%a %b %d %Y %H-%M-%S.%f' else: str_format = '%a %b %d %Y %H:%M:%S.%f' files.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime(str_format) location = os.path.join(bkdir, fname) files[timestamp]['Size'] = os.stat(location).st_size files[timestamp]['Location'] = location return dict(list(zip( list(range(len(files))), [files[x] for x in sorted(files, reverse=True)[:limit]] ))) list_backup = salt.utils.functools.alias_function(list_backups, 'list_backup') def list_backups_dir(path, limit=None): ''' Lists the previous versions of a directory backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The directory on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups_dir /foo/bar/baz/ ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups_dir: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) # Figure out full path of location of backup folder in minion cache bkdir = os.path.join(bkroot, parent_dir[1:]) if not os.path.isdir(bkdir): return {} files = {} f = dict([(i, len(list(n))) for i, n in itertools.groupby([x.split("_")[0] for x in sorted(os.listdir(bkdir))])]) ff = os.listdir(bkdir) for i, n in six.iteritems(f): ssfile = {} for x in sorted(ff): basename = x.split('_')[0] if i == basename: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(x, strpfmt) except ValueError: # Folder didn't match the strp format string, so it's not a backup # for this folder. Move on to the next one. continue ssfile.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime('%a %b %d %Y %H:%M:%S.%f') location = os.path.join(bkdir, x) ssfile[timestamp]['Size'] = os.stat(location).st_size ssfile[timestamp]['Location'] = location sfiles = dict(list(zip(list(range(n)), [ssfile[x] for x in sorted(ssfile, reverse=True)[:limit]]))) sefiles = {i: sfiles} files.update(sefiles) return files def restore_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Restore a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to restore, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.restore_backup /foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) # Note: This only supports minion backups, so this function will need to be # modified if/when master backups are implemented. ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret salt.utils.files.backup_minion(path, _get_bkroot()) try: shutil.copyfile(backup['Location'], path) except IOError as exc: ret['comment'] = \ 'Unable to restore {0} to {1}: ' \ '{2}'.format(backup['Location'], path, exc) return ret else: ret['result'] = True ret['comment'] = 'Successfully restored {0} to ' \ '{1}'.format(backup['Location'], path) # Try to set proper ownership if not salt.utils.platform.is_windows(): try: fstat = os.stat(path) except (OSError, IOError): ret['comment'] += ', but was unable to set ownership' else: os.chown(path, fstat.st_uid, fstat.st_gid) return ret def delete_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Delete a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to delete, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.delete_backup /var/cache/salt/minion/file_backup/home/foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret try: os.remove(backup['Location']) except IOError as exc: ret['comment'] = 'Unable to remove {0}: {1}'.format(backup['Location'], exc) else: ret['result'] = True ret['comment'] = 'Successfully removed {0}'.format(backup['Location']) return ret remove_backup = salt.utils.functools.alias_function(delete_backup, 'remove_backup') def grep(path, pattern, *opts): ''' Grep for a string in the specified file .. note:: This function's return value is slated for refinement in future versions of Salt path Path to the file to be searched .. note:: Globbing is supported (i.e. ``/var/log/foo/*.log``, but if globbing is being used then the path should be quoted to keep the shell from attempting to expand the glob expression. pattern Pattern to match. For example: ``test``, or ``a[0-5]`` opts Additional command-line flags to pass to the grep command. For example: ``-v``, or ``-i -B2`` .. note:: The options should come after a double-dash (as shown in the examples below) to keep Salt's own argument parser from interpreting them. CLI Example: .. code-block:: bash salt '*' file.grep /etc/passwd nobody salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i -B2 salt '*' file.grep "/etc/sysconfig/network-scripts/*" ipaddr -- -i -l ''' path = os.path.expanduser(path) # Backup the path in case the glob returns nothing _path = path path = glob.glob(path) # If the list is empty no files exist # so we revert back to the original path # so the result is an error. if not path: path = _path split_opts = [] for opt in opts: try: split = salt.utils.args.shlex_split(opt) except AttributeError: split = salt.utils.args.shlex_split(six.text_type(opt)) if len(split) > 1: raise SaltInvocationError( 'Passing multiple command line arguments in a single string ' 'is not supported, please pass the following arguments ' 'separately: {0}'.format(opt) ) split_opts.extend(split) if isinstance(path, list): cmd = ['grep'] + split_opts + [pattern] + path else: cmd = ['grep'] + split_opts + [pattern, path] try: ret = __salt__['cmd.run_all'](cmd, python_shell=False) except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return ret def open_files(by_pid=False): ''' Return a list of all physical open files on the system. CLI Examples: .. code-block:: bash salt '*' file.open_files salt '*' file.open_files by_pid=True ''' # First we collect valid PIDs pids = {} procfs = os.listdir('/proc/') for pfile in procfs: try: pids[int(pfile)] = [] except ValueError: # Not a valid PID, move on pass # Then we look at the open files for each PID files = {} for pid in pids: ppath = '/proc/{0}'.format(pid) try: tids = os.listdir('{0}/task'.format(ppath)) except OSError: continue # Collect the names of all of the file descriptors fd_ = [] #try: # fd_.append(os.path.realpath('{0}/task/{1}exe'.format(ppath, tid))) #except Exception: # pass for fpath in os.listdir('{0}/fd'.format(ppath)): fd_.append('{0}/fd/{1}'.format(ppath, fpath)) for tid in tids: try: fd_.append( os.path.realpath('{0}/task/{1}/exe'.format(ppath, tid)) ) except OSError: continue for tpath in os.listdir('{0}/task/{1}/fd'.format(ppath, tid)): fd_.append('{0}/task/{1}/fd/{2}'.format(ppath, tid, tpath)) fd_ = sorted(set(fd_)) # Loop through file descriptors and return useful data for each file for fdpath in fd_: # Sometimes PIDs and TIDs disappear before we can query them try: name = os.path.realpath(fdpath) # Running stat on the file cuts out all of the sockets and # deleted files from the list os.stat(name) except OSError: continue if name not in files: files[name] = [pid] else: # We still want to know which PIDs are using each file files[name].append(pid) files[name] = sorted(set(files[name])) pids[pid].append(name) pids[pid] = sorted(set(pids[pid])) if by_pid: return pids return files def pardir(): ''' Return the relative parent directory path symbol for underlying OS .. versionadded:: 2014.7.0 This can be useful when constructing Salt Formulas. .. code-block:: jinja {% set pardir = salt['file.pardir']() %} {% set final_path = salt['file.join']('subdir', pardir, 'confdir') %} CLI Example: .. code-block:: bash salt '*' file.pardir ''' return os.path.pardir def normpath(path): ''' Returns Normalize path, eliminating double slashes, etc. .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.normpath'](tpldir + '/../vars.jinja') import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.normpath 'a/b/c/..' ''' return os.path.normpath(path) def basename(path): ''' Returns the final component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- set filename = salt['file.basename'](source_file) %} CLI Example: .. code-block:: bash salt '*' file.basename 'test/test.config' ''' return os.path.basename(path) def dirname(path): ''' Returns the directory component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.dirname'](tpldir) + '/vars.jinja' import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.dirname 'test/path/filename.config' ''' return os.path.dirname(path) def join(*args): ''' Return a normalized file system path for the underlying OS .. versionadded:: 2014.7.0 This can be useful at the CLI but is frequently useful when scripting combining path variables: .. code-block:: jinja {% set www_root = '/var' %} {% set app_dir = 'myapp' %} myapp_config: file: - managed - name: {{ salt['file.join'](www_root, app_dir, 'config.yaml') }} CLI Example: .. code-block:: bash salt '*' file.join '/' 'usr' 'local' 'bin' ''' return os.path.join(*args) def move(src, dst): ''' Move a file or directory CLI Example: .. code-block:: bash salt '*' file.move /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('Source path must be absolute.') if not os.path.isabs(dst): raise SaltInvocationError('Destination path must be absolute.') ret = { 'result': True, 'comment': "'{0}' moved to '{1}'".format(src, dst), } try: shutil.move(src, dst) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move '{0}' to '{1}': {2}".format(src, dst, exc) ) return ret def diskusage(path): ''' Recursively calculate disk usage of path and return it in bytes CLI Example: .. code-block:: bash salt '*' file.diskusage /path/to/check ''' total_size = 0 seen = set() if os.path.isfile(path): stat_structure = os.stat(path) ret = stat_structure.st_size return ret for dirpath, dirnames, filenames in salt.utils.path.os_walk(path): for f in filenames: fp = os.path.join(dirpath, f) try: stat_structure = os.stat(fp) except OSError: continue if stat_structure.st_ino in seen: continue seen.add(stat_structure.st_ino) total_size += stat_structure.st_size ret = total_size return ret
saltstack/salt
salt/modules/file.py
get_uid
python
def get_uid(path, follow_symlinks=True): ''' Return the id of the user that owns a given file path file or directory of which to get the uid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_uid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('uid', -1)
Return the id of the user that owns a given file path file or directory of which to get the uid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_uid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L303-L322
[ "def stats(path, hash_type=None, follow_symlinks=True):\n '''\n Return a dict containing the stats for a given file\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' file.stats /etc/passwd\n '''\n path = os.path.expanduser(path)\n\n ret = {}\n if not os.path.exists(path):\n try:\n # Broken symlinks will return False for os.path.exists(), but still\n # have a uid and gid\n pstat = os.lstat(path)\n except OSError:\n # Not a broken symlink, just a nonexistent path\n # NOTE: The file.directory state checks the content of the error\n # message in this exception. Any changes made to the message for this\n # exception will reflect the file.directory state as well, and will\n # likely require changes there.\n raise CommandExecutionError('Path not found: {0}'.format(path))\n else:\n if follow_symlinks:\n pstat = os.stat(path)\n else:\n pstat = os.lstat(path)\n ret['inode'] = pstat.st_ino\n ret['uid'] = pstat.st_uid\n ret['gid'] = pstat.st_gid\n ret['group'] = gid_to_group(pstat.st_gid)\n ret['user'] = uid_to_user(pstat.st_uid)\n ret['atime'] = pstat.st_atime\n ret['mtime'] = pstat.st_mtime\n ret['ctime'] = pstat.st_ctime\n ret['size'] = pstat.st_size\n ret['mode'] = six.text_type(oct(stat.S_IMODE(pstat.st_mode)))\n if hash_type:\n ret['sum'] = get_hash(path, hash_type)\n ret['type'] = 'file'\n if stat.S_ISDIR(pstat.st_mode):\n ret['type'] = 'dir'\n if stat.S_ISCHR(pstat.st_mode):\n ret['type'] = 'char'\n if stat.S_ISBLK(pstat.st_mode):\n ret['type'] = 'block'\n if stat.S_ISREG(pstat.st_mode):\n ret['type'] = 'file'\n if stat.S_ISLNK(pstat.st_mode):\n ret['type'] = 'link'\n if stat.S_ISFIFO(pstat.st_mode):\n ret['type'] = 'pipe'\n if stat.S_ISSOCK(pstat.st_mode):\n ret['type'] = 'socket'\n ret['target'] = os.path.realpath(path)\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage information about regular files, directories, and special files on the minion, set/read user, group, mode, and data ''' # TODO: We should add the capability to do u+r type operations here # some time in the future from __future__ import absolute_import, print_function, unicode_literals # Import python libs import datetime import errno import fnmatch import io import itertools import logging import operator import os import re import shutil import stat import string import sys import tempfile import time import glob import hashlib import mmap from collections import Iterable, Mapping from functools import reduce # pylint: disable=redefined-builtin # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range, zip from salt.ext.six.moves.urllib.parse import urlparse as _urlparse # pylint: enable=import-error,no-name-in-module,redefined-builtin try: import grp import pwd except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.atomicfile import salt.utils.data import salt.utils.dictupdate import salt.utils.filebuffer import salt.utils.files import salt.utils.find import salt.utils.functools import salt.utils.hashutils import salt.utils.itertools import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.templates import salt.utils.url import salt.utils.user from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError, get_error_message as _get_error_message from salt.utils.files import HASHES, HASHES_REVMAP log = logging.getLogger(__name__) __func_alias__ = { 'makedirs_': 'makedirs' } def __virtual__(): ''' Only work on POSIX-like systems ''' # win_file takes care of windows if salt.utils.platform.is_windows(): return ( False, 'The file execution module cannot be loaded: only available on ' 'non-Windows systems - use win_file instead.' ) return True def __clean_tmp(sfn): ''' Clean out a template temp file ''' if sfn.startswith(os.path.join(tempfile.gettempdir(), salt.utils.files.TEMPFILE_PREFIX)): # Don't remove if it exists in file_roots (any saltenv) all_roots = itertools.chain.from_iterable( six.itervalues(__opts__['file_roots'])) in_roots = any(sfn.startswith(root) for root in all_roots) # Only clean up files that exist if os.path.exists(sfn) and not in_roots: os.remove(sfn) def _error(ret, err_msg): ''' Common function for setting error information for return dicts ''' ret['result'] = False ret['comment'] = err_msg return ret def _binary_replace(old, new): ''' This function does NOT do any diffing, it just checks the old and new files to see if either is binary, and provides an appropriate string noting the difference between the two files. If neither file is binary, an empty string is returned. This function should only be run AFTER it has been determined that the files differ. ''' old_isbin = not __utils__['files.is_text'](old) new_isbin = not __utils__['files.is_text'](new) if any((old_isbin, new_isbin)): if all((old_isbin, new_isbin)): return 'Replace binary file' elif old_isbin: return 'Replace binary file with text file' elif new_isbin: return 'Replace text file with binary file' return '' def _get_bkroot(): ''' Get the location of the backup dir in the minion cache ''' # Get the cachedir from the minion config return os.path.join(__salt__['config.get']('cachedir'), 'file_backup') def _splitlines_preserving_trailing_newline(str): ''' Returns a list of the lines in the string, breaking at line boundaries and preserving a trailing newline (if present). Essentially, this works like ``str.striplines(False)`` but preserves an empty line at the end. This is equivalent to the following code: .. code-block:: python lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') ''' lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') return lines def gid_to_group(gid): ''' Convert the group id to the group name on this system gid gid to convert to a group name CLI Example: .. code-block:: bash salt '*' file.gid_to_group 0 ''' try: gid = int(gid) except ValueError: # This is not an integer, maybe it's already the group name? gid = group_to_gid(gid) if gid == '': # Don't even bother to feed it to grp return '' try: return grp.getgrgid(gid).gr_name except (KeyError, NameError): # If group is not present, fall back to the gid. return gid def group_to_gid(group): ''' Convert the group to the gid on this system group group to convert to its gid CLI Example: .. code-block:: bash salt '*' file.group_to_gid root ''' if group is None: return '' try: if isinstance(group, int): return group return grp.getgrnam(group).gr_gid except KeyError: return '' def get_gid(path, follow_symlinks=True): ''' Return the id of the group that owns a given file path file or directory of which to get the gid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_gid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('gid', -1) def get_group(path, follow_symlinks=True): ''' Return the group that owns a given file path file or directory of which to get the group follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_group /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('group', False) def uid_to_user(uid): ''' Convert a uid to a user name uid uid to convert to a username CLI Example: .. code-block:: bash salt '*' file.uid_to_user 0 ''' try: return pwd.getpwuid(uid).pw_name except (KeyError, NameError): # If user is not present, fall back to the uid. return uid def user_to_uid(user): ''' Convert user name to a uid user user name to convert to its uid CLI Example: .. code-block:: bash salt '*' file.user_to_uid root ''' if user is None: user = salt.utils.user.get_user() try: if isinstance(user, int): return user return pwd.getpwnam(user).pw_uid except KeyError: return '' def get_user(path, follow_symlinks=True): ''' Return the user that owns a given file path file or directory of which to get the user follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_user /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('user', False) def get_mode(path, follow_symlinks=True): ''' Return the mode of a file path file or directory of which to get the mode follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_mode /etc/passwd .. versionchanged:: 2014.1.0 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('mode', '') def set_mode(path, mode): ''' Set the mode of a file path file or directory of which to set the mode mode mode to set the path to CLI Example: .. code-block:: bash salt '*' file.set_mode /etc/passwd 0644 ''' path = os.path.expanduser(path) mode = six.text_type(mode).lstrip('0Oo') if not mode: mode = '0' if not os.path.exists(path): raise CommandExecutionError('{0}: File not found'.format(path)) try: os.chmod(path, int(mode, 8)) except Exception: return 'Invalid Mode ' + mode return get_mode(path) def lchown(path, user, group): ''' Chown a file, pass the file the desired user and group without following symlinks. path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 return os.lchown(path, uid, gid) def chown(path, user, group): ''' Chown a file, pass the file the desired user and group path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 if not os.path.exists(path): try: # Broken symlinks will return false, but still need to be chowned return os.lchown(path, uid, gid) except OSError: pass err += 'File not found' if err: return err return os.chown(path, uid, gid) def chgrp(path, group): ''' Change the group of a file path path to the file or directory group group owner CLI Example: .. code-block:: bash salt '*' file.chgrp /etc/passwd root ''' path = os.path.expanduser(path) user = get_user(path) return chown(path, user, group) def _cmp_attrs(path, attrs): ''' .. versionadded:: 2018.3.0 Compare attributes of a given file to given attributes. Returns a pair (list) where first item are attributes to add and second item are to be removed. Please take into account when using this function that some minions will not have lsattr installed. path path to file to compare attributes with. attrs string of attributes to compare against a given file ''' diff = [None, None] # lsattr for AIX is not the same thing as lsattr for linux. if salt.utils.platform.is_aix(): return None try: lattrs = lsattr(path).get(path, '') except AttributeError: # lsattr not installed return None old = [chr for chr in lattrs if chr not in attrs] if old: diff[1] = ''.join(old) new = [chr for chr in attrs if chr not in lattrs] if new: diff[0] = ''.join(new) return diff def lsattr(path): ''' .. versionadded:: 2018.3.0 .. versionchanged:: 2018.3.1 If ``lsattr`` is not installed on the system, ``None`` is returned. .. versionchanged:: 2018.3.4 If on ``AIX``, ``None`` is returned even if in filesystem as lsattr on ``AIX`` is not the same thing as the linux version. Obtain the modifiable attributes of the given file. If path is to a directory, an empty list is returned. path path to file to obtain attributes of. File/directory must exist. CLI Example: .. code-block:: bash salt '*' file.lsattr foo1.txt ''' if not salt.utils.path.which('lsattr') or salt.utils.platform.is_aix(): return None if not os.path.exists(path): raise SaltInvocationError("File or directory does not exist: " + path) cmd = ['lsattr', path] result = __salt__['cmd.run'](cmd, ignore_retcode=True, python_shell=False) results = {} for line in result.splitlines(): if not line.startswith('lsattr: '): vals = line.split(None, 1) results[vals[1]] = re.findall(r"[aAcCdDeijPsStTu]", vals[0]) return results def chattr(*files, **kwargs): ''' .. versionadded:: 2018.3.0 Change the attributes of files. This function accepts one or more files and the following options: operator Can be wither ``add`` or ``remove``. Determines whether attributes should be added or removed from files attributes One or more of the following characters: ``aAcCdDeijPsStTu``, representing attributes to add to/remove from files version a version number to assign to the file(s) flags One or more of the following characters: ``RVf``, representing flags to assign to chattr (recurse, verbose, suppress most errors) CLI Example: .. code-block:: bash salt '*' file.chattr foo1.txt foo2.txt operator=add attributes=ai salt '*' file.chattr foo3.txt operator=remove attributes=i version=2 ''' operator = kwargs.pop('operator', None) attributes = kwargs.pop('attributes', None) flags = kwargs.pop('flags', None) version = kwargs.pop('version', None) if (operator is None) or (operator not in ('add', 'remove')): raise SaltInvocationError( "Need an operator: 'add' or 'remove' to modify attributes.") if attributes is None: raise SaltInvocationError("Need attributes: [aAcCdDeijPsStTu]") cmd = ['chattr'] if operator == "add": attrs = '+{0}'.format(attributes) elif operator == "remove": attrs = '-{0}'.format(attributes) cmd.append(attrs) if flags is not None: cmd.append('-{0}'.format(flags)) if version is not None: cmd.extend(['-v', version]) cmd.extend(files) result = __salt__['cmd.run'](cmd, python_shell=False) if bool(result): raise CommandExecutionError( "chattr failed to run, possibly due to bad parameters.") return True def get_sum(path, form='sha256'): ''' Return the checksum for the given file. The following checksum algorithms are supported: * md5 * sha1 * sha224 * sha256 **(default)** * sha384 * sha512 path path to the file or directory form desired sum format CLI Example: .. code-block:: bash salt '*' file.get_sum /etc/passwd sha512 ''' path = os.path.expanduser(path) if not os.path.isfile(path): return 'File not found' return salt.utils.hashutils.get_hash(path, form, 4096) def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` path path to the file or directory form desired sum format chunk_size amount to sum at once CLI Example: .. code-block:: bash salt '*' file.get_hash /etc/shadow ''' return salt.utils.hashutils.get_hash(os.path.expanduser(path), form, chunk_size) def get_source_sum(file_name='', source='', source_hash=None, source_hash_name=None, saltenv='base'): ''' .. versionadded:: 2016.11.0 Used by :py:func:`file.get_managed <salt.modules.file.get_managed>` to obtain the hash and hash type from the parameters specified below. file_name Optional file name being managed, for matching with :py:func:`file.extract_hash <salt.modules.file.extract_hash>`. source Source file, as used in :py:mod:`file <salt.states.file>` and other states. If ``source_hash`` refers to a file containing hashes, then this filename will be used to match a filename in that file. If the ``source_hash`` is a hash expression, then this argument will be ignored. source_hash Hash file/expression, as used in :py:mod:`file <salt.states.file>` and other states. If this value refers to a remote URL or absolute path to a local file, it will be cached and :py:func:`file.extract_hash <salt.modules.file.extract_hash>` will be used to obtain a hash from it. source_hash_name Specific file name to look for when ``source_hash`` refers to a remote file, used to disambiguate ambiguous matches. saltenv : base Salt fileserver environment from which to retrieve the source_hash. This value will only be used when ``source_hash`` refers to a file on the Salt fileserver (i.e. one beginning with ``salt://``). CLI Example: .. code-block:: bash salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=499ae16dcae71eeb7c3a30c75ea7a1a6 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 source_hash_name=./dir2/foo.tar.gz ''' def _invalid_source_hash_format(): ''' DRY helper for reporting invalid source_hash input ''' raise CommandExecutionError( 'Source hash {0} format is invalid. The supported formats are: ' '1) a hash, 2) an expression in the format <hash_type>=<hash>, or ' '3) either a path to a local file containing hashes, or a URI of ' 'a remote hash file. Supported protocols for remote hash files ' 'are: {1}. The hash may also not be of a valid length, the ' 'following are supported hash types and lengths: {2}.'.format( source_hash, ', '.join(salt.utils.files.VALID_PROTOS), ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) hash_fn = None if os.path.isabs(source_hash): hash_fn = source_hash else: try: proto = _urlparse(source_hash).scheme if proto in salt.utils.files.VALID_PROTOS: hash_fn = __salt__['cp.cache_file'](source_hash, saltenv) if not hash_fn: raise CommandExecutionError( 'Source hash file {0} not found'.format(source_hash) ) else: if proto != '': # Some unsupported protocol (e.g. foo://) is being used. # We'll get into this else block if a hash expression # (like md5=<md5 checksum here>), but in those cases, the # protocol will be an empty string, in which case we avoid # this error condition. _invalid_source_hash_format() except (AttributeError, TypeError): _invalid_source_hash_format() if hash_fn is not None: ret = extract_hash(hash_fn, '', file_name, source, source_hash_name) if ret is None: _invalid_source_hash_format() ret['hsum'] = ret['hsum'].lower() return ret else: # The source_hash is a hash expression ret = {} try: ret['hash_type'], ret['hsum'] = \ [x.strip() for x in source_hash.split('=', 1)] except AttributeError: _invalid_source_hash_format() except ValueError: # No hash type, try to figure out by hash length if not re.match('^[{0}]+$'.format(string.hexdigits), source_hash): _invalid_source_hash_format() ret['hsum'] = source_hash source_hash_len = len(source_hash) if source_hash_len in HASHES_REVMAP: ret['hash_type'] = HASHES_REVMAP[source_hash_len] else: _invalid_source_hash_format() if ret['hash_type'] not in HASHES: raise CommandExecutionError( 'Invalid hash type \'{0}\'. Supported hash types are: {1}. ' 'Either remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to a supported type.' .format(ret['hash_type'], ', '.join(HASHES), ret['hsum']) ) else: hsum_len = len(ret['hsum']) if hsum_len not in HASHES_REVMAP: _invalid_source_hash_format() elif hsum_len != HASHES[ret['hash_type']]: raise CommandExecutionError( 'Invalid length ({0}) for hash type \'{1}\'. Either ' 'remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to \'{3}\''.format( hsum_len, ret['hash_type'], ret['hsum'], HASHES_REVMAP[hsum_len], ) ) ret['hsum'] = ret['hsum'].lower() return ret def check_hash(path, file_hash): ''' Check if a file matches the given hash string Returns ``True`` if the hash matches, otherwise ``False``. path Path to a file local to the minion. hash The hash to check against the file specified in the ``path`` argument. .. versionchanged:: 2016.11.4 For this and newer versions the hash can be specified without an accompanying hash type (e.g. ``e138491e9d5b97023cea823fe17bac22``), but for earlier releases it is necessary to also specify the hash type in the format ``<hash_type>=<hash_value>`` (e.g. ``md5=e138491e9d5b97023cea823fe17bac22``). CLI Example: .. code-block:: bash salt '*' file.check_hash /etc/fstab e138491e9d5b97023cea823fe17bac22 salt '*' file.check_hash /etc/fstab md5=e138491e9d5b97023cea823fe17bac22 ''' path = os.path.expanduser(path) if not isinstance(file_hash, six.string_types): raise SaltInvocationError('hash must be a string') for sep in (':', '='): if sep in file_hash: hash_type, hash_value = file_hash.split(sep, 1) break else: hash_value = file_hash hash_len = len(file_hash) hash_type = HASHES_REVMAP.get(hash_len) if hash_type is None: raise SaltInvocationError( 'Hash {0} (length: {1}) could not be matched to a supported ' 'hash type. The supported hash types and lengths are: ' '{2}'.format( file_hash, hash_len, ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) return get_hash(path, hash_type) == hash_value def find(path, *args, **kwargs): ''' Approximate the Unix ``find(1)`` command and return a list of paths that meet the specified criteria. The options include match criteria: .. code-block:: text name = path-glob # case sensitive iname = path-glob # case insensitive regex = path-regex # case sensitive iregex = path-regex # case insensitive type = file-types # match any listed type user = users # match any listed user group = groups # match any listed group size = [+-]number[size-unit] # default unit = byte mtime = interval # modified since date grep = regex # search file contents and/or actions: .. code-block:: text delete [= file-types] # default type = 'f' exec = command [arg ...] # where {} is replaced by pathname print [= print-opts] and/or depth criteria: .. code-block:: text maxdepth = maximum depth to transverse in path mindepth = minimum depth to transverse before checking files or directories The default action is ``print=path`` ``path-glob``: .. code-block:: text * = match zero or more chars ? = match any char [abc] = match a, b, or c [!abc] or [^abc] = match anything except a, b, and c [x-y] = match chars x through y [!x-y] or [^x-y] = match anything except chars x through y {a,b,c} = match a or b or c ``path-regex``: a Python Regex (regular expression) pattern to match pathnames ``file-types``: a string of one or more of the following: .. code-block:: text a: all file types b: block device c: character device d: directory p: FIFO (named pipe) f: plain file l: symlink s: socket ``users``: a space and/or comma separated list of user names and/or uids ``groups``: a space and/or comma separated list of group names and/or gids ``size-unit``: .. code-block:: text b: bytes k: kilobytes m: megabytes g: gigabytes t: terabytes interval: .. code-block:: text [<num>w] [<num>d] [<num>h] [<num>m] [<num>s] where: w: week d: day h: hour m: minute s: second print-opts: a comma and/or space separated list of one or more of the following: .. code-block:: text group: group name md5: MD5 digest of file contents mode: file permissions (as integer) mtime: last modification time (as time_t) name: file basename path: file absolute path size: file size in bytes type: file type user: user name CLI Examples: .. code-block:: bash salt '*' file.find / type=f name=\\*.bak size=+10m salt '*' file.find /var mtime=+30d size=+10m print=path,size,mtime salt '*' file.find /var/log name=\\*.[0-9] mtime=+30d size=+10m delete ''' if 'delete' in args: kwargs['delete'] = 'f' elif 'print' in args: kwargs['print'] = 'path' try: finder = salt.utils.find.Finder(kwargs) except ValueError as ex: return 'error: {0}'.format(ex) ret = [item for i in [finder.find(p) for p in glob.glob(os.path.expanduser(path))] for item in i] ret.sort() return ret def _sed_esc(string, escape_all=False): ''' Escape single quotes and forward slashes ''' special_chars = "^.[$()|*+?{" string = string.replace("'", "'\"'\"'").replace("/", "\\/") if escape_all is True: for char in special_chars: string = string.replace(char, "\\" + char) return string def sed(path, before, after, limit='', backup='.bak', options='-r -e', flags='g', escape_all=False, negate_match=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup options : ``-r -e`` Options to pass to sed flags : ``g`` Flags to modify the sed search; e.g., ``i`` for case-insensitive pattern matching negate_match : False Negate the search command (``!``) .. versionadded:: 0.17.0 Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # path = os.path.expanduser(path) if not os.path.exists(path): return False # Mandate that before and after are strings before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.append('-i{0}'.format(backup) if backup else '-i') cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}{negate_match}s/{before}/{after}/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', negate_match='!' if negate_match else '', before=before, after=after, flags=flags ) ) cmd.append(path) return __salt__['cmd.run_all'](cmd, python_shell=False) def sed_contains(path, text, limit='', flags='g'): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the file at ``path`` contains ``text``. Utilizes sed to perform the search (line-wise search). Note: the ``p`` flag will be added to any flags you pass in. CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' # Largely inspired by Fabric's contrib.files.contains() path = os.path.expanduser(path) if not os.path.exists(path): return False before = _sed_esc(six.text_type(text), False) limit = _sed_esc(six.text_type(limit), False) options = '-n -r -e' if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}s/{before}/$/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', before=before, flags='p{0}'.format(flags) ) ) cmd.append(path) result = __salt__['cmd.run'](cmd, python_shell=False) return bool(result) def psed(path, before, after, limit='', backup='.bak', flags='gMS', escape_all=False, multi=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file (pure Python version) Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup flags : ``gMS`` Flags to modify the search. Valid values are: - ``g``: Replace all occurrences of the pattern, not just the first. - ``I``: Ignore case. - ``L``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\s`` and ``\\S`` dependent on the locale. - ``M``: Treat multiple lines as a single line. - ``S``: Make `.` match all characters, including newlines. - ``U``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\d``, ``\\D``, ``\\s`` and ``\\S`` dependent on Unicode. - ``X``: Verbose (whitespace is ignored). multi: ``False`` If True, treat the entire file as a single line Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # # Mandate that before and after are strings path = os.path.expanduser(path) multi = bool(multi) before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) # The pattern to replace with does not need to be escaped!!! # after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) shutil.copy2(path, '{0}{1}'.format(path, backup)) with salt.utils.files.fopen(path, 'w') as ofile: with salt.utils.files.fopen('{0}{1}'.format(path, backup), 'r') as ifile: if multi is True: for line in ifile.readline(): ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(line), before, after, limit, flags ) ) ) else: ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(ifile.read()), before, after, limit, flags ) ) ) RE_FLAG_TABLE = {'I': re.I, 'L': re.L, 'M': re.M, 'S': re.S, 'U': re.U, 'X': re.X} def _psed(text, before, after, limit, flags): ''' Does the actual work for file.psed, so that single lines can be passed in ''' atext = text if limit: limit = re.compile(limit) comps = text.split(limit) atext = ''.join(comps[1:]) count = 1 if 'g' in flags: count = 0 flags = flags.replace('g', '') aflags = 0 for flag in flags: aflags |= RE_FLAG_TABLE[flag] before = re.compile(before, flags=aflags) text = re.sub(before, after, atext, count=count) return text def uncomment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Uncomment specified commented lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be uncommented. This regex should not include the comment character. A leading ``^`` character will be stripped for convenience (for easily switching between comment() and uncomment()). char : ``#`` The character to remove in order to uncomment a line backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup CLI Example: .. code-block:: bash salt '*' file.uncomment /etc/hosts.deny 'ALL: PARANOID' ''' return comment_line(path=path, regex=regex, char=char, cmnt=False, backup=backup) def comment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Comment out specified lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be commented; this pattern will be wrapped in parenthesis and will move any preceding/trailing ``^`` or ``$`` characters outside the parenthesis (e.g., the pattern ``^foo$`` will be rewritten as ``^(foo)$``) char : ``#`` The character to be inserted at the beginning of a line in order to comment it out backup : ``.bak`` The file will be backed up before edit with this file extension .. warning:: This backup will be overwritten each time ``sed`` / ``comment`` / ``uncomment`` is called. Meaning the backup will only be useful after the first invocation. CLI Example: .. code-block:: bash salt '*' file.comment /etc/modules pcspkr ''' return comment_line(path=path, regex=regex, char=char, cmnt=True, backup=backup) def comment_line(path, regex, char='#', cmnt=True, backup='.bak'): r''' Comment or Uncomment a line in a text file. :param path: string The full path to the text file. :param regex: string A regex expression that begins with ``^`` that will find the line you wish to comment. Can be as simple as ``^color =`` :param char: string The character used to comment a line in the type of file you're referencing. Default is ``#`` :param cmnt: boolean True to comment the line. False to uncomment the line. Default is True. :param backup: string The file extension to give the backup file. Default is ``.bak`` Set to False/None to not keep a backup. :return: boolean Returns True if successful, False if not CLI Example: The following example will comment out the ``pcspkr`` line in the ``/etc/modules`` file using the default ``#`` character and create a backup file named ``modules.bak`` .. code-block:: bash salt '*' file.comment_line '/etc/modules' '^pcspkr' CLI Example: The following example will uncomment the ``log_level`` setting in ``minion`` config file if it is set to either ``warning``, ``info``, or ``debug`` using the ``#`` character and create a backup file named ``minion.bk`` .. code-block:: bash salt '*' file.comment_line 'C:\salt\conf\minion' '^log_level: (warning|info|debug)' '#' False '.bk' ''' # Get the regex for comment or uncomment if cmnt: regex = '{0}({1}){2}'.format( '^' if regex.startswith('^') else '', regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') else: regex = r'^{0}\s*({1}){2}'.format( char, regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') # Load the real path to the file path = os.path.realpath(os.path.expanduser(path)) # Make sure the file exists if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) # Make sure it is a text file if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}'.format(path)) # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes found = False # Dictionaries for comparing changes orig_file = [] new_file = [] # Buffer size for fopen bufsize = os.path.getsize(path) try: # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: # Is it in this line line = salt.utils.stringutils.to_unicode(line) if re.match(regex, line): # Load lines into dictionaries, set found to True orig_file.append(line) if cmnt: new_file.append('{0}{1}'.format(char, line)) else: new_file.append(line.lstrip(char)) found = True except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) # We've searched the whole file. If we didn't find anything, return False if not found: return False if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Create a copy to read from and to use as a backup later try: temp_file = _mkstemp_copy(path=path, preserve_inode=False) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) try: # Open the file in write mode mode = 'wb' if six.PY2 and salt.utils.platform.is_windows() else 'w' with salt.utils.files.fopen(path, mode=mode, buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: line = salt.utils.stringutils.to_unicode(line) try: # Is it in this line if re.match(regex, line): # Write the new line if cmnt: wline = '{0}{1}'.format(char, line) else: wline = line.lstrip(char) else: # Write the existing line (no change) wline = line wline = salt.utils.stringutils.to_bytes(wline) \ if six.PY2 and salt.utils.platform.is_windows() \ else salt.utils.stringutils.to_str(wline) w_file.write(wline) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if backup: # Move the backup file to the original directory backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: os.remove(temp_file) if not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) # Return a diff using the two dictionaries return __utils__['stringutils.get_diff'](orig_file, new_file) def _get_flags(flags): ''' Return an integer appropriate for use as a flag for the re module from a list of human-readable strings .. code-block:: python >>> _get_flags(['MULTILINE', 'IGNORECASE']) 10 >>> _get_flags('MULTILINE') 8 >>> _get_flags(2) 2 ''' if isinstance(flags, six.string_types): flags = [flags] if isinstance(flags, Iterable) and not isinstance(flags, Mapping): _flags_acc = [] for flag in flags: _flag = getattr(re, six.text_type(flag).upper()) if not isinstance(_flag, six.integer_types): raise SaltInvocationError( 'Invalid re flag given: {0}'.format(flag) ) _flags_acc.append(_flag) return reduce(operator.__or__, _flags_acc) elif isinstance(flags, six.integer_types): return flags else: raise SaltInvocationError( 'Invalid re flags: "{0}", must be given either as a single flag ' 'string, a list of strings, or as an integer'.format(flags) ) def _add_flags(flags, new_flags): ''' Combine ``flags`` and ``new_flags`` ''' flags = _get_flags(flags) new_flags = _get_flags(new_flags) return flags | new_flags def _mkstemp_copy(path, preserve_inode=True): ''' Create a temp file and move/copy the contents of ``path`` to the temp file. Return the path to the temp file. path The full path to the file whose contents will be moved/copied to a temp file. Whether it's moved or copied depends on the value of ``preserve_inode``. preserve_inode Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). Default is ``True``. ''' temp_file = None # Create the temp file try: temp_file = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to create temp file. " "Exception: {0}".format(exc) ) # use `copy` to preserve the inode of the # original file, and thus preserve hardlinks # to the inode. otherwise, use `move` to # preserve prior behavior, which results in # writing the file to a new inode. if preserve_inode: try: shutil.copy2(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to copy file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: try: shutil.move(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) return temp_file def _starts_till(src, probe, strip_comments=True): ''' Returns True if src and probe at least matches at the beginning till some point. ''' def _strip_comments(txt): ''' Strip possible comments. Usually comments are one or two symbols at the beginning of the line, separated with space ''' buff = txt.split(" ", 1) return len(buff) == 2 and len(buff[0]) < 2 and buff[1] or txt def _to_words(txt): ''' Split by words ''' return txt and [w for w in txt.strip().split(" ") if w.strip()] or txt no_match = -1 equal = 0 if not src or not probe: return no_match src = src.rstrip('\n\r') probe = probe.rstrip('\n\r') if src == probe: return equal src = _to_words(strip_comments and _strip_comments(src) or src) probe = _to_words(strip_comments and _strip_comments(probe) or probe) a_buff, b_buff = len(src) < len(probe) and (src, probe) or (probe, src) b_buff = ' '.join(b_buff) for idx in range(len(a_buff)): prb = ' '.join(a_buff[:-(idx + 1)]) if prb and b_buff.startswith(prb): return idx return no_match def _regex_to_static(src, regex): ''' Expand regular expression to static match. ''' if not src or not regex: return None try: compiled = re.compile(regex, re.DOTALL) src = [line for line in src if compiled.search(line) or line.count(regex)] except Exception as ex: raise CommandExecutionError("{0}: '{1}'".format(_get_error_message(ex), regex)) return src and src or [] def _assert_occurrence(probe, target, amount=1): ''' Raise an exception, if there are different amount of specified occurrences in src. ''' occ = len(probe) if occ > amount: msg = 'more than' elif occ < amount: msg = 'less than' elif not occ: msg = 'no' else: msg = None if msg: raise CommandExecutionError('Found {0} expected occurrences in "{1}" expression'.format(msg, target)) return occ def _set_line_indent(src, line, indent): ''' Indent the line with the source line. ''' if not indent: return line idt = [] for c in src: if c not in ['\t', ' ']: break idt.append(c) return ''.join(idt) + line.lstrip() def _get_eol(line): match = re.search('((?<!\r)\n|\r(?!\n)|\r\n)$', line) return match and match.group() or '' def _set_line_eol(src, line): ''' Add line ending ''' line_ending = _get_eol(src) or os.linesep return line.rstrip() + line_ending def _insert_line_before(idx, body, content, indent): if not idx or (idx and _starts_till(body[idx - 1], content) < 0): cnd = _set_line_indent(body[idx], content, indent) body.insert(idx, cnd) return body def _insert_line_after(idx, body, content, indent): # No duplicates or append, if "after" is the last line next_line = idx + 1 < len(body) and body[idx + 1] or None if next_line is None or _starts_till(next_line, content) < 0: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) return body def line(path, content=None, match=None, mode=None, location=None, before=None, after=None, show_changes=True, backup=False, quiet=False, indent=True): ''' .. versionadded:: 2015.8.0 Edit a line in the configuration file. The ``path`` and ``content`` arguments are required, as well as passing in one of the ``mode`` options. path Filesystem path to the file to be edited. content Content of the line. Allowed to be empty if mode=delete. match Match the target line for an action by a fragment of a string or regular expression. If neither ``before`` nor ``after`` are provided, and ``match`` is also ``None``, match becomes the ``content`` value. mode Defines how to edit a line. One of the following options is required: - ensure If line does not exist, it will be added. This is based on the ``content`` argument. - replace If line already exists, it will be replaced. - delete Delete the line, once found. - insert Insert a line. .. note:: If ``mode=insert`` is used, at least one of the following options must also be defined: ``location``, ``before``, or ``after``. If ``location`` is used, it takes precedence over the other two options. location Defines where to place content in the line. Note this option is only used when ``mode=insert`` is specified. If a location is passed in, it takes precedence over both the ``before`` and ``after`` kwargs. Valid locations are: - start Place the content at the beginning of the file. - end Place the content at the end of the file. before Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. after Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. show_changes Output a unified diff of the old file and the new file. If ``False`` return a boolean if any changes were made. Default is ``True`` .. note:: Using this option will store two copies of the file in-memory (the original version and the edited version) in order to generate the diff. backup Create a backup of the original file with the extension: "Year-Month-Day-Hour-Minutes-Seconds". quiet Do not raise any exceptions. E.g. ignore the fact that the file that is tried to be edited does not exist and nothing really happened. indent Keep indentation with the previous line. This option is not considered when the ``delete`` mode is specified. CLI Example: .. code-block:: bash salt '*' file.line /etc/nsswitch.conf "networks:\tfiles dns" after="hosts:.*?" mode='ensure' .. note:: If an equal sign (``=``) appears in an argument to a Salt command, it is interpreted as a keyword argument in the format of ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.line /path/to/file content="CREATEMAIL_SPOOL=no" match="CREATE_MAIL_SPOOL=yes" mode="replace" ''' path = os.path.realpath(os.path.expanduser(path)) if not os.path.isfile(path): if not quiet: raise CommandExecutionError('File "{0}" does not exists or is not a file.'.format(path)) return False # No changes had happened mode = mode and mode.lower() or mode if mode not in ['insert', 'ensure', 'delete', 'replace']: if mode is None: raise CommandExecutionError('Mode was not defined. How to process the file?') else: raise CommandExecutionError('Unknown mode: "{0}"'.format(mode)) # We've set the content to be empty in the function params but we want to make sure # it gets passed when needed. Feature #37092 empty_content_modes = ['delete'] if mode not in empty_content_modes and content is None: raise CommandExecutionError('Content can only be empty if mode is "{0}"'.format(', '.join(empty_content_modes))) del empty_content_modes # Before/after has privilege. If nothing defined, match is used by content. if before is None and after is None and not match: match = content with salt.utils.files.fopen(path, mode='r') as fp_: body = salt.utils.data.decode_list(fp_.readlines()) body_before = hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() # Add empty line at the end if last line ends with eol. # Allows simpler code if body and _get_eol(body[-1]): body.append('') after = _regex_to_static(body, after) before = _regex_to_static(body, before) match = _regex_to_static(body, match) if os.stat(path).st_size == 0 and mode in ('delete', 'replace'): log.warning('Cannot find text to %s. File \'%s\' is empty.', mode, path) body = [] elif mode == 'delete' and match: body = [line for line in body if line != match[0]] elif mode == 'replace' and match: idx = body.index(match[0]) file_line = body.pop(idx) body.insert(idx, _set_line_indent(file_line, content, indent)) elif mode == 'insert': if not location and not before and not after: raise CommandExecutionError('On insert must be defined either "location" or "before/after" conditions.') if not location: if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') out = [] in_range = False for line in body: if line == after[0]: in_range = True elif line == before[0] and in_range: cnd = _set_line_indent(line, content, indent) out.append(cnd) out.append(line) body = out if before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif after and not before: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: if location == 'start': if body: body.insert(0, _set_line_eol(body[0], content)) else: body.append(content + os.linesep) elif location == 'end': body.append(_set_line_indent(body[-1], content, indent) if body else content) elif mode == 'ensure': if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') is_there = bool([l for l in body if l.count(content)]) if not is_there: idx = body.index(after[0]) if idx < (len(body) - 1) and body[idx + 1] == before[0]: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) else: raise CommandExecutionError('Found more than one line between ' 'boundaries "before" and "after".') elif before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif not before and after: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: raise CommandExecutionError("Wrong conditions? " "Unable to ensure line without knowing " "where to put it before and/or after.") if body: for idx, line in enumerate(body): if not _get_eol(line) and idx+1 < len(body): prev = idx and idx-1 or 1 body[idx] = _set_line_eol(body[prev], line) # We do not need empty line at the end anymore if '' == body[-1]: body.pop() changed = body_before != hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() if backup and changed and __opts__['test'] is False: try: temp_file = _mkstemp_copy(path=path, preserve_inode=True) shutil.move(temp_file, '{0}.{1}'.format(path, time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime()))) except (OSError, IOError) as exc: raise CommandExecutionError("Unable to create the backup file of {0}. Exception: {1}".format(path, exc)) changes_diff = None if changed: if show_changes: with salt.utils.files.fopen(path, 'r') as fp_: path_content = salt.utils.data.decode_list(fp_.read().splitlines(True)) changes_diff = __utils__['stringutils.get_diff'](path_content, body) if __opts__['test'] is False: fh_ = None try: # Make sure we match the file mode from salt.utils.files.fopen if six.PY2 and salt.utils.platform.is_windows(): mode = 'wb' body = salt.utils.data.encode_list(body) else: mode = 'w' body = salt.utils.data.decode_list(body, to_str=True) fh_ = salt.utils.atomicfile.atomic_open(path, mode) fh_.writelines(body) finally: if fh_: fh_.close() return show_changes and changes_diff or changed def replace(path, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, backup='.bak', dry_run=False, search_only=False, show_changes=True, ignore_if_missing=False, preserve_inode=True, backslash_literal=False, ): ''' .. versionadded:: 0.17.0 Replace occurrences of a pattern in a file. If ``show_changes`` is ``True``, then a diff of what changed will be returned, otherwise a ``True`` will be returned when changes are made, and ``False`` when no changes are made. This is a pure Python implementation that wraps Python's :py:func:`~re.sub`. path Filesystem path to the file to be edited. If a symlink is specified, it will be resolved to its target. pattern A regular expression, to be matched using Python's :py:func:`~re.search`. repl The replacement text count : 0 Maximum number of pattern occurrences to be replaced. If count is a positive integer ``n``, only ``n`` occurrences will be replaced, otherwise all occurrences will be replaced. flags (list or int) A list of flags defined in the ``re`` module documentation from the Python standard library. Each list item should be a string that will correlate to the human-friendly flag name. E.g., ``['IGNORECASE', 'MULTILINE']``. Optionally, ``flags`` may be an int, with a value corresponding to the XOR (``|``) of all the desired flags. Defaults to 8 (which supports 'MULTILINE'). bufsize (int or str) How much of the file to buffer into memory at once. The default value ``1`` processes one line at a time. The special value ``file`` may be specified which will read the entire file into memory before processing. append_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True``, and pattern is not found, then the content will be appended to the file. prepend_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True`` and pattern is not found, then the content will be prepended to the file. not_found_content .. versionadded:: 2014.7.0 Content to use for append/prepend if not found. If None (default), uses ``repl``. Useful when ``repl`` uses references to group in pattern. backup : .bak The file extension to use for a backup of the file before editing. Set to ``False`` to skip making a backup. dry_run : False If set to ``True``, no changes will be made to the file, the function will just return the changes that would have been made (or a ``True``/``False`` value if ``show_changes`` is set to ``False``). search_only : False If set to true, this no changes will be performed on the file, and this function will simply return ``True`` if the pattern was matched, and ``False`` if not. show_changes : True If ``True``, return a diff of changes made. Otherwise, return ``True`` if changes were made, and ``False`` if not. .. note:: Using this option will store two copies of the file in memory (the original version and the edited version) in order to generate the diff. This may not normally be a concern, but could impact performance if used with large files. ignore_if_missing : False .. versionadded:: 2015.8.0 If set to ``True``, this function will simply return ``False`` if the file doesn't exist. Otherwise, an error will be thrown. preserve_inode : True .. versionadded:: 2015.8.0 Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). backslash_literal : False .. versionadded:: 2016.11.7 Interpret backslashes as literal backslashes for the repl and not escape characters. This will help when using append/prepend so that the backslashes are not interpreted for the repl on the second run of the state. If an equal sign (``=``) appears in an argument to a Salt command it is interpreted as a keyword argument in the format ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.replace /path/to/file pattern='=' repl=':' salt '*' file.replace /path/to/file pattern="bind-address\\s*=" repl='bind-address:' CLI Examples: .. code-block:: bash salt '*' file.replace /etc/httpd/httpd.conf pattern='LogLevel warn' repl='LogLevel info' salt '*' file.replace /some/file pattern='before' repl='after' flags='[MULTILINE, IGNORECASE]' ''' symlink = False if is_link(path): symlink = True target_path = os.readlink(path) given_path = os.path.expanduser(path) path = os.path.realpath(os.path.expanduser(path)) if not os.path.exists(path): if ignore_if_missing: return False else: raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if search_only and (append_if_not_found or prepend_if_not_found): raise SaltInvocationError( 'search_only cannot be used with append/prepend_if_not_found' ) if append_if_not_found and prepend_if_not_found: raise SaltInvocationError( 'Only one of append and prepend_if_not_found is permitted' ) flags_num = _get_flags(flags) cpattern = re.compile(salt.utils.stringutils.to_bytes(pattern), flags_num) filesize = os.path.getsize(path) if bufsize == 'file': bufsize = filesize # Search the file; track if any changes have been made for the return val has_changes = False orig_file = [] # used for show_changes and change detection new_file = [] # used for show_changes and change detection if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Avoid TypeErrors by forcing repl to be bytearray related to mmap # Replacement text may contains integer: 123 for example repl = salt.utils.stringutils.to_bytes(six.text_type(repl)) if not_found_content: not_found_content = salt.utils.stringutils.to_bytes(not_found_content) found = False temp_file = None content = salt.utils.stringutils.to_unicode(not_found_content) \ if not_found_content and (prepend_if_not_found or append_if_not_found) \ else salt.utils.stringutils.to_unicode(repl) try: # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes r_data = None # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: try: # mmap throws a ValueError if the file is empty. r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) except (ValueError, mmap.error): # size of file in /proc is 0, but contains data r_data = salt.utils.stringutils.to_bytes("".join(r_file)) if search_only: # Just search; bail as early as a match is found if re.search(cpattern, r_data): return True # `with` block handles file closure else: return False else: result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) # found anything? (even if no change) if nrepl > 0: found = True # Identity check the potential change has_changes = True if pattern != repl else has_changes if prepend_if_not_found or append_if_not_found: # Search for content, to avoid pre/appending the # content if it was pre/appended in a previous run. if re.search(salt.utils.stringutils.to_bytes('^{0}($|(?=\r\n))'.format(re.escape(content))), r_data, flags=flags_num): # Content was found, so set found. found = True orig_file = r_data.read(filesize).splitlines(True) \ if isinstance(r_data, mmap.mmap) \ else r_data.splitlines(True) new_file = result.splitlines(True) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() if has_changes and not dry_run: # Write the replacement text in this block. try: # Create a copy to read from and to use as a backup later temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) r_data = None try: # Open the file in write mode with salt.utils.files.fopen(path, mode='w', buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='r', buffering=bufsize) as r_file: r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) try: w_file.write(salt.utils.stringutils.to_str(result)) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if not found and (append_if_not_found or prepend_if_not_found): if not_found_content is None: not_found_content = repl if prepend_if_not_found: new_file.insert(0, not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) else: # append_if_not_found # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(salt.utils.stringutils.to_bytes(os.linesep)): new_file[-1] += salt.utils.stringutils.to_bytes(os.linesep) new_file.append(not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) has_changes = True if not dry_run: try: # Create a copy to read from and for later use as a backup temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line)) finally: fh_.close() if backup and has_changes and not dry_run: # keep the backup only if it was requested # and only if there were any changes backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) if symlink: symlink_backup = '{0}{1}'.format(given_path, backup) target_backup = '{0}{1}'.format(target_path, backup) # Always clobber any existing symlink backup # to match the behaviour of the 'backup' option try: os.symlink(target_backup, symlink_backup) except OSError: os.remove(symlink_backup) os.symlink(target_backup, symlink_backup) except Exception: raise CommandExecutionError( "Unable create backup symlink '{0}'. " "Target was '{1}'. " "Exception: {2}".format(symlink_backup, target_backup, exc) ) elif temp_file: try: os.remove(temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to delete temp file '{0}'. " "Exception: {1}".format(temp_file, exc) ) if not dry_run and not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) differences = __utils__['stringutils.get_diff'](orig_file, new_file) if show_changes: return differences # We may have found a regex line match but don't need to change the line # (for situations where the pattern also matches the repl). Revert the # has_changes flag to False if the final result is unchanged. if not differences: has_changes = False return has_changes def blockreplace(path, marker_start='#-- start managed zone --', marker_end='#-- end managed zone --', content='', append_if_not_found=False, prepend_if_not_found=False, backup='.bak', dry_run=False, show_changes=True, append_newline=False, insert_before_match=None, insert_after_match=None): ''' .. versionadded:: 2014.1.0 Replace content of a text block in a file, delimited by line markers A block of content delimited by comments can help you manage several lines entries without worrying about old entries removal. .. note:: This function will store two copies of the file in-memory (the original version and the edited version) in order to detect changes and only edit the targeted file if necessary. path Filesystem path to the file to be edited marker_start The line content identifying a line as the start of the content block. Note that the whole line containing this marker will be considered, so whitespace or extra content before or after the marker is included in final output marker_end The line content identifying the end of the content block. As of versions 2017.7.5 and 2018.3.1, everything up to the text matching the marker will be replaced, so it's important to ensure that your marker includes the beginning of the text you wish to replace. content The content to be used between the two lines identified by marker_start and marker_stop. append_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be appended to the file. prepend_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be prepended to the file. insert_before_match If markers are not found, this parameter can be set to a regex which will insert the block before the first found occurrence in the file. .. versionadded:: Neon insert_after_match If markers are not found, this parameter can be set to a regex which will insert the block after the first found occurrence in the file. .. versionadded:: Neon backup The file extension to use for a backup of the file if any edit is made. Set to ``False`` to skip making a backup. dry_run : False If ``True``, do not make any edits to the file and simply return the changes that *would* be made. show_changes : True Controls how changes are presented. If ``True``, this function will return a unified diff of the changes made. If False, then it will return a boolean (``True`` if any changes were made, otherwise ``False``). append_newline : False Controls whether or not a newline is appended to the content block. If the value of this argument is ``True`` then a newline will be added to the content block. If it is ``False``, then a newline will *not* be added to the content block. If it is ``None`` then a newline will only be added to the content block if it does not already end in a newline. .. versionadded:: 2016.3.4 .. versionchanged:: 2017.7.5,2018.3.1 New behavior added when value is ``None``. .. versionchanged:: 2019.2.0 The default value of this argument will change to ``None`` to match the behavior of the :py:func:`file.blockreplace state <salt.states.file.blockreplace>` CLI Example: .. code-block:: bash salt '*' file.blockreplace /etc/hosts '#-- start managed zone foobar : DO NOT EDIT --' \\ '#-- end managed zone foobar --' $'10.0.1.1 foo.foobar\\n10.0.1.2 bar.foobar' True ''' exclusive_params = [append_if_not_found, prepend_if_not_found, bool(insert_before_match), bool(insert_after_match)] if sum(exclusive_params) > 1: raise SaltInvocationError( 'Only one of append_if_not_found, prepend_if_not_found,' ' insert_before_match, and insert_after_match is permitted' ) path = os.path.expanduser(path) if not os.path.exists(path): raise SaltInvocationError('File not found: {0}'.format(path)) try: file_encoding = __utils__['files.get_encoding'](path) except CommandExecutionError: file_encoding = None if __utils__['files.is_binary'](path): if not file_encoding: raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if insert_before_match or insert_after_match: if insert_before_match: if not isinstance(insert_before_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_before_match parameter.' ) elif insert_after_match: if not isinstance(insert_after_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_after_match parameter.' ) if append_newline is None and not content.endswith((os.linesep, '\n')): append_newline = True # Split the content into a list of lines, removing newline characters. To # ensure that we handle both Windows and POSIX newlines, first split on # Windows newlines, and then split on POSIX newlines. split_content = [] for win_line in content.split('\r\n'): for content_line in win_line.split('\n'): split_content.append(content_line) line_count = len(split_content) has_changes = False orig_file = [] new_file = [] in_block = False block_found = False linesep = None def _add_content(linesep, lines=None, include_marker_start=True, end_line=None): if lines is None: lines = [] include_marker_start = True if end_line is None: end_line = marker_end end_line = end_line.rstrip('\r\n') + linesep if include_marker_start: lines.append(marker_start + linesep) if split_content: for index, content_line in enumerate(split_content, 1): if index != line_count: lines.append(content_line + linesep) else: # We're on the last line of the content block if append_newline: lines.append(content_line + linesep) lines.append(end_line) else: lines.append(content_line + end_line) else: lines.append(end_line) return lines # We do not use in-place editing to avoid file attrs modifications when # no changes are required and to avoid any file access on a partially # written file. try: fi_file = io.open(path, mode='r', encoding=file_encoding, newline='') for line in fi_file: write_line_to_new_file = True if linesep is None: # Auto-detect line separator if line.endswith('\r\n'): linesep = '\r\n' elif line.endswith('\n'): linesep = '\n' else: # No newline(s) in file, fall back to system's linesep linesep = os.linesep if marker_start in line: # We've entered the content block in_block = True else: if in_block: # We're not going to write the lines from the old file to # the new file until we have exited the block. write_line_to_new_file = False marker_end_pos = line.find(marker_end) if marker_end_pos != -1: # End of block detected in_block = False # We've found and exited the block block_found = True _add_content(linesep, lines=new_file, include_marker_start=False, end_line=line[marker_end_pos:]) # Save the line from the original file orig_file.append(line) if write_line_to_new_file: new_file.append(line) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read from {0}: {1}'.format(path, exc) ) finally: if linesep is None: # If the file was empty, we will not have set linesep yet. Assume # the system's line separator. This is needed for when we # prepend/append later on. linesep = os.linesep try: fi_file.close() except Exception: pass if in_block: # unterminated block => bad, always fail raise CommandExecutionError( 'Unterminated marked block. End of file reached before marker_end.' ) if not block_found: if prepend_if_not_found: # add the markers and content at the beginning of file prepended_content = _add_content(linesep) prepended_content.extend(new_file) new_file = prepended_content block_found = True elif append_if_not_found: # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(linesep): new_file[-1] += linesep # add the markers and content at the end of file _add_content(linesep, lines=new_file) block_found = True elif insert_before_match or insert_after_match: match_regex = insert_before_match or insert_after_match match_idx = [i for i, item in enumerate(orig_file) if re.search(match_regex, item)] if match_idx: match_idx = match_idx[0] for line in _add_content(linesep): if insert_after_match: match_idx += 1 new_file.insert(match_idx, line) if insert_before_match: match_idx += 1 block_found = True if not block_found: raise CommandExecutionError( 'Cannot edit marked block. Markers were not found in file.' ) diff = __utils__['stringutils.get_diff'](orig_file, new_file) has_changes = diff is not '' if has_changes and not dry_run: # changes detected # backup file attrs perms = {} perms['user'] = get_user(path) perms['group'] = get_group(path) perms['mode'] = salt.utils.files.normalize_mode(get_mode(path)) # backup old content if backup is not False: backup_path = '{0}{1}'.format(path, backup) shutil.copy2(path, backup_path) # copy2 does not preserve ownership check_perms(backup_path, None, perms['user'], perms['group'], perms['mode']) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line, encoding=file_encoding)) finally: fh_.close() # this may have overwritten file attrs check_perms(path, None, perms['user'], perms['group'], perms['mode']) if show_changes: return diff return has_changes def search(path, pattern, flags=8, bufsize=1, ignore_if_missing=False, multiline=False ): ''' .. versionadded:: 0.17.0 Search for occurrences of a pattern in a file Except for multiline, params are identical to :py:func:`~salt.modules.file.replace`. multiline If true, inserts 'MULTILINE' into ``flags`` and sets ``bufsize`` to 'file'. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' file.search /etc/crontab 'mymaintenance.sh' ''' if multiline: flags = _add_flags(flags, 'MULTILINE') bufsize = 'file' # This function wraps file.replace on purpose in order to enforce # consistent usage, compatible regex's, expected behavior, *and* bugs. :) # Any enhancements or fixes to one should affect the other. return replace(path, pattern, '', flags=flags, bufsize=bufsize, dry_run=True, search_only=True, show_changes=False, ignore_if_missing=ignore_if_missing) def patch(originalfile, patchfile, options='', dry_run=False): ''' .. versionadded:: 0.10.4 Apply a patch to a file or directory. Equivalent to: .. code-block:: bash patch <options> -i <patchfile> <originalfile> Or, when a directory is patched: .. code-block:: bash patch <options> -i <patchfile> -d <originalfile> -p0 originalfile The full path to the file or directory to be patched patchfile A patch file to apply to ``originalfile`` options Options to pass to patch. CLI Example: .. code-block:: bash salt '*' file.patch /opt/file.txt /tmp/file.txt.patch ''' patchpath = salt.utils.path.which('patch') if not patchpath: raise CommandExecutionError( 'patch executable not found. Is the distribution\'s patch ' 'package installed?' ) cmd = [patchpath] cmd.extend(salt.utils.args.shlex_split(options)) if dry_run: if __grains__['kernel'] in ('FreeBSD', 'OpenBSD'): cmd.append('-C') else: cmd.append('--dry-run') # this argument prevents interactive prompts when the patch fails to apply. # the exit code will still be greater than 0 if that is the case. if '-N' not in cmd and '--forward' not in cmd: cmd.append('--forward') has_rejectfile_option = False for option in cmd: if option == '-r' or option.startswith('-r ') \ or option.startswith('--reject-file'): has_rejectfile_option = True break # by default, patch will write rejected patch files to <filename>.rej. # this option prevents that. if not has_rejectfile_option: cmd.append('--reject-file=-') cmd.extend(['-i', patchfile]) if os.path.isdir(originalfile): cmd.extend(['-d', originalfile]) has_strip_option = False for option in cmd: if option.startswith('-p') or option.startswith('--strip='): has_strip_option = True break if not has_strip_option: cmd.append('--strip=0') else: cmd.append(originalfile) return __salt__['cmd.run_all'](cmd, python_shell=False) def contains(path, text): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the file at ``path`` contains ``text`` CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False stripped_text = six.text_type(text).strip() try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if stripped_text in chunk: return True return False except (IOError, OSError): return False def contains_regex(path, regex, lchar=''): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the given regular expression matches on any line in the text of a given file. If the lchar argument (leading char) is specified, it will strip `lchar` from the left side of each line before trying to match CLI Example: .. code-block:: bash salt '*' file.contains_regex /etc/crontab ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.files.fopen(path, 'r') as target: for line in target: line = salt.utils.stringutils.to_unicode(line) if lchar: line = line.lstrip(lchar) if re.search(regex, line): return True return False except (IOError, OSError): return False def contains_glob(path, glob_expr): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the given glob matches a string in the named file CLI Example: .. code-block:: bash salt '*' file.contains_glob /etc/foobar '*cheese*' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if fnmatch.fnmatch(chunk, glob_expr): return True return False except (IOError, OSError): return False def append(path, *args, **kwargs): ''' .. versionadded:: 0.9.5 Append text to the end of a file path path to file `*args` strings to append to file CLI Example: .. code-block:: bash salt '*' file.append /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.append /etc/motd args='cheese=spam' salt '*' file.append /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) # Largely inspired by Fabric's contrib.files.append() if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] # Make sure we have a newline at the end of the file. Do this in binary # mode so SEEK_END with nonzero offset will work. with salt.utils.files.fopen(path, 'rb+') as ofile: linesep = salt.utils.stringutils.to_bytes(os.linesep) try: ofile.seek(-len(linesep), os.SEEK_END) except IOError as exc: if exc.errno in (errno.EINVAL, errno.ESPIPE): # Empty file, simply append lines at the beginning of the file pass else: raise else: if ofile.read(len(linesep)) != linesep: ofile.seek(0, os.SEEK_END) ofile.write(linesep) # Append lines in text mode with salt.utils.files.fopen(path, 'a') as ofile: for new_line in args: ofile.write( salt.utils.stringutils.to_str( '{0}{1}'.format(new_line, os.linesep) ) ) return 'Wrote {0} lines to "{1}"'.format(len(args), path) def prepend(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Prepend text to the beginning of a file path path to file `*args` strings to prepend to the file CLI Example: .. code-block:: bash salt '*' file.prepend /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.prepend /etc/motd args='cheese=spam' salt '*' file.prepend /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] try: with salt.utils.files.fopen(path) as fhr: contents = [salt.utils.stringutils.to_unicode(line) for line in fhr.readlines()] except IOError: contents = [] preface = [] for line in args: preface.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, 'w') as ofile: contents = preface + contents ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Prepended {0} lines to "{1}"'.format(len(args), path) def write(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Write text to a file, overwriting any existing contents. path path to file `*args` strings to write to the file CLI Example: .. code-block:: bash salt '*' file.write /etc/motd \\ "With all thine offerings thou shalt offer salt." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.write /etc/motd args='cheese=spam' salt '*' file.write /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] contents = [] for line in args: contents.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, "w") as ofile: ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Wrote {0} lines to "{1}"'.format(len(contents), path) def touch(name, atime=None, mtime=None): ''' .. versionadded:: 0.9.5 Just like the ``touch`` command, create a file if it doesn't exist or simply update the atime and mtime if it already does. atime: Access time in Unix epoch time. Set it to 0 to set atime of the file with Unix date of birth. If this parameter isn't set, atime will be set with current time. mtime: Last modification in Unix epoch time. Set it to 0 to set mtime of the file with Unix date of birth. If this parameter isn't set, mtime will be set with current time. CLI Example: .. code-block:: bash salt '*' file.touch /var/log/emptyfile ''' name = os.path.expanduser(name) if atime and atime.isdigit(): atime = int(atime) if mtime and mtime.isdigit(): mtime = int(mtime) try: if not os.path.exists(name): with salt.utils.files.fopen(name, 'a'): pass if atime is None and mtime is None: times = None elif mtime is None and atime is not None: times = (atime, time.time()) elif atime is None and mtime is not None: times = (time.time(), mtime) else: times = (atime, mtime) os.utime(name, times) except TypeError: raise SaltInvocationError('atime and mtime must be integers') except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return os.path.exists(name) def tail(path, lines): ''' .. versionadded:: Neon Read the last n lines from a file path path to file lines number of lines to read CLI Example: .. code-block:: bash salt '*' file.tail /path/to/file 10 ''' path = os.path.expanduser(path) lines_found = [] buffer_size = 4098 if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot tail a binary file: {0}'.format(path)) try: lines = int(lines) except ValueError: raise SaltInvocationError('file.tail: \'lines\' value must be an integer') try: with salt.utils.fopen(path) as tail_fh: blk_cnt = 1 size = os.stat(path).st_size if size > buffer_size: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size), os.linesep) for i in range(lines): while len(data) == 1 and ((blk_cnt * buffer_size) < size): blk_cnt += 1 line = data[0] try: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size) + line, os.linesep) except IOError: tail_fh.seek(0) data = string.split(tail_fh.read(size - (buffer_size * (blk_cnt - 1))) + line, os.linesep) line = data[-1] data.pop() lines_found.append(line) return lines_found[-lines:] except (OSError, IOError): raise CommandExecutionError('Could not tail \'{0}\''.format(path)) def seek_read(path, size, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and read it path path to file seek amount to read at once offset offset to start into the file CLI Example: .. code-block:: bash salt '*' file.seek_read /path/to/file 4096 0 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_RDONLY) try: os.lseek(seek_fh, int(offset), 0) data = os.read(seek_fh, int(size)) finally: os.close(seek_fh) return data def seek_write(path, data, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and write to it path path to file data data to write to file offset position in file to start writing CLI Example: .. code-block:: bash salt '*' file.seek_write /path/to/file 'some data' 4096 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_WRONLY) try: os.lseek(seek_fh, int(offset), 0) ret = os.write(seek_fh, data) os.fsync(seek_fh) finally: os.close(seek_fh) return ret def truncate(path, length): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and delete everything after that point path path to file length offset into file to truncate CLI Example: .. code-block:: bash salt '*' file.truncate /path/to/file 512 ''' path = os.path.expanduser(path) with salt.utils.files.fopen(path, 'rb+') as seek_fh: seek_fh.truncate(int(length)) def link(src, path): ''' .. versionadded:: 2014.1.0 Create a hard link to a file CLI Example: .. code-block:: bash salt '*' file.link /path/to/file /path/to/link ''' src = os.path.expanduser(src) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.link(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def is_link(path): ''' Check if the path is a symbolic link CLI Example: .. code-block:: bash salt '*' file.is_link /path/to/link ''' # This function exists because os.path.islink does not support Windows, # therefore a custom function will need to be called. This function # therefore helps API consistency by providing a single function to call for # both operating systems. return os.path.islink(os.path.expanduser(path)) def symlink(src, path): ''' Create a symbolic link (symlink, soft link) to a file CLI Example: .. code-block:: bash salt '*' file.symlink /path/to/file /path/to/link ''' path = os.path.expanduser(path) try: if os.path.normpath(os.readlink(path)) == os.path.normpath(src): log.debug('link already in correct state: %s -> %s', path, src) return True except OSError: pass if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: os.symlink(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def rename(src, dst): ''' Rename a file or directory CLI Example: .. code-block:: bash salt '*' file.rename /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.rename(src, dst) return True except OSError: raise CommandExecutionError( 'Could not rename \'{0}\' to \'{1}\''.format(src, dst) ) return False def copy(src, dst, recurse=False, remove_existing=False): ''' Copy a file or directory from source to dst In order to copy a directory, the recurse flag is required, and will by default overwrite files in the destination with the same path, and retain all other existing files. (similar to cp -r on unix) remove_existing will remove all files in the target directory, and then copy files from the source. .. note:: The copy function accepts paths that are local to the Salt minion. This function does not support salt://, http://, or the other additional file paths that are supported by :mod:`states.file.managed <salt.states.file.managed>` and :mod:`states.file.recurse <salt.states.file.recurse>`. CLI Example: .. code-block:: bash salt '*' file.copy /path/to/src /path/to/dst salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True remove_existing=True ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') if not os.path.exists(src): raise CommandExecutionError('No such file or directory \'{0}\''.format(src)) if not salt.utils.platform.is_windows(): pre_user = get_user(src) pre_group = get_group(src) pre_mode = salt.utils.files.normalize_mode(get_mode(src)) try: if (os.path.exists(dst) and os.path.isdir(dst)) or os.path.isdir(src): if not recurse: raise SaltInvocationError( "Cannot copy overwriting a directory without recurse flag set to true!") if remove_existing: if os.path.exists(dst): shutil.rmtree(dst) shutil.copytree(src, dst) else: salt.utils.files.recursive_copy(src, dst) else: shutil.copyfile(src, dst) except OSError: raise CommandExecutionError( 'Could not copy \'{0}\' to \'{1}\''.format(src, dst) ) if not salt.utils.platform.is_windows(): check_perms(dst, None, pre_user, pre_group, pre_mode) return True def lstat(path): ''' .. versionadded:: 2014.1.0 Returns the lstat attributes for the given file or dir. Does not support symbolic links. CLI Example: .. code-block:: bash salt '*' file.lstat /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to file must be absolute.') try: lst = os.lstat(path) return dict((key, getattr(lst, key)) for key in ('st_atime', 'st_ctime', 'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid')) except Exception: return {} def access(path, mode): ''' .. versionadded:: 2014.1.0 Test whether the Salt process has the specified access to the file. One of the following modes must be specified: .. code-block::text f: Test the existence of the path r: Test the readability of the path w: Test the writability of the path x: Test whether the path can be executed CLI Example: .. code-block:: bash salt '*' file.access /path/to/file f salt '*' file.access /path/to/file x ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') modes = {'f': os.F_OK, 'r': os.R_OK, 'w': os.W_OK, 'x': os.X_OK} if mode in modes: return os.access(path, modes[mode]) elif mode in six.itervalues(modes): return os.access(path, mode) else: raise SaltInvocationError('Invalid mode specified.') def read(path, binary=False): ''' .. versionadded:: 2017.7.0 Return the content of the file. CLI Example: .. code-block:: bash salt '*' file.read /path/to/file ''' access_mode = 'r' if binary is True: access_mode += 'b' with salt.utils.files.fopen(path, access_mode) as file_obj: return salt.utils.stringutils.to_unicode(file_obj.read()) def readlink(path, canonicalize=False): ''' .. versionadded:: 2014.1.0 Return the path that a symlink points to If canonicalize is set to True, then it return the final target CLI Example: .. code-block:: bash salt '*' file.readlink /path/to/link ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') if not os.path.islink(path): raise SaltInvocationError('A valid link was not specified.') if canonicalize: return os.path.realpath(path) else: return os.readlink(path) def readdir(path): ''' .. versionadded:: 2014.1.0 Return a list containing the contents of a directory CLI Example: .. code-block:: bash salt '*' file.readdir /path/to/dir/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Dir path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') dirents = ['.', '..'] dirents.extend(os.listdir(path)) return dirents def statvfs(path): ''' .. versionadded:: 2014.1.0 Perform a statvfs call against the filesystem that the file resides on CLI Example: .. code-block:: bash salt '*' file.statvfs /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: stv = os.statvfs(path) return dict((key, getattr(stv, key)) for key in ('f_bavail', 'f_bfree', 'f_blocks', 'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag', 'f_frsize', 'f_namemax')) except (OSError, IOError): raise CommandExecutionError('Could not statvfs \'{0}\''.format(path)) return False def stats(path, hash_type=None, follow_symlinks=True): ''' Return a dict containing the stats for a given file CLI Example: .. code-block:: bash salt '*' file.stats /etc/passwd ''' path = os.path.expanduser(path) ret = {} if not os.path.exists(path): try: # Broken symlinks will return False for os.path.exists(), but still # have a uid and gid pstat = os.lstat(path) except OSError: # Not a broken symlink, just a nonexistent path # NOTE: The file.directory state checks the content of the error # message in this exception. Any changes made to the message for this # exception will reflect the file.directory state as well, and will # likely require changes there. raise CommandExecutionError('Path not found: {0}'.format(path)) else: if follow_symlinks: pstat = os.stat(path) else: pstat = os.lstat(path) ret['inode'] = pstat.st_ino ret['uid'] = pstat.st_uid ret['gid'] = pstat.st_gid ret['group'] = gid_to_group(pstat.st_gid) ret['user'] = uid_to_user(pstat.st_uid) ret['atime'] = pstat.st_atime ret['mtime'] = pstat.st_mtime ret['ctime'] = pstat.st_ctime ret['size'] = pstat.st_size ret['mode'] = six.text_type(oct(stat.S_IMODE(pstat.st_mode))) if hash_type: ret['sum'] = get_hash(path, hash_type) ret['type'] = 'file' if stat.S_ISDIR(pstat.st_mode): ret['type'] = 'dir' if stat.S_ISCHR(pstat.st_mode): ret['type'] = 'char' if stat.S_ISBLK(pstat.st_mode): ret['type'] = 'block' if stat.S_ISREG(pstat.st_mode): ret['type'] = 'file' if stat.S_ISLNK(pstat.st_mode): ret['type'] = 'link' if stat.S_ISFIFO(pstat.st_mode): ret['type'] = 'pipe' if stat.S_ISSOCK(pstat.st_mode): ret['type'] = 'socket' ret['target'] = os.path.realpath(path) return ret def rmdir(path): ''' .. versionadded:: 2014.1.0 Remove the specified directory. Fails if a directory is not empty. CLI Example: .. code-block:: bash salt '*' file.rmdir /tmp/foo/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') try: os.rmdir(path) return True except OSError as exc: return exc.strerror def remove(path, **kwargs): ''' Remove the named file. If a directory is supplied, it will be recursively deleted. CLI Example: .. code-block:: bash salt '*' file.remove /tmp/foo ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute: {0}'.format(path)) try: if os.path.isfile(path) or os.path.islink(path): os.remove(path) return True elif os.path.isdir(path): shutil.rmtree(path) return True except (OSError, IOError) as exc: raise CommandExecutionError( 'Could not remove \'{0}\': {1}'.format(path, exc) ) return False def directory_exists(path): ''' Tests to see if path is a valid directory. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.directory_exists /etc ''' return os.path.isdir(os.path.expanduser(path)) def file_exists(path): ''' Tests to see if path is a valid file. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.file_exists /etc/passwd ''' return os.path.isfile(os.path.expanduser(path)) def path_exists_glob(path): ''' Tests to see if path after expansion is a valid path (file or directory). Expansion allows usage of ? * and character ranges []. Tilde expansion is not supported. Returns True/False. .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' file.path_exists_glob /etc/pam*/pass* ''' return True if glob.glob(os.path.expanduser(path)) else False def restorecon(path, recursive=False): ''' Reset the SELinux context on a given path CLI Example: .. code-block:: bash salt '*' file.restorecon /home/user/.ssh/authorized_keys ''' if recursive: cmd = ['restorecon', '-FR', path] else: cmd = ['restorecon', '-F', path] return not __salt__['cmd.retcode'](cmd, python_shell=False) def get_selinux_context(path): ''' Get an SELinux context from a given path CLI Example: .. code-block:: bash salt '*' file.get_selinux_context /etc/hosts ''' out = __salt__['cmd.run'](['ls', '-Z', path], python_shell=False) try: ret = re.search(r'\w+:\w+:\w+:\w+', out).group(0) except AttributeError: ret = ( 'No selinux context information is available for {0}'.format(path) ) return ret def set_selinux_context(path, user=None, role=None, type=None, # pylint: disable=W0622 range=None, # pylint: disable=W0622 persist=False): ''' .. versionchanged:: Neon Added persist option Set a specific SELinux label on a given path CLI Example: .. code-block:: bash salt '*' file.set_selinux_context path <user> <role> <type> <range> salt '*' file.set_selinux_context /etc/yum.repos.d/epel.repo system_u object_r system_conf_t s0 ''' if not any((user, role, type, range)): return False if persist: fcontext_result = __salt__['selinux.fcontext_add_policy'](path, sel_type=type, sel_user=user, sel_level=range) if fcontext_result.get('retcode', None) is not 0: # Problem setting fcontext policy raise CommandExecutionError( 'Problem setting fcontext: {0}'.format(fcontext_result) ) cmd = ['chcon'] if user: cmd.extend(['-u', user]) if role: cmd.extend(['-r', role]) if type: cmd.extend(['-t', type]) if range: cmd.extend(['-l', range]) cmd.append(path) ret = not __salt__['cmd.retcode'](cmd, python_shell=False) if ret: return get_selinux_context(path) else: return ret def source_list(source, source_hash, saltenv): ''' Check the source list and return the source to use CLI Example: .. code-block:: bash salt '*' file.source_list salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' base ''' contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv) if contextkey in __context__: return __context__[contextkey] # get the master file list if isinstance(source, list): mfiles = [(f, saltenv) for f in __salt__['cp.list_master'](saltenv)] mdirs = [(d, saltenv) for d in __salt__['cp.list_master_dirs'](saltenv)] for single in source: if isinstance(single, dict): single = next(iter(single)) path, senv = salt.utils.url.parse(single) if senv: mfiles += [(f, senv) for f in __salt__['cp.list_master'](senv)] mdirs += [(d, senv) for d in __salt__['cp.list_master_dirs'](senv)] ret = None for single in source: if isinstance(single, dict): # check the proto, if it is http or ftp then download the file # to check, if it is salt then check the master list # if it is a local file, check if the file exists if len(single) != 1: continue single_src = next(iter(single)) single_hash = single[single_src] if single[single_src] else source_hash urlparsed_single_src = _urlparse(single_src) # Fix this for Windows if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_single_src.scheme.lower() in string.ascii_lowercase: urlparsed_single_src = _urlparse('file://' + single_src) proto = urlparsed_single_src.scheme if proto == 'salt': path, senv = salt.utils.url.parse(single_src) if not senv: senv = saltenv if (path, saltenv) in mfiles or (path, saltenv) in mdirs: ret = (single_src, single_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single_src, single_hash) break elif proto == 'file' and ( os.path.exists(urlparsed_single_src.netloc) or os.path.exists(urlparsed_single_src.path) or os.path.exists(os.path.join( urlparsed_single_src.netloc, urlparsed_single_src.path))): ret = (single_src, single_hash) break elif single_src.startswith(os.sep) and os.path.exists(single_src): ret = (single_src, single_hash) break elif isinstance(single, six.string_types): path, senv = salt.utils.url.parse(single) if not senv: senv = saltenv if (path, senv) in mfiles or (path, senv) in mdirs: ret = (single, source_hash) break urlparsed_src = _urlparse(single) if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_src.scheme.lower() in string.ascii_lowercase: urlparsed_src = _urlparse('file://' + single) proto = urlparsed_src.scheme if proto == 'file' and ( os.path.exists(urlparsed_src.netloc) or os.path.exists(urlparsed_src.path) or os.path.exists(os.path.join( urlparsed_src.netloc, urlparsed_src.path))): ret = (single, source_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single, source_hash) break elif single.startswith(os.sep) and os.path.exists(single): ret = (single, source_hash) break if ret is None: # None of the list items matched raise CommandExecutionError( 'none of the specified sources were found' ) else: ret = (source, source_hash) __context__[contextkey] = ret return ret def apply_template_on_contents( contents, template, context, defaults, saltenv): ''' Return the contents after applying the templating engine contents template string template template format context Overrides default context variables passed to the template. defaults Default context passed to the template. CLI Example: .. code-block:: bash salt '*' file.apply_template_on_contents \\ contents='This is a {{ template }} string.' \\ template=jinja \\ "context={}" "defaults={'template': 'cool'}" \\ saltenv=base ''' if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) # Apply templating contents = salt.utils.templates.TEMPLATE_REGISTRY[template]( contents, from_str=True, to_str=True, context=context_dict, saltenv=saltenv, grains=__opts__['grains'], pillar=__pillar__, salt=__salt__, opts=__opts__)['data'] if six.PY2: contents = contents.encode('utf-8') elif six.PY3 and isinstance(contents, bytes): # bytes -> str contents = contents.decode('utf-8') else: ret = {} ret['result'] = False ret['comment'] = ('Specified template format {0} is not supported' ).format(template) return ret return contents def get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify=False, **kwargs): ''' Return the managed file data for file.managed name location where the file lives on the server template template format source managed source file source_hash hash of the source file source_hash_name When ``source_hash`` refers to a remote file, this specifies the filename to look for in that file. .. versionadded:: 2016.3.5 user Owner of file group Group owner of file mode Permissions of file attrs Attributes of file .. versionadded:: 2018.3.0 context Variables to add to the template context defaults Default values of for context_dict skip_verify If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' file.get_managed /etc/httpd/conf.d/httpd.conf jinja salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' None root root '755' base None None ''' # Copy the file to the minion and templatize it sfn = '' source_sum = {} def _get_local_file_source_sum(path): ''' DRY helper for getting the source_sum value from a locally cached path. ''' return {'hsum': get_hash(path, form='sha256'), 'hash_type': 'sha256'} # If we have a source defined, let's figure out what the hash is if source: urlparsed_source = _urlparse(source) if urlparsed_source.scheme in salt.utils.files.VALID_PROTOS: parsed_scheme = urlparsed_source.scheme else: parsed_scheme = '' parsed_path = os.path.join( urlparsed_source.netloc, urlparsed_source.path).rstrip(os.sep) unix_local_source = parsed_scheme in ('file', '') if parsed_scheme == '': parsed_path = sfn = source if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg elif parsed_scheme == 'file': sfn = parsed_path if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg if parsed_scheme and parsed_scheme.lower() in string.ascii_lowercase: parsed_path = ':'.join([parsed_scheme, parsed_path]) parsed_scheme = 'file' if parsed_scheme == 'salt': source_sum = __salt__['cp.hash_file'](source, saltenv) if not source_sum: return '', {}, 'Source file {0} not found in saltenv \'{1}\''.format(source, saltenv) elif not source_hash and unix_local_source: source_sum = _get_local_file_source_sum(parsed_path) elif not source_hash and source.startswith(os.sep): # This should happen on Windows source_sum = _get_local_file_source_sum(source) else: if not skip_verify: if source_hash: try: source_sum = get_source_sum(name, source, source_hash, source_hash_name, saltenv) except CommandExecutionError as exc: return '', {}, exc.strerror else: msg = ( 'Unable to verify upstream hash of source file {0}, ' 'please set source_hash or set skip_verify to True' .format(salt.utils.url.redact_http_basic_auth(source)) ) return '', {}, msg if source and (template or parsed_scheme in salt.utils.files.REMOTE_PROTOS): # Check if we have the template or remote file cached cache_refetch = False cached_dest = __salt__['cp.is_cached'](source, saltenv) if cached_dest and (source_hash or skip_verify): htype = source_sum.get('hash_type', 'sha256') cached_sum = get_hash(cached_dest, form=htype) if skip_verify: # prev: if skip_verify or cached_sum == source_sum['hsum']: # but `cached_sum == source_sum['hsum']` is elliptical as prev if sfn = cached_dest source_sum = {'hsum': cached_sum, 'hash_type': htype} elif cached_sum != source_sum.get('hsum', __opts__['hash_type']): cache_refetch = True else: sfn = cached_dest # If we didn't have the template or remote file, or the file has been # updated and the cache has to be refreshed, download the file. if not sfn or cache_refetch: try: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum.get('hsum')) except Exception as exc: # A 404 or other error code may raise an exception, catch it # and return a comment that will fail the calling state. _source = salt.utils.url.redact_http_basic_auth(source) return '', {}, 'Failed to cache {0}: {1}'.format(_source, exc) # If cache failed, sfn will be False, so do a truth check on sfn first # as invoking os.path.exists() on a bool raises a TypeError. if not sfn or not os.path.exists(sfn): _source = salt.utils.url.redact_http_basic_auth(source) return sfn, {}, 'Source file \'{0}\' not found'.format(_source) if sfn == name: raise SaltInvocationError( 'Source file cannot be the same as destination' ) if template: if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, name=name, source=source, user=user, group=group, mode=mode, attrs=attrs, saltenv=saltenv, context=context_dict, salt=__salt__, pillar=__pillar__, grains=__opts__['grains'], opts=__opts__, **kwargs) else: return sfn, {}, ('Specified template format {0} is not supported' ).format(template) if data['result']: sfn = data['data'] hsum = get_hash(sfn, form='sha256') source_sum = {'hash_type': 'sha256', 'hsum': hsum} else: __clean_tmp(sfn) return sfn, {}, data['data'] return sfn, source_sum, '' def extract_hash(hash_fn, hash_type='sha256', file_name='', source='', source_hash_name=None): ''' .. versionchanged:: 2016.3.5 Prior to this version, only the ``file_name`` argument was considered for filename matches in the hash file. This would be problematic for cases in which the user was relying on a remote checksum file that they do not control, and they wished to use a different name for that file on the minion from the filename on the remote server (and in the checksum file). For example, managing ``/tmp/myfile.tar.gz`` when the remote file was at ``https://mydomain.tld/different_name.tar.gz``. The :py:func:`file.managed <salt.states.file.managed>` state now also passes this function the source URI as well as the ``source_hash_name`` (if specified). In cases where ``source_hash_name`` is specified, it takes precedence over both the ``file_name`` and ``source``. When it is not specified, ``file_name`` takes precedence over ``source``. This allows for better capability for matching hashes. .. versionchanged:: 2016.11.0 File name and source URI matches are no longer disregarded when ``source_hash_name`` is specified. They will be used as fallback matches if there is no match to the ``source_hash_name`` value. This routine is called from the :mod:`file.managed <salt.states.file.managed>` state to pull a hash from a remote file. Regular expressions are used line by line on the ``source_hash`` file, to find a potential candidate of the indicated hash type. This avoids many problems of arbitrary file layout rules. It specifically permits pulling hash codes from debian ``*.dsc`` files. If no exact match of a hash and filename are found, then the first hash found (if any) will be returned. If no hashes at all are found, then ``None`` will be returned. For example: .. code-block:: yaml openerp_7.0-latest-1.tar.gz: file.managed: - name: /tmp/openerp_7.0-20121227-075624-1_all.deb - source: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.tar.gz - source_hash: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.dsc CLI Example: .. code-block:: bash salt '*' file.extract_hash /path/to/hash/file sha512 /etc/foo ''' hash_len = HASHES.get(hash_type) if hash_len is None: if hash_type: log.warning( 'file.extract_hash: Unsupported hash_type \'%s\', falling ' 'back to matching any supported hash_type', hash_type ) hash_type = '' hash_len_expr = '{0},{1}'.format(min(HASHES_REVMAP), max(HASHES_REVMAP)) else: hash_len_expr = six.text_type(hash_len) filename_separators = string.whitespace + r'\/' if source_hash_name: if not isinstance(source_hash_name, six.string_types): source_hash_name = six.text_type(source_hash_name) source_hash_name_idx = (len(source_hash_name) + 1) * -1 log.debug( 'file.extract_hash: Extracting %s hash for file matching ' 'source_hash_name \'%s\'', 'any supported' if not hash_type else hash_type, source_hash_name ) if file_name: if not isinstance(file_name, six.string_types): file_name = six.text_type(file_name) file_name_basename = os.path.basename(file_name) file_name_idx = (len(file_name_basename) + 1) * -1 if source: if not isinstance(source, six.string_types): source = six.text_type(source) urlparsed_source = _urlparse(source) source_basename = os.path.basename( urlparsed_source.path or urlparsed_source.netloc ) source_idx = (len(source_basename) + 1) * -1 basename_searches = [x for x in (file_name, source) if x] if basename_searches: log.debug( 'file.extract_hash: %s %s hash for file matching%s: %s', 'If no source_hash_name match found, will extract' if source_hash_name else 'Extracting', 'any supported' if not hash_type else hash_type, '' if len(basename_searches) == 1 else ' either of the following', ', '.join(basename_searches) ) partial = None found = {} with salt.utils.files.fopen(hash_fn, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line.strip()) hash_re = r'(?i)(?<![a-z0-9])([a-f0-9]{' + hash_len_expr + '})(?![a-z0-9])' hash_match = re.search(hash_re, line) matched = None if hash_match: matched_hsum = hash_match.group(1) if matched_hsum is not None: matched_type = HASHES_REVMAP.get(len(matched_hsum)) if matched_type is None: # There was a match, but it's not of the correct length # to match one of the supported hash types. matched = None else: matched = {'hsum': matched_hsum, 'hash_type': matched_type} if matched is None: log.debug( 'file.extract_hash: In line \'%s\', no %shash found', line, '' if not hash_type else hash_type + ' ' ) continue if partial is None: partial = matched def _add_to_matches(found, line, match_type, value, matched): log.debug( 'file.extract_hash: Line \'%s\' matches %s \'%s\'', line, match_type, value ) found.setdefault(match_type, []).append(matched) hash_matched = False if source_hash_name: if line.endswith(source_hash_name): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[source_hash_name_idx] in string.whitespace: _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source_hash_name) + r'\s+', line): _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True if file_name: if line.endswith(file_name_basename): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[file_name_idx] in filename_separators: _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(file_name) + r'\s+', line): _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True if source: if line.endswith(source_basename): # Same as above, we can't just do an rsplit here. try: if line[source_idx] in filename_separators: _add_to_matches(found, line, 'source', source, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source) + r'\s+', line): _add_to_matches(found, line, 'source', source, matched) hash_matched = True if not hash_matched: log.debug( 'file.extract_hash: Line \'%s\' contains %s hash ' '\'%s\', but line did not meet the search criteria', line, matched['hash_type'], matched['hsum'] ) for found_type, found_str in (('source_hash_name', source_hash_name), ('file_name', file_name), ('source', source)): if found_type in found: if len(found[found_type]) > 1: log.debug( 'file.extract_hash: Multiple %s matches for %s: %s', found_type, found_str, ', '.join( ['{0} ({1})'.format(x['hsum'], x['hash_type']) for x in found[found_type]] ) ) ret = found[found_type][0] log.debug( 'file.extract_hash: Returning %s hash \'%s\' as a match of %s', ret['hash_type'], ret['hsum'], found_str ) return ret if partial: log.debug( 'file.extract_hash: Returning the partially identified %s hash ' '\'%s\'', partial['hash_type'], partial['hsum'] ) return partial log.debug('file.extract_hash: No matches, returning None') return None def check_perms(name, ret, user, group, mode, attrs=None, follow_symlinks=False, seuser=None, serole=None, setype=None, serange=None): ''' .. versionchanged:: Neon Added selinux options Check the permissions on files, modify attributes and chown if needed. File attributes are only verified if lsattr(1) is installed. CLI Example: .. code-block:: bash salt '*' file.check_perms /etc/sudoers '{}' root root 400 ai .. versionchanged:: 2014.1.3 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': [], 'result': True} orig_comment = '' else: orig_comment = ret['comment'] ret['comment'] = [] # Check permissions perms = {} cur = stats(name, follow_symlinks=follow_symlinks) perms['luser'] = cur['user'] perms['lgroup'] = cur['group'] perms['lmode'] = salt.utils.files.normalize_mode(cur['mode']) is_dir = os.path.isdir(name) is_link = os.path.islink(name) if attrs is not None \ and not salt.utils.platform.is_windows() \ and not is_dir and not is_link: try: lattrs = lsattr(name) except SaltInvocationError: lattrs = None if lattrs is not None: # List attributes on file perms['lattrs'] = ''.join(lattrs.get(name, '')) # Remove attributes on file so changes can be enforced. if perms['lattrs']: chattr(name, operator='remove', attributes=perms['lattrs']) # user/group changes if needed, then check if it worked if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid(perms['luser']) ) or ( not salt.utils.platform.is_windows() and user != perms['luser'] ): perms['cuser'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid(perms['lgroup']) ) or ( not salt.utils.platform.is_windows() and group != perms['lgroup'] ): perms['cgroup'] = group if 'cuser' in perms or 'cgroup' in perms: if not __opts__['test']: if os.path.islink(name) and not follow_symlinks: chown_func = lchown else: chown_func = chown if user is None: user = perms['luser'] if group is None: group = perms['lgroup'] try: chown_func(name, user, group) # Python os.chown() does reset the suid and sgid, # that's why setting the right mode again is needed here. set_mode(name, mode) except OSError: ret['result'] = False if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid( get_user(name, follow_symlinks=follow_symlinks)) and user != '' ) or ( not salt.utils.platform.is_windows() and user != get_user(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['user'] = user else: ret['result'] = False ret['comment'].append('Failed to change user to {0}' .format(user)) elif 'cuser' in perms and user != '': ret['changes']['user'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid( get_group(name, follow_symlinks=follow_symlinks)) and user != '') or ( not salt.utils.platform.is_windows() and group != get_group(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['group'] = group else: ret['result'] = False ret['comment'].append('Failed to change group to {0}' .format(group)) elif 'cgroup' in perms and user != '': ret['changes']['group'] = group if not salt.utils.platform.is_windows() and not is_dir: # Replace attributes on file if it had been removed if perms.get('lattrs', ''): chattr(name, operator='add', attributes=perms['lattrs']) # Mode changes if needed if mode is not None: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: mode = salt.utils.files.normalize_mode(mode) if mode != perms['lmode']: if __opts__['test'] is True: ret['changes']['mode'] = mode else: set_mode(name, mode) if mode != salt.utils.files.normalize_mode(get_mode(name)): ret['result'] = False ret['comment'].append( 'Failed to change mode to {0}'.format(mode) ) else: ret['changes']['mode'] = mode # Modify attributes of file if needed if attrs is not None and not is_dir: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if diff_attrs[0] is not None or diff_attrs[1] is not None: if __opts__['test'] is True: ret['changes']['attrs'] = attrs else: if diff_attrs[0] is not None: chattr(name, operator="add", attributes=diff_attrs[0]) if diff_attrs[1] is not None: chattr(name, operator="remove", attributes=diff_attrs[1]) cmp_attrs = _cmp_attrs(name, attrs) if cmp_attrs[0] is not None or cmp_attrs[1] is not None: ret['result'] = False ret['comment'].append( 'Failed to change attributes to {0}'.format(attrs) ) else: ret['changes']['attrs'] = attrs # Set selinux attributes if needed if salt.utils.platform.is_linux() and (seuser or serole or setype or serange): selinux_error = False try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError: log.error('Unable to get current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to get selinux attributes' ) selinux_error = True if not selinux_error: requested_seuser = None requested_serole = None requested_setype = None requested_serange = None # Only set new selinux variables if updates are needed if seuser and seuser != current_seuser: requested_seuser = seuser if serole and serole != current_serole: requested_serole = serole if setype and setype != current_setype: requested_setype = setype if serange and serange != current_serange: requested_serange = serange if requested_seuser or requested_serole or requested_setype or requested_serange: # selinux updates needed, prep changes output selinux_change_new = '' selinux_change_orig = '' if requested_seuser: selinux_change_new += "User: {0} ".format(requested_seuser) selinux_change_orig += "User: {0} ".format(current_seuser) if requested_serole: selinux_change_new += "Role: {0} ".format(requested_serole) selinux_change_orig += "Role: {0} ".format(current_serole) if requested_setype: selinux_change_new += "Type: {0} ".format(requested_setype) selinux_change_orig += "Type: {0} ".format(current_setype) if requested_serange: selinux_change_new += "Range: {0} ".format(requested_serange) selinux_change_orig += "Range: {0} ".format(current_serange) if __opts__['test']: ret['comment'] = 'File {0} selinux context to be updated'.format(name) ret['result'] = None ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} else: try: # set_selinux_context requires type to be set on any other change if (requested_seuser or requested_serole or requested_serange) and not requested_setype: requested_setype = current_setype result = set_selinux_context(name, user=requested_seuser, role=requested_serole, type=requested_setype, range=requested_serange, persist=True) log.debug('selinux set result: %s', result) current_seuser, current_serole, current_setype, current_serange = result.split(':') except ValueError: log.error('Unable to set current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to set selinux attributes' ) selinux_error = True if not selinux_error: ret['comment'].append('The file {0} is set to be changed'.format(name)) if requested_seuser: if current_seuser != requested_seuser: ret['comment'].append("Unable to update seuser context") ret['result'] = False if requested_serole: if current_serole != requested_serole: ret['comment'].append("Unable to update serole context") ret['result'] = False if requested_setype: if current_setype != requested_setype: ret['comment'].append("Unable to update setype context") ret['result'] = False if requested_serange: if current_serange != requested_serange: ret['comment'].append("Unable to update serange context") ret['result'] = False ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} # Only combine the comment list into a string # after all comments are added above if isinstance(orig_comment, six.string_types): if orig_comment: ret['comment'].insert(0, orig_comment) ret['comment'] = '; '.join(ret['comment']) # Set result to None at the very end of the function, # after all changes have been recorded above if __opts__['test'] is True and ret['changes']: ret['result'] = None return ret, perms def check_managed( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Check to see what changes need to be made for a file CLI Example: .. code-block:: bash salt '*' file.check_managed /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) if comments: __clean_tmp(sfn) return False, comments changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) # Ignore permission for files written temporary directories # Files in any path will still be set correctly using get_managed() if name.startswith(tempfile.gettempdir()): for key in ['user', 'group', 'mode']: changes.pop(key, None) __clean_tmp(sfn) if changes: log.info(changes) comments = ['The following values are set to be changed:\n'] comments.extend('{0}: {1}\n'.format(key, val) for key, val in six.iteritems(changes)) return None, ''.join(comments) return True, 'The file {0} is in the correct state'.format(name) def check_managed_changes( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, keep_mode=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Return a dictionary of what changes need to be made for a file .. versionchanged:: Neon selinux attributes added CLI Example: .. code-block:: bash salt '*' file.check_managed_changes /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if comments: __clean_tmp(sfn) raise CommandExecutionError(comments) if sfn and source and keep_mode: if _urlparse(source).scheme in ('salt', 'file') \ or source.startswith('/'): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) __clean_tmp(sfn) return changes def check_file_meta( name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents=None, seuser=None, serole=None, setype=None, serange=None): ''' Check for the changes in the file metadata. CLI Example: .. code-block:: bash salt '*' file.check_file_meta /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' base .. note:: Supported hash types include sha512, sha384, sha256, sha224, sha1, and md5. name Path to file destination sfn Template-processed source file contents source URL to file source source_sum File checksum information as a dictionary .. code-block:: yaml {hash_type: md5, hsum: <md5sum>} user Destination file user owner group Destination file group owner mode Destination file permissions mode attrs Destination file attributes .. versionadded:: 2018.3.0 saltenv Salt environment used to resolve source files contents File contents seuser selinux user attribute .. versionadded:: Neon serole selinux role attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon ''' changes = {} if not source_sum: source_sum = dict() try: lstats = stats(name, hash_type=source_sum.get('hash_type', None), follow_symlinks=False) except CommandExecutionError: lstats = {} if not lstats: changes['newfile'] = name return changes if 'hsum' in source_sum: if source_sum['hsum'] != lstats['sum']: if not sfn and source: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum['hsum']) if sfn: try: changes['diff'] = get_diff( name, sfn, template=True, show_filenames=False) except CommandExecutionError as exc: changes['diff'] = exc.strerror else: changes['sum'] = 'Checksum differs' if contents is not None: # Write a tempfile with the static contents tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'w') as tmp_: tmp_.write(salt.utils.stringutils.to_str(contents)) # Compare the static contents with the named file try: differences = get_diff(name, tmp, show_filenames=False) except CommandExecutionError as exc: log.error('Failed to diff files: %s', exc) differences = exc.strerror __clean_tmp(tmp) if differences: if __salt__['config.option']('obfuscate_templates'): changes['diff'] = '<Obfuscated Template>' else: changes['diff'] = differences if not salt.utils.platform.is_windows(): # Check owner if (user is not None and user != lstats['user'] and user != lstats['uid']): changes['user'] = user # Check group if (group is not None and group != lstats['group'] and group != lstats['gid']): changes['group'] = group # Normalize the file mode smode = salt.utils.files.normalize_mode(lstats['mode']) mode = salt.utils.files.normalize_mode(mode) if mode is not None and mode != smode: changes['mode'] = mode if attrs: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if attrs is not None \ and (diff_attrs[0] is not None or diff_attrs[1] is not None): changes['attrs'] = attrs # Check selinux if seuser or serole or setype or serange: try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError as exc: log.error('Unable to get current selinux attributes') changes['selinux'] = exc.strerror if seuser and seuser != current_seuser: changes['selinux'] = {"user": seuser} if serole and serole != current_serole: changes['selinux'] = {"role": serole} if setype and setype != current_setype: changes['selinux'] = {"type": setype} if serange and serange != current_serange: changes['selinux'] = {"range": serange} return changes def get_diff(file1, file2, saltenv='base', show_filenames=True, show_changes=True, template=False, source_hash_file1=None, source_hash_file2=None): ''' Return unified diff of two files file1 The first file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, thuis had to be a file local to the minion. file2 The second file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, this had to be a file on the salt fileserver (i.e. ``salt://somefile.txt``) show_filenames : True Set to ``False`` to hide the filenames in the top two lines of the diff. show_changes : True If set to ``False``, and there are differences, then instead of a diff a simple message stating that show_changes is set to ``False`` will be returned. template : False Set to ``True`` if two templates are being compared. This is not useful except for within states, with the ``obfuscate_templates`` option set to ``True``. .. versionadded:: 2018.3.0 source_hash_file1 If ``file1`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 source_hash_file2 If ``file2`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 CLI Examples: .. code-block:: bash salt '*' file.get_diff /home/fred/.vimrc salt://users/fred/.vimrc salt '*' file.get_diff /tmp/foo.txt /tmp/bar.txt ''' files = (file1, file2) source_hashes = (source_hash_file1, source_hash_file2) paths = [] errors = [] for filename, source_hash in zip(files, source_hashes): try: # Local file paths will just return the same path back when passed # to cp.cache_file. cached_path = __salt__['cp.cache_file'](filename, saltenv, source_hash=source_hash) if cached_path is False: errors.append( 'File {0} not found'.format( salt.utils.stringutils.to_unicode(filename) ) ) continue paths.append(cached_path) except MinionError as exc: errors.append(salt.utils.stringutils.to_unicode(exc.__str__())) continue if errors: raise CommandExecutionError( 'Failed to cache one or more files', info=errors ) args = [] for filename in paths: try: with salt.utils.files.fopen(filename, 'rb') as fp_: args.append(fp_.readlines()) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read {0}: {1}'.format( salt.utils.stringutils.to_unicode(filename), exc.strerror ) ) if args[0] != args[1]: if template and __salt__['config.option']('obfuscate_templates'): ret = '<Obfuscated Template>' elif not show_changes: ret = '<show_changes=False>' else: bdiff = _binary_replace(*paths) # pylint: disable=no-value-for-parameter if bdiff: ret = bdiff else: if show_filenames: args.extend(paths) ret = __utils__['stringutils.get_diff'](*args) return ret return '' def manage_file(name, sfn, ret, source, source_sum, user, group, mode, attrs, saltenv, backup, makedirs=False, template=None, # pylint: disable=W0613 show_changes=True, contents=None, dir_mode=None, follow_symlinks=True, skip_verify=False, keep_mode=False, encoding=None, encoding_errors='strict', seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Checks the destination against what was retrieved with get_managed and makes the appropriate modifications (if necessary). name location to place the file sfn location of cached file on the minion This is the path to the file stored on the minion. This file is placed on the minion using cp.cache_file. If the hash sum of that file matches the source_sum, we do not transfer the file to the minion again. This file is then grabbed and if it has template set, it renders the file to be placed into the correct place on the system using salt.files.utils.copyfile() ret The initial state return data structure. Pass in ``None`` to use the default structure. source file reference on the master source_sum sum hash for source user user owner group group owner backup backup_mode attrs attributes to be set on file: '' means remove all of them .. versionadded:: 2018.3.0 makedirs make directories if they do not exist template format of templating show_changes Include diff in state return contents: contents to be placed in the file dir_mode mode for directories created with makedirs skip_verify : False If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 keep_mode : False If ``True``, and the ``source`` is a file from the Salt fileserver (or a local file on the minion), the mode of the destination file will be set to the mode of the source file. .. note:: keep_mode does not work with salt-ssh. As a consequence of how the files are transferred to the minion, and the inability to connect back to the master with salt-ssh, salt is unable to stat the file as it exists on the fileserver and thus cannot mirror the mode on the salt-ssh minion encoding If specified, then the specified encoding will be used. Otherwise, the file will be encoded using the system locale (usually UTF-8). See https://docs.python.org/3/library/codecs.html#standard-encodings for the list of available encodings. .. versionadded:: 2017.7.0 encoding_errors : 'strict' Default is ```'strict'```. See https://docs.python.org/2/library/codecs.html#codec-base-classes for the error handling schemes. .. versionadded:: 2017.7.0 seuser selinux user attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon CLI Example: .. code-block:: bash salt '*' file.manage_file /etc/httpd/conf.d/httpd.conf '' '{}' salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' '' base '' .. versionchanged:: 2014.7.0 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if source: if not sfn: # File is not present, cache it sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) htype = source_sum.get('hash_type', __opts__['hash_type']) # Recalculate source sum now that file has been cached source_sum = { 'hash_type': htype, 'hsum': get_hash(sfn, form=htype) } if keep_mode: if _urlparse(source).scheme in ('salt', 'file', ''): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) # Check changes if the target file exists if os.path.isfile(name) or os.path.islink(name): if os.path.islink(name) and follow_symlinks: real_name = os.path.realpath(name) else: real_name = name # Only test the checksums on files with managed contents if source and not (not follow_symlinks and os.path.islink(real_name)): name_sum = get_hash(real_name, source_sum.get('hash_type', __opts__['hash_type'])) else: name_sum = None # Check if file needs to be replaced if source and (name_sum is None or source_sum.get('hsum', __opts__['hash_type']) != name_sum): if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server or local # source, and we are not skipping checksum verification, then # verify that it matches the specified checksum. if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3}). If the \'source_hash\' value ' 'refers to a remote file with multiple possible ' 'matches, then it may be necessary to set ' '\'source_hash_name\'.'.format( source_sum['hash_type'], source, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # Print a diff equivalent to diff -u old new if __salt__['config.option']('obfuscate_templates'): ret['changes']['diff'] = '<Obfuscated Template>' elif not show_changes: ret['changes']['diff'] = '<show_changes=False>' else: try: ret['changes']['diff'] = get_diff( real_name, sfn, show_filenames=False) except CommandExecutionError as exc: ret['changes']['diff'] = exc.strerror # Pre requisites are met, and the file needs to be replaced, do it try: salt.utils.files.copyfile(sfn, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) try: differences = get_diff( real_name, tmp, show_filenames=False, show_changes=show_changes, template=True) except CommandExecutionError as exc: ret.setdefault('warnings', []).append( 'Failed to detect changes to file: {0}'.format(exc.strerror) ) differences = '' if differences: ret['changes']['diff'] = differences # Pre requisites are met, the file needs to be replaced, do it try: salt.utils.files.copyfile(tmp, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(tmp) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) __clean_tmp(tmp) # Check for changing symlink to regular file here if os.path.islink(name) and not follow_symlinks: if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret try: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) ret['changes']['diff'] = \ 'Replace symbolic link with regular file' if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, follow_symlinks, seuser=seuser, serole=serole, setype=setype, serange=serange) if ret['changes']: ret['comment'] = 'File {0} updated'.format( salt.utils.data.decode(name) ) elif not ret['changes'] and ret['result']: ret['comment'] = 'File {0} is in the correct state'.format( salt.utils.data.decode(name) ) if sfn: __clean_tmp(sfn) return ret else: # target file does not exist contain_dir = os.path.dirname(name) def _set_mode_and_make_dirs(name, dir_mode, mode, user, group): # check for existence of windows drive letter if salt.utils.platform.is_windows(): drive, _ = os.path.splitdrive(name) if drive and not os.path.exists(drive): __clean_tmp(sfn) return _error(ret, '{0} drive not present'.format(drive)) if dir_mode is None and mode is not None: # Add execute bit to each nonzero digit in the mode, if # dir_mode was not specified. Otherwise, any # directories created with makedirs_() below can't be # listed via a shell. mode_list = [x for x in six.text_type(mode)][-3:] for idx in range(len(mode_list)): if mode_list[idx] != '0': mode_list[idx] = six.text_type(int(mode_list[idx]) | 1) dir_mode = ''.join(mode_list) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 makedirs_( path=name, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: makedirs_(name, user=user, group=group, mode=dir_mode) if source: # Apply the new file if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # It is a new file, set the diff accordingly ret['changes']['diff'] = 'New file' if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') else: # source != True if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') # Create the file, user rw-only if mode will be set to prevent # a small security race problem before the permissions are set with salt.utils.files.set_umask(0o077 if mode else None): # Create a new file when test is False and source is None if contents is None: if not __opts__['test']: if touch(name): ret['changes']['new'] = 'file {0} created'.format(name) ret['comment'] = 'Empty file' else: return _error( ret, 'Empty file {0} not created'.format(name) ) else: if not __opts__['test']: if touch(name): ret['changes']['diff'] = 'New file' else: return _error( ret, 'File {0} not created'.format(name) ) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) # Copy into place salt.utils.files.copyfile(tmp, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(tmp) # Now copy the file contents if there is a source file elif sfn: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(sfn) # This is a new file, if no mode specified, use the umask to figure # out what mode to use for the new file. if mode is None and not salt.utils.platform.is_windows(): # Get current umask mask = salt.utils.files.get_umask() # Calculate the mode value that results from the umask mode = oct((0o777 ^ mask) & 0o666) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, seuser=seuser, serole=serole, setype=setype, serange=serange) if not ret['comment']: ret['comment'] = 'File ' + name + ' updated' if __opts__['test']: ret['comment'] = 'File ' + name + ' not updated' elif not ret['changes'] and ret['result']: ret['comment'] = 'File ' + name + ' is in the correct state' if sfn: __clean_tmp(sfn) return ret def mkdir(dir_path, user=None, group=None, mode=None): ''' Ensure that a directory is available. CLI Example: .. code-block:: bash salt '*' file.mkdir /opt/jetty/context ''' dir_path = os.path.expanduser(dir_path) directory = os.path.normpath(dir_path) if not os.path.isdir(directory): # If a caller such as managed() is invoked with makedirs=True, make # sure that any created dirs are created with the same user and group # to follow the principal of least surprise method. makedirs_perms(directory, user, group, mode) return True def makedirs_(path, user=None, group=None, mode=None): ''' Ensure that the directory containing this path is available. .. note:: The path must end with a trailing slash otherwise the directory/directories will be created up to the parent directory. For example if path is ``/opt/code``, then it would be treated as ``/opt/`` but if the path ends with a trailing slash like ``/opt/code/``, then it would be treated as ``/opt/code/``. CLI Example: .. code-block:: bash salt '*' file.makedirs /opt/code/ ''' path = os.path.expanduser(path) if mode: mode = salt.utils.files.normalize_mode(mode) # walk up the directory structure until we find the first existing # directory dirname = os.path.normpath(os.path.dirname(path)) if os.path.isdir(dirname): # There's nothing for us to do msg = 'Directory \'{0}\' already exists'.format(dirname) log.debug(msg) return msg if os.path.exists(dirname): msg = 'The path \'{0}\' already exists and is not a directory'.format( dirname ) log.debug(msg) return msg directories_to_create = [] while True: if os.path.isdir(dirname): break directories_to_create.append(dirname) current_dirname = dirname dirname = os.path.dirname(dirname) if current_dirname == dirname: raise SaltInvocationError( 'Recursive creation for path \'{0}\' would result in an ' 'infinite loop. Please use an absolute path.'.format(dirname) ) # create parent directories from the topmost to the most deeply nested one directories_to_create.reverse() for directory_to_create in directories_to_create: # all directories have the user, group and mode set!! log.debug('Creating directory: %s', directory_to_create) mkdir(directory_to_create, user=user, group=group, mode=mode) def makedirs_perms(name, user=None, group=None, mode='0755'): ''' Taken and modified from os.makedirs to set user, group and mode for each directory created. CLI Example: .. code-block:: bash salt '*' file.makedirs_perms /opt/code ''' name = os.path.expanduser(name) path = os.path head, tail = path.split(name) if not tail: head, tail = path.split(head) if head and tail and not path.exists(head): try: makedirs_perms(head, user, group, mode) except OSError as exc: # be happy if someone already created the path if exc.errno != errno.EEXIST: raise if tail == os.curdir: # xxx/newdir/. exists if xxx/newdir exists return os.mkdir(name) check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) def get_devmm(name): ''' Get major/minor info from a device CLI Example: .. code-block:: bash salt '*' file.get_devmm /dev/chr ''' name = os.path.expanduser(name) if is_chrdev(name) or is_blkdev(name): stat_structure = os.stat(name) return ( os.major(stat_structure.st_rdev), os.minor(stat_structure.st_rdev)) else: return (0, 0) def is_chrdev(name): ''' Check if a file exists and is a character device. CLI Example: .. code-block:: bash salt '*' file.is_chrdev /dev/chr ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the character device does not exist in the first place return False else: raise return stat.S_ISCHR(stat_structure.st_mode) def mknod_chrdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a character device. CLI Example: .. code-block:: bash salt '*' file.mknod_chrdev /dev/chr 180 31 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating character device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFCHR, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created character device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_blkdev(name): ''' Check if a file exists and is a block device. CLI Example: .. code-block:: bash salt '*' file.is_blkdev /dev/blk ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the block device does not exist in the first place return False else: raise return stat.S_ISBLK(stat_structure.st_mode) def mknod_blkdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a block device. CLI Example: .. code-block:: bash salt '*' file.mknod_blkdev /dev/blk 8 999 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating block device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFBLK, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created block device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_fifo(name): ''' Check if a file exists and is a FIFO. CLI Example: .. code-block:: bash salt '*' file.is_fifo /dev/fifo ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the fifo does not exist in the first place return False else: raise return stat.S_ISFIFO(stat_structure.st_mode) def mknod_fifo(name, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a FIFO pipe. CLI Example: .. code-block:: bash salt '*' file.mknod_fifo /dev/fifo ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating FIFO name: %s', name) try: if __opts__['test']: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = None else: if os.mkfifo(name, int(six.text_type(mode).lstrip('0Oo'), 8)) is None: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created fifo check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def mknod(name, ntype, major=0, minor=0, user=None, group=None, mode='0600'): ''' .. versionadded:: 0.17.0 Create a block device, character device, or fifo pipe. Identical to the gnu mknod. CLI Examples: .. code-block:: bash salt '*' file.mknod /dev/chr c 180 31 salt '*' file.mknod /dev/blk b 8 999 salt '*' file.nknod /dev/fifo p ''' ret = False makedirs_(name, user, group) if ntype == 'c': ret = mknod_chrdev(name, major, minor, user, group, mode) elif ntype == 'b': ret = mknod_blkdev(name, major, minor, user, group, mode) elif ntype == 'p': ret = mknod_fifo(name, user, group, mode) else: raise SaltInvocationError( 'Node type unavailable: \'{0}\'. Available node types are ' 'character (\'c\'), block (\'b\'), and pipe (\'p\').'.format(ntype) ) return ret def list_backups(path, limit=None): ''' .. versionadded:: 0.17.0 Lists the previous versions of a file backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups /foo/bar/baz.txt ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows src_dir = parent_dir.replace(':', '_') else: src_dir = parent_dir[1:] # Figure out full path of location of backup file in minion cache bkdir = os.path.join(bkroot, src_dir) if not os.path.isdir(bkdir): return {} files = {} for fname in [x for x in os.listdir(bkdir) if os.path.isfile(os.path.join(bkdir, x))]: if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows strpfmt = '{0}_%a_%b_%d_%H-%M-%S_%f_%Y'.format(basename) else: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(fname, strpfmt) except ValueError: # File didn't match the strp format string, so it's not a backup # for this file. Move on to the next one. continue if salt.utils.platform.is_windows(): str_format = '%a %b %d %Y %H-%M-%S.%f' else: str_format = '%a %b %d %Y %H:%M:%S.%f' files.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime(str_format) location = os.path.join(bkdir, fname) files[timestamp]['Size'] = os.stat(location).st_size files[timestamp]['Location'] = location return dict(list(zip( list(range(len(files))), [files[x] for x in sorted(files, reverse=True)[:limit]] ))) list_backup = salt.utils.functools.alias_function(list_backups, 'list_backup') def list_backups_dir(path, limit=None): ''' Lists the previous versions of a directory backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The directory on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups_dir /foo/bar/baz/ ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups_dir: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) # Figure out full path of location of backup folder in minion cache bkdir = os.path.join(bkroot, parent_dir[1:]) if not os.path.isdir(bkdir): return {} files = {} f = dict([(i, len(list(n))) for i, n in itertools.groupby([x.split("_")[0] for x in sorted(os.listdir(bkdir))])]) ff = os.listdir(bkdir) for i, n in six.iteritems(f): ssfile = {} for x in sorted(ff): basename = x.split('_')[0] if i == basename: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(x, strpfmt) except ValueError: # Folder didn't match the strp format string, so it's not a backup # for this folder. Move on to the next one. continue ssfile.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime('%a %b %d %Y %H:%M:%S.%f') location = os.path.join(bkdir, x) ssfile[timestamp]['Size'] = os.stat(location).st_size ssfile[timestamp]['Location'] = location sfiles = dict(list(zip(list(range(n)), [ssfile[x] for x in sorted(ssfile, reverse=True)[:limit]]))) sefiles = {i: sfiles} files.update(sefiles) return files def restore_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Restore a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to restore, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.restore_backup /foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) # Note: This only supports minion backups, so this function will need to be # modified if/when master backups are implemented. ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret salt.utils.files.backup_minion(path, _get_bkroot()) try: shutil.copyfile(backup['Location'], path) except IOError as exc: ret['comment'] = \ 'Unable to restore {0} to {1}: ' \ '{2}'.format(backup['Location'], path, exc) return ret else: ret['result'] = True ret['comment'] = 'Successfully restored {0} to ' \ '{1}'.format(backup['Location'], path) # Try to set proper ownership if not salt.utils.platform.is_windows(): try: fstat = os.stat(path) except (OSError, IOError): ret['comment'] += ', but was unable to set ownership' else: os.chown(path, fstat.st_uid, fstat.st_gid) return ret def delete_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Delete a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to delete, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.delete_backup /var/cache/salt/minion/file_backup/home/foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret try: os.remove(backup['Location']) except IOError as exc: ret['comment'] = 'Unable to remove {0}: {1}'.format(backup['Location'], exc) else: ret['result'] = True ret['comment'] = 'Successfully removed {0}'.format(backup['Location']) return ret remove_backup = salt.utils.functools.alias_function(delete_backup, 'remove_backup') def grep(path, pattern, *opts): ''' Grep for a string in the specified file .. note:: This function's return value is slated for refinement in future versions of Salt path Path to the file to be searched .. note:: Globbing is supported (i.e. ``/var/log/foo/*.log``, but if globbing is being used then the path should be quoted to keep the shell from attempting to expand the glob expression. pattern Pattern to match. For example: ``test``, or ``a[0-5]`` opts Additional command-line flags to pass to the grep command. For example: ``-v``, or ``-i -B2`` .. note:: The options should come after a double-dash (as shown in the examples below) to keep Salt's own argument parser from interpreting them. CLI Example: .. code-block:: bash salt '*' file.grep /etc/passwd nobody salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i -B2 salt '*' file.grep "/etc/sysconfig/network-scripts/*" ipaddr -- -i -l ''' path = os.path.expanduser(path) # Backup the path in case the glob returns nothing _path = path path = glob.glob(path) # If the list is empty no files exist # so we revert back to the original path # so the result is an error. if not path: path = _path split_opts = [] for opt in opts: try: split = salt.utils.args.shlex_split(opt) except AttributeError: split = salt.utils.args.shlex_split(six.text_type(opt)) if len(split) > 1: raise SaltInvocationError( 'Passing multiple command line arguments in a single string ' 'is not supported, please pass the following arguments ' 'separately: {0}'.format(opt) ) split_opts.extend(split) if isinstance(path, list): cmd = ['grep'] + split_opts + [pattern] + path else: cmd = ['grep'] + split_opts + [pattern, path] try: ret = __salt__['cmd.run_all'](cmd, python_shell=False) except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return ret def open_files(by_pid=False): ''' Return a list of all physical open files on the system. CLI Examples: .. code-block:: bash salt '*' file.open_files salt '*' file.open_files by_pid=True ''' # First we collect valid PIDs pids = {} procfs = os.listdir('/proc/') for pfile in procfs: try: pids[int(pfile)] = [] except ValueError: # Not a valid PID, move on pass # Then we look at the open files for each PID files = {} for pid in pids: ppath = '/proc/{0}'.format(pid) try: tids = os.listdir('{0}/task'.format(ppath)) except OSError: continue # Collect the names of all of the file descriptors fd_ = [] #try: # fd_.append(os.path.realpath('{0}/task/{1}exe'.format(ppath, tid))) #except Exception: # pass for fpath in os.listdir('{0}/fd'.format(ppath)): fd_.append('{0}/fd/{1}'.format(ppath, fpath)) for tid in tids: try: fd_.append( os.path.realpath('{0}/task/{1}/exe'.format(ppath, tid)) ) except OSError: continue for tpath in os.listdir('{0}/task/{1}/fd'.format(ppath, tid)): fd_.append('{0}/task/{1}/fd/{2}'.format(ppath, tid, tpath)) fd_ = sorted(set(fd_)) # Loop through file descriptors and return useful data for each file for fdpath in fd_: # Sometimes PIDs and TIDs disappear before we can query them try: name = os.path.realpath(fdpath) # Running stat on the file cuts out all of the sockets and # deleted files from the list os.stat(name) except OSError: continue if name not in files: files[name] = [pid] else: # We still want to know which PIDs are using each file files[name].append(pid) files[name] = sorted(set(files[name])) pids[pid].append(name) pids[pid] = sorted(set(pids[pid])) if by_pid: return pids return files def pardir(): ''' Return the relative parent directory path symbol for underlying OS .. versionadded:: 2014.7.0 This can be useful when constructing Salt Formulas. .. code-block:: jinja {% set pardir = salt['file.pardir']() %} {% set final_path = salt['file.join']('subdir', pardir, 'confdir') %} CLI Example: .. code-block:: bash salt '*' file.pardir ''' return os.path.pardir def normpath(path): ''' Returns Normalize path, eliminating double slashes, etc. .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.normpath'](tpldir + '/../vars.jinja') import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.normpath 'a/b/c/..' ''' return os.path.normpath(path) def basename(path): ''' Returns the final component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- set filename = salt['file.basename'](source_file) %} CLI Example: .. code-block:: bash salt '*' file.basename 'test/test.config' ''' return os.path.basename(path) def dirname(path): ''' Returns the directory component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.dirname'](tpldir) + '/vars.jinja' import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.dirname 'test/path/filename.config' ''' return os.path.dirname(path) def join(*args): ''' Return a normalized file system path for the underlying OS .. versionadded:: 2014.7.0 This can be useful at the CLI but is frequently useful when scripting combining path variables: .. code-block:: jinja {% set www_root = '/var' %} {% set app_dir = 'myapp' %} myapp_config: file: - managed - name: {{ salt['file.join'](www_root, app_dir, 'config.yaml') }} CLI Example: .. code-block:: bash salt '*' file.join '/' 'usr' 'local' 'bin' ''' return os.path.join(*args) def move(src, dst): ''' Move a file or directory CLI Example: .. code-block:: bash salt '*' file.move /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('Source path must be absolute.') if not os.path.isabs(dst): raise SaltInvocationError('Destination path must be absolute.') ret = { 'result': True, 'comment': "'{0}' moved to '{1}'".format(src, dst), } try: shutil.move(src, dst) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move '{0}' to '{1}': {2}".format(src, dst, exc) ) return ret def diskusage(path): ''' Recursively calculate disk usage of path and return it in bytes CLI Example: .. code-block:: bash salt '*' file.diskusage /path/to/check ''' total_size = 0 seen = set() if os.path.isfile(path): stat_structure = os.stat(path) ret = stat_structure.st_size return ret for dirpath, dirnames, filenames in salt.utils.path.os_walk(path): for f in filenames: fp = os.path.join(dirpath, f) try: stat_structure = os.stat(fp) except OSError: continue if stat_structure.st_ino in seen: continue seen.add(stat_structure.st_ino) total_size += stat_structure.st_size ret = total_size return ret
saltstack/salt
salt/modules/file.py
get_mode
python
def get_mode(path, follow_symlinks=True): ''' Return the mode of a file path file or directory of which to get the mode follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_mode /etc/passwd .. versionchanged:: 2014.1.0 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('mode', '')
Return the mode of a file path file or directory of which to get the mode follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_mode /etc/passwd .. versionchanged:: 2014.1.0 ``follow_symlinks`` option added
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L347-L366
[ "def stats(path, hash_type=None, follow_symlinks=True):\n '''\n Return a dict containing the stats for a given file\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' file.stats /etc/passwd\n '''\n path = os.path.expanduser(path)\n\n ret = {}\n if not os.path.exists(path):\n try:\n # Broken symlinks will return False for os.path.exists(), but still\n # have a uid and gid\n pstat = os.lstat(path)\n except OSError:\n # Not a broken symlink, just a nonexistent path\n # NOTE: The file.directory state checks the content of the error\n # message in this exception. Any changes made to the message for this\n # exception will reflect the file.directory state as well, and will\n # likely require changes there.\n raise CommandExecutionError('Path not found: {0}'.format(path))\n else:\n if follow_symlinks:\n pstat = os.stat(path)\n else:\n pstat = os.lstat(path)\n ret['inode'] = pstat.st_ino\n ret['uid'] = pstat.st_uid\n ret['gid'] = pstat.st_gid\n ret['group'] = gid_to_group(pstat.st_gid)\n ret['user'] = uid_to_user(pstat.st_uid)\n ret['atime'] = pstat.st_atime\n ret['mtime'] = pstat.st_mtime\n ret['ctime'] = pstat.st_ctime\n ret['size'] = pstat.st_size\n ret['mode'] = six.text_type(oct(stat.S_IMODE(pstat.st_mode)))\n if hash_type:\n ret['sum'] = get_hash(path, hash_type)\n ret['type'] = 'file'\n if stat.S_ISDIR(pstat.st_mode):\n ret['type'] = 'dir'\n if stat.S_ISCHR(pstat.st_mode):\n ret['type'] = 'char'\n if stat.S_ISBLK(pstat.st_mode):\n ret['type'] = 'block'\n if stat.S_ISREG(pstat.st_mode):\n ret['type'] = 'file'\n if stat.S_ISLNK(pstat.st_mode):\n ret['type'] = 'link'\n if stat.S_ISFIFO(pstat.st_mode):\n ret['type'] = 'pipe'\n if stat.S_ISSOCK(pstat.st_mode):\n ret['type'] = 'socket'\n ret['target'] = os.path.realpath(path)\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage information about regular files, directories, and special files on the minion, set/read user, group, mode, and data ''' # TODO: We should add the capability to do u+r type operations here # some time in the future from __future__ import absolute_import, print_function, unicode_literals # Import python libs import datetime import errno import fnmatch import io import itertools import logging import operator import os import re import shutil import stat import string import sys import tempfile import time import glob import hashlib import mmap from collections import Iterable, Mapping from functools import reduce # pylint: disable=redefined-builtin # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range, zip from salt.ext.six.moves.urllib.parse import urlparse as _urlparse # pylint: enable=import-error,no-name-in-module,redefined-builtin try: import grp import pwd except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.atomicfile import salt.utils.data import salt.utils.dictupdate import salt.utils.filebuffer import salt.utils.files import salt.utils.find import salt.utils.functools import salt.utils.hashutils import salt.utils.itertools import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.templates import salt.utils.url import salt.utils.user from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError, get_error_message as _get_error_message from salt.utils.files import HASHES, HASHES_REVMAP log = logging.getLogger(__name__) __func_alias__ = { 'makedirs_': 'makedirs' } def __virtual__(): ''' Only work on POSIX-like systems ''' # win_file takes care of windows if salt.utils.platform.is_windows(): return ( False, 'The file execution module cannot be loaded: only available on ' 'non-Windows systems - use win_file instead.' ) return True def __clean_tmp(sfn): ''' Clean out a template temp file ''' if sfn.startswith(os.path.join(tempfile.gettempdir(), salt.utils.files.TEMPFILE_PREFIX)): # Don't remove if it exists in file_roots (any saltenv) all_roots = itertools.chain.from_iterable( six.itervalues(__opts__['file_roots'])) in_roots = any(sfn.startswith(root) for root in all_roots) # Only clean up files that exist if os.path.exists(sfn) and not in_roots: os.remove(sfn) def _error(ret, err_msg): ''' Common function for setting error information for return dicts ''' ret['result'] = False ret['comment'] = err_msg return ret def _binary_replace(old, new): ''' This function does NOT do any diffing, it just checks the old and new files to see if either is binary, and provides an appropriate string noting the difference between the two files. If neither file is binary, an empty string is returned. This function should only be run AFTER it has been determined that the files differ. ''' old_isbin = not __utils__['files.is_text'](old) new_isbin = not __utils__['files.is_text'](new) if any((old_isbin, new_isbin)): if all((old_isbin, new_isbin)): return 'Replace binary file' elif old_isbin: return 'Replace binary file with text file' elif new_isbin: return 'Replace text file with binary file' return '' def _get_bkroot(): ''' Get the location of the backup dir in the minion cache ''' # Get the cachedir from the minion config return os.path.join(__salt__['config.get']('cachedir'), 'file_backup') def _splitlines_preserving_trailing_newline(str): ''' Returns a list of the lines in the string, breaking at line boundaries and preserving a trailing newline (if present). Essentially, this works like ``str.striplines(False)`` but preserves an empty line at the end. This is equivalent to the following code: .. code-block:: python lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') ''' lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') return lines def gid_to_group(gid): ''' Convert the group id to the group name on this system gid gid to convert to a group name CLI Example: .. code-block:: bash salt '*' file.gid_to_group 0 ''' try: gid = int(gid) except ValueError: # This is not an integer, maybe it's already the group name? gid = group_to_gid(gid) if gid == '': # Don't even bother to feed it to grp return '' try: return grp.getgrgid(gid).gr_name except (KeyError, NameError): # If group is not present, fall back to the gid. return gid def group_to_gid(group): ''' Convert the group to the gid on this system group group to convert to its gid CLI Example: .. code-block:: bash salt '*' file.group_to_gid root ''' if group is None: return '' try: if isinstance(group, int): return group return grp.getgrnam(group).gr_gid except KeyError: return '' def get_gid(path, follow_symlinks=True): ''' Return the id of the group that owns a given file path file or directory of which to get the gid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_gid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('gid', -1) def get_group(path, follow_symlinks=True): ''' Return the group that owns a given file path file or directory of which to get the group follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_group /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('group', False) def uid_to_user(uid): ''' Convert a uid to a user name uid uid to convert to a username CLI Example: .. code-block:: bash salt '*' file.uid_to_user 0 ''' try: return pwd.getpwuid(uid).pw_name except (KeyError, NameError): # If user is not present, fall back to the uid. return uid def user_to_uid(user): ''' Convert user name to a uid user user name to convert to its uid CLI Example: .. code-block:: bash salt '*' file.user_to_uid root ''' if user is None: user = salt.utils.user.get_user() try: if isinstance(user, int): return user return pwd.getpwnam(user).pw_uid except KeyError: return '' def get_uid(path, follow_symlinks=True): ''' Return the id of the user that owns a given file path file or directory of which to get the uid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_uid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('uid', -1) def get_user(path, follow_symlinks=True): ''' Return the user that owns a given file path file or directory of which to get the user follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_user /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('user', False) def set_mode(path, mode): ''' Set the mode of a file path file or directory of which to set the mode mode mode to set the path to CLI Example: .. code-block:: bash salt '*' file.set_mode /etc/passwd 0644 ''' path = os.path.expanduser(path) mode = six.text_type(mode).lstrip('0Oo') if not mode: mode = '0' if not os.path.exists(path): raise CommandExecutionError('{0}: File not found'.format(path)) try: os.chmod(path, int(mode, 8)) except Exception: return 'Invalid Mode ' + mode return get_mode(path) def lchown(path, user, group): ''' Chown a file, pass the file the desired user and group without following symlinks. path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 return os.lchown(path, uid, gid) def chown(path, user, group): ''' Chown a file, pass the file the desired user and group path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 if not os.path.exists(path): try: # Broken symlinks will return false, but still need to be chowned return os.lchown(path, uid, gid) except OSError: pass err += 'File not found' if err: return err return os.chown(path, uid, gid) def chgrp(path, group): ''' Change the group of a file path path to the file or directory group group owner CLI Example: .. code-block:: bash salt '*' file.chgrp /etc/passwd root ''' path = os.path.expanduser(path) user = get_user(path) return chown(path, user, group) def _cmp_attrs(path, attrs): ''' .. versionadded:: 2018.3.0 Compare attributes of a given file to given attributes. Returns a pair (list) where first item are attributes to add and second item are to be removed. Please take into account when using this function that some minions will not have lsattr installed. path path to file to compare attributes with. attrs string of attributes to compare against a given file ''' diff = [None, None] # lsattr for AIX is not the same thing as lsattr for linux. if salt.utils.platform.is_aix(): return None try: lattrs = lsattr(path).get(path, '') except AttributeError: # lsattr not installed return None old = [chr for chr in lattrs if chr not in attrs] if old: diff[1] = ''.join(old) new = [chr for chr in attrs if chr not in lattrs] if new: diff[0] = ''.join(new) return diff def lsattr(path): ''' .. versionadded:: 2018.3.0 .. versionchanged:: 2018.3.1 If ``lsattr`` is not installed on the system, ``None`` is returned. .. versionchanged:: 2018.3.4 If on ``AIX``, ``None`` is returned even if in filesystem as lsattr on ``AIX`` is not the same thing as the linux version. Obtain the modifiable attributes of the given file. If path is to a directory, an empty list is returned. path path to file to obtain attributes of. File/directory must exist. CLI Example: .. code-block:: bash salt '*' file.lsattr foo1.txt ''' if not salt.utils.path.which('lsattr') or salt.utils.platform.is_aix(): return None if not os.path.exists(path): raise SaltInvocationError("File or directory does not exist: " + path) cmd = ['lsattr', path] result = __salt__['cmd.run'](cmd, ignore_retcode=True, python_shell=False) results = {} for line in result.splitlines(): if not line.startswith('lsattr: '): vals = line.split(None, 1) results[vals[1]] = re.findall(r"[aAcCdDeijPsStTu]", vals[0]) return results def chattr(*files, **kwargs): ''' .. versionadded:: 2018.3.0 Change the attributes of files. This function accepts one or more files and the following options: operator Can be wither ``add`` or ``remove``. Determines whether attributes should be added or removed from files attributes One or more of the following characters: ``aAcCdDeijPsStTu``, representing attributes to add to/remove from files version a version number to assign to the file(s) flags One or more of the following characters: ``RVf``, representing flags to assign to chattr (recurse, verbose, suppress most errors) CLI Example: .. code-block:: bash salt '*' file.chattr foo1.txt foo2.txt operator=add attributes=ai salt '*' file.chattr foo3.txt operator=remove attributes=i version=2 ''' operator = kwargs.pop('operator', None) attributes = kwargs.pop('attributes', None) flags = kwargs.pop('flags', None) version = kwargs.pop('version', None) if (operator is None) or (operator not in ('add', 'remove')): raise SaltInvocationError( "Need an operator: 'add' or 'remove' to modify attributes.") if attributes is None: raise SaltInvocationError("Need attributes: [aAcCdDeijPsStTu]") cmd = ['chattr'] if operator == "add": attrs = '+{0}'.format(attributes) elif operator == "remove": attrs = '-{0}'.format(attributes) cmd.append(attrs) if flags is not None: cmd.append('-{0}'.format(flags)) if version is not None: cmd.extend(['-v', version]) cmd.extend(files) result = __salt__['cmd.run'](cmd, python_shell=False) if bool(result): raise CommandExecutionError( "chattr failed to run, possibly due to bad parameters.") return True def get_sum(path, form='sha256'): ''' Return the checksum for the given file. The following checksum algorithms are supported: * md5 * sha1 * sha224 * sha256 **(default)** * sha384 * sha512 path path to the file or directory form desired sum format CLI Example: .. code-block:: bash salt '*' file.get_sum /etc/passwd sha512 ''' path = os.path.expanduser(path) if not os.path.isfile(path): return 'File not found' return salt.utils.hashutils.get_hash(path, form, 4096) def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` path path to the file or directory form desired sum format chunk_size amount to sum at once CLI Example: .. code-block:: bash salt '*' file.get_hash /etc/shadow ''' return salt.utils.hashutils.get_hash(os.path.expanduser(path), form, chunk_size) def get_source_sum(file_name='', source='', source_hash=None, source_hash_name=None, saltenv='base'): ''' .. versionadded:: 2016.11.0 Used by :py:func:`file.get_managed <salt.modules.file.get_managed>` to obtain the hash and hash type from the parameters specified below. file_name Optional file name being managed, for matching with :py:func:`file.extract_hash <salt.modules.file.extract_hash>`. source Source file, as used in :py:mod:`file <salt.states.file>` and other states. If ``source_hash`` refers to a file containing hashes, then this filename will be used to match a filename in that file. If the ``source_hash`` is a hash expression, then this argument will be ignored. source_hash Hash file/expression, as used in :py:mod:`file <salt.states.file>` and other states. If this value refers to a remote URL or absolute path to a local file, it will be cached and :py:func:`file.extract_hash <salt.modules.file.extract_hash>` will be used to obtain a hash from it. source_hash_name Specific file name to look for when ``source_hash`` refers to a remote file, used to disambiguate ambiguous matches. saltenv : base Salt fileserver environment from which to retrieve the source_hash. This value will only be used when ``source_hash`` refers to a file on the Salt fileserver (i.e. one beginning with ``salt://``). CLI Example: .. code-block:: bash salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=499ae16dcae71eeb7c3a30c75ea7a1a6 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 source_hash_name=./dir2/foo.tar.gz ''' def _invalid_source_hash_format(): ''' DRY helper for reporting invalid source_hash input ''' raise CommandExecutionError( 'Source hash {0} format is invalid. The supported formats are: ' '1) a hash, 2) an expression in the format <hash_type>=<hash>, or ' '3) either a path to a local file containing hashes, or a URI of ' 'a remote hash file. Supported protocols for remote hash files ' 'are: {1}. The hash may also not be of a valid length, the ' 'following are supported hash types and lengths: {2}.'.format( source_hash, ', '.join(salt.utils.files.VALID_PROTOS), ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) hash_fn = None if os.path.isabs(source_hash): hash_fn = source_hash else: try: proto = _urlparse(source_hash).scheme if proto in salt.utils.files.VALID_PROTOS: hash_fn = __salt__['cp.cache_file'](source_hash, saltenv) if not hash_fn: raise CommandExecutionError( 'Source hash file {0} not found'.format(source_hash) ) else: if proto != '': # Some unsupported protocol (e.g. foo://) is being used. # We'll get into this else block if a hash expression # (like md5=<md5 checksum here>), but in those cases, the # protocol will be an empty string, in which case we avoid # this error condition. _invalid_source_hash_format() except (AttributeError, TypeError): _invalid_source_hash_format() if hash_fn is not None: ret = extract_hash(hash_fn, '', file_name, source, source_hash_name) if ret is None: _invalid_source_hash_format() ret['hsum'] = ret['hsum'].lower() return ret else: # The source_hash is a hash expression ret = {} try: ret['hash_type'], ret['hsum'] = \ [x.strip() for x in source_hash.split('=', 1)] except AttributeError: _invalid_source_hash_format() except ValueError: # No hash type, try to figure out by hash length if not re.match('^[{0}]+$'.format(string.hexdigits), source_hash): _invalid_source_hash_format() ret['hsum'] = source_hash source_hash_len = len(source_hash) if source_hash_len in HASHES_REVMAP: ret['hash_type'] = HASHES_REVMAP[source_hash_len] else: _invalid_source_hash_format() if ret['hash_type'] not in HASHES: raise CommandExecutionError( 'Invalid hash type \'{0}\'. Supported hash types are: {1}. ' 'Either remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to a supported type.' .format(ret['hash_type'], ', '.join(HASHES), ret['hsum']) ) else: hsum_len = len(ret['hsum']) if hsum_len not in HASHES_REVMAP: _invalid_source_hash_format() elif hsum_len != HASHES[ret['hash_type']]: raise CommandExecutionError( 'Invalid length ({0}) for hash type \'{1}\'. Either ' 'remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to \'{3}\''.format( hsum_len, ret['hash_type'], ret['hsum'], HASHES_REVMAP[hsum_len], ) ) ret['hsum'] = ret['hsum'].lower() return ret def check_hash(path, file_hash): ''' Check if a file matches the given hash string Returns ``True`` if the hash matches, otherwise ``False``. path Path to a file local to the minion. hash The hash to check against the file specified in the ``path`` argument. .. versionchanged:: 2016.11.4 For this and newer versions the hash can be specified without an accompanying hash type (e.g. ``e138491e9d5b97023cea823fe17bac22``), but for earlier releases it is necessary to also specify the hash type in the format ``<hash_type>=<hash_value>`` (e.g. ``md5=e138491e9d5b97023cea823fe17bac22``). CLI Example: .. code-block:: bash salt '*' file.check_hash /etc/fstab e138491e9d5b97023cea823fe17bac22 salt '*' file.check_hash /etc/fstab md5=e138491e9d5b97023cea823fe17bac22 ''' path = os.path.expanduser(path) if not isinstance(file_hash, six.string_types): raise SaltInvocationError('hash must be a string') for sep in (':', '='): if sep in file_hash: hash_type, hash_value = file_hash.split(sep, 1) break else: hash_value = file_hash hash_len = len(file_hash) hash_type = HASHES_REVMAP.get(hash_len) if hash_type is None: raise SaltInvocationError( 'Hash {0} (length: {1}) could not be matched to a supported ' 'hash type. The supported hash types and lengths are: ' '{2}'.format( file_hash, hash_len, ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) return get_hash(path, hash_type) == hash_value def find(path, *args, **kwargs): ''' Approximate the Unix ``find(1)`` command and return a list of paths that meet the specified criteria. The options include match criteria: .. code-block:: text name = path-glob # case sensitive iname = path-glob # case insensitive regex = path-regex # case sensitive iregex = path-regex # case insensitive type = file-types # match any listed type user = users # match any listed user group = groups # match any listed group size = [+-]number[size-unit] # default unit = byte mtime = interval # modified since date grep = regex # search file contents and/or actions: .. code-block:: text delete [= file-types] # default type = 'f' exec = command [arg ...] # where {} is replaced by pathname print [= print-opts] and/or depth criteria: .. code-block:: text maxdepth = maximum depth to transverse in path mindepth = minimum depth to transverse before checking files or directories The default action is ``print=path`` ``path-glob``: .. code-block:: text * = match zero or more chars ? = match any char [abc] = match a, b, or c [!abc] or [^abc] = match anything except a, b, and c [x-y] = match chars x through y [!x-y] or [^x-y] = match anything except chars x through y {a,b,c} = match a or b or c ``path-regex``: a Python Regex (regular expression) pattern to match pathnames ``file-types``: a string of one or more of the following: .. code-block:: text a: all file types b: block device c: character device d: directory p: FIFO (named pipe) f: plain file l: symlink s: socket ``users``: a space and/or comma separated list of user names and/or uids ``groups``: a space and/or comma separated list of group names and/or gids ``size-unit``: .. code-block:: text b: bytes k: kilobytes m: megabytes g: gigabytes t: terabytes interval: .. code-block:: text [<num>w] [<num>d] [<num>h] [<num>m] [<num>s] where: w: week d: day h: hour m: minute s: second print-opts: a comma and/or space separated list of one or more of the following: .. code-block:: text group: group name md5: MD5 digest of file contents mode: file permissions (as integer) mtime: last modification time (as time_t) name: file basename path: file absolute path size: file size in bytes type: file type user: user name CLI Examples: .. code-block:: bash salt '*' file.find / type=f name=\\*.bak size=+10m salt '*' file.find /var mtime=+30d size=+10m print=path,size,mtime salt '*' file.find /var/log name=\\*.[0-9] mtime=+30d size=+10m delete ''' if 'delete' in args: kwargs['delete'] = 'f' elif 'print' in args: kwargs['print'] = 'path' try: finder = salt.utils.find.Finder(kwargs) except ValueError as ex: return 'error: {0}'.format(ex) ret = [item for i in [finder.find(p) for p in glob.glob(os.path.expanduser(path))] for item in i] ret.sort() return ret def _sed_esc(string, escape_all=False): ''' Escape single quotes and forward slashes ''' special_chars = "^.[$()|*+?{" string = string.replace("'", "'\"'\"'").replace("/", "\\/") if escape_all is True: for char in special_chars: string = string.replace(char, "\\" + char) return string def sed(path, before, after, limit='', backup='.bak', options='-r -e', flags='g', escape_all=False, negate_match=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup options : ``-r -e`` Options to pass to sed flags : ``g`` Flags to modify the sed search; e.g., ``i`` for case-insensitive pattern matching negate_match : False Negate the search command (``!``) .. versionadded:: 0.17.0 Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # path = os.path.expanduser(path) if not os.path.exists(path): return False # Mandate that before and after are strings before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.append('-i{0}'.format(backup) if backup else '-i') cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}{negate_match}s/{before}/{after}/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', negate_match='!' if negate_match else '', before=before, after=after, flags=flags ) ) cmd.append(path) return __salt__['cmd.run_all'](cmd, python_shell=False) def sed_contains(path, text, limit='', flags='g'): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the file at ``path`` contains ``text``. Utilizes sed to perform the search (line-wise search). Note: the ``p`` flag will be added to any flags you pass in. CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' # Largely inspired by Fabric's contrib.files.contains() path = os.path.expanduser(path) if not os.path.exists(path): return False before = _sed_esc(six.text_type(text), False) limit = _sed_esc(six.text_type(limit), False) options = '-n -r -e' if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}s/{before}/$/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', before=before, flags='p{0}'.format(flags) ) ) cmd.append(path) result = __salt__['cmd.run'](cmd, python_shell=False) return bool(result) def psed(path, before, after, limit='', backup='.bak', flags='gMS', escape_all=False, multi=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file (pure Python version) Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup flags : ``gMS`` Flags to modify the search. Valid values are: - ``g``: Replace all occurrences of the pattern, not just the first. - ``I``: Ignore case. - ``L``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\s`` and ``\\S`` dependent on the locale. - ``M``: Treat multiple lines as a single line. - ``S``: Make `.` match all characters, including newlines. - ``U``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\d``, ``\\D``, ``\\s`` and ``\\S`` dependent on Unicode. - ``X``: Verbose (whitespace is ignored). multi: ``False`` If True, treat the entire file as a single line Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # # Mandate that before and after are strings path = os.path.expanduser(path) multi = bool(multi) before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) # The pattern to replace with does not need to be escaped!!! # after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) shutil.copy2(path, '{0}{1}'.format(path, backup)) with salt.utils.files.fopen(path, 'w') as ofile: with salt.utils.files.fopen('{0}{1}'.format(path, backup), 'r') as ifile: if multi is True: for line in ifile.readline(): ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(line), before, after, limit, flags ) ) ) else: ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(ifile.read()), before, after, limit, flags ) ) ) RE_FLAG_TABLE = {'I': re.I, 'L': re.L, 'M': re.M, 'S': re.S, 'U': re.U, 'X': re.X} def _psed(text, before, after, limit, flags): ''' Does the actual work for file.psed, so that single lines can be passed in ''' atext = text if limit: limit = re.compile(limit) comps = text.split(limit) atext = ''.join(comps[1:]) count = 1 if 'g' in flags: count = 0 flags = flags.replace('g', '') aflags = 0 for flag in flags: aflags |= RE_FLAG_TABLE[flag] before = re.compile(before, flags=aflags) text = re.sub(before, after, atext, count=count) return text def uncomment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Uncomment specified commented lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be uncommented. This regex should not include the comment character. A leading ``^`` character will be stripped for convenience (for easily switching between comment() and uncomment()). char : ``#`` The character to remove in order to uncomment a line backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup CLI Example: .. code-block:: bash salt '*' file.uncomment /etc/hosts.deny 'ALL: PARANOID' ''' return comment_line(path=path, regex=regex, char=char, cmnt=False, backup=backup) def comment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Comment out specified lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be commented; this pattern will be wrapped in parenthesis and will move any preceding/trailing ``^`` or ``$`` characters outside the parenthesis (e.g., the pattern ``^foo$`` will be rewritten as ``^(foo)$``) char : ``#`` The character to be inserted at the beginning of a line in order to comment it out backup : ``.bak`` The file will be backed up before edit with this file extension .. warning:: This backup will be overwritten each time ``sed`` / ``comment`` / ``uncomment`` is called. Meaning the backup will only be useful after the first invocation. CLI Example: .. code-block:: bash salt '*' file.comment /etc/modules pcspkr ''' return comment_line(path=path, regex=regex, char=char, cmnt=True, backup=backup) def comment_line(path, regex, char='#', cmnt=True, backup='.bak'): r''' Comment or Uncomment a line in a text file. :param path: string The full path to the text file. :param regex: string A regex expression that begins with ``^`` that will find the line you wish to comment. Can be as simple as ``^color =`` :param char: string The character used to comment a line in the type of file you're referencing. Default is ``#`` :param cmnt: boolean True to comment the line. False to uncomment the line. Default is True. :param backup: string The file extension to give the backup file. Default is ``.bak`` Set to False/None to not keep a backup. :return: boolean Returns True if successful, False if not CLI Example: The following example will comment out the ``pcspkr`` line in the ``/etc/modules`` file using the default ``#`` character and create a backup file named ``modules.bak`` .. code-block:: bash salt '*' file.comment_line '/etc/modules' '^pcspkr' CLI Example: The following example will uncomment the ``log_level`` setting in ``minion`` config file if it is set to either ``warning``, ``info``, or ``debug`` using the ``#`` character and create a backup file named ``minion.bk`` .. code-block:: bash salt '*' file.comment_line 'C:\salt\conf\minion' '^log_level: (warning|info|debug)' '#' False '.bk' ''' # Get the regex for comment or uncomment if cmnt: regex = '{0}({1}){2}'.format( '^' if regex.startswith('^') else '', regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') else: regex = r'^{0}\s*({1}){2}'.format( char, regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') # Load the real path to the file path = os.path.realpath(os.path.expanduser(path)) # Make sure the file exists if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) # Make sure it is a text file if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}'.format(path)) # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes found = False # Dictionaries for comparing changes orig_file = [] new_file = [] # Buffer size for fopen bufsize = os.path.getsize(path) try: # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: # Is it in this line line = salt.utils.stringutils.to_unicode(line) if re.match(regex, line): # Load lines into dictionaries, set found to True orig_file.append(line) if cmnt: new_file.append('{0}{1}'.format(char, line)) else: new_file.append(line.lstrip(char)) found = True except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) # We've searched the whole file. If we didn't find anything, return False if not found: return False if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Create a copy to read from and to use as a backup later try: temp_file = _mkstemp_copy(path=path, preserve_inode=False) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) try: # Open the file in write mode mode = 'wb' if six.PY2 and salt.utils.platform.is_windows() else 'w' with salt.utils.files.fopen(path, mode=mode, buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: line = salt.utils.stringutils.to_unicode(line) try: # Is it in this line if re.match(regex, line): # Write the new line if cmnt: wline = '{0}{1}'.format(char, line) else: wline = line.lstrip(char) else: # Write the existing line (no change) wline = line wline = salt.utils.stringutils.to_bytes(wline) \ if six.PY2 and salt.utils.platform.is_windows() \ else salt.utils.stringutils.to_str(wline) w_file.write(wline) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if backup: # Move the backup file to the original directory backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: os.remove(temp_file) if not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) # Return a diff using the two dictionaries return __utils__['stringutils.get_diff'](orig_file, new_file) def _get_flags(flags): ''' Return an integer appropriate for use as a flag for the re module from a list of human-readable strings .. code-block:: python >>> _get_flags(['MULTILINE', 'IGNORECASE']) 10 >>> _get_flags('MULTILINE') 8 >>> _get_flags(2) 2 ''' if isinstance(flags, six.string_types): flags = [flags] if isinstance(flags, Iterable) and not isinstance(flags, Mapping): _flags_acc = [] for flag in flags: _flag = getattr(re, six.text_type(flag).upper()) if not isinstance(_flag, six.integer_types): raise SaltInvocationError( 'Invalid re flag given: {0}'.format(flag) ) _flags_acc.append(_flag) return reduce(operator.__or__, _flags_acc) elif isinstance(flags, six.integer_types): return flags else: raise SaltInvocationError( 'Invalid re flags: "{0}", must be given either as a single flag ' 'string, a list of strings, or as an integer'.format(flags) ) def _add_flags(flags, new_flags): ''' Combine ``flags`` and ``new_flags`` ''' flags = _get_flags(flags) new_flags = _get_flags(new_flags) return flags | new_flags def _mkstemp_copy(path, preserve_inode=True): ''' Create a temp file and move/copy the contents of ``path`` to the temp file. Return the path to the temp file. path The full path to the file whose contents will be moved/copied to a temp file. Whether it's moved or copied depends on the value of ``preserve_inode``. preserve_inode Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). Default is ``True``. ''' temp_file = None # Create the temp file try: temp_file = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to create temp file. " "Exception: {0}".format(exc) ) # use `copy` to preserve the inode of the # original file, and thus preserve hardlinks # to the inode. otherwise, use `move` to # preserve prior behavior, which results in # writing the file to a new inode. if preserve_inode: try: shutil.copy2(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to copy file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: try: shutil.move(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) return temp_file def _starts_till(src, probe, strip_comments=True): ''' Returns True if src and probe at least matches at the beginning till some point. ''' def _strip_comments(txt): ''' Strip possible comments. Usually comments are one or two symbols at the beginning of the line, separated with space ''' buff = txt.split(" ", 1) return len(buff) == 2 and len(buff[0]) < 2 and buff[1] or txt def _to_words(txt): ''' Split by words ''' return txt and [w for w in txt.strip().split(" ") if w.strip()] or txt no_match = -1 equal = 0 if not src or not probe: return no_match src = src.rstrip('\n\r') probe = probe.rstrip('\n\r') if src == probe: return equal src = _to_words(strip_comments and _strip_comments(src) or src) probe = _to_words(strip_comments and _strip_comments(probe) or probe) a_buff, b_buff = len(src) < len(probe) and (src, probe) or (probe, src) b_buff = ' '.join(b_buff) for idx in range(len(a_buff)): prb = ' '.join(a_buff[:-(idx + 1)]) if prb and b_buff.startswith(prb): return idx return no_match def _regex_to_static(src, regex): ''' Expand regular expression to static match. ''' if not src or not regex: return None try: compiled = re.compile(regex, re.DOTALL) src = [line for line in src if compiled.search(line) or line.count(regex)] except Exception as ex: raise CommandExecutionError("{0}: '{1}'".format(_get_error_message(ex), regex)) return src and src or [] def _assert_occurrence(probe, target, amount=1): ''' Raise an exception, if there are different amount of specified occurrences in src. ''' occ = len(probe) if occ > amount: msg = 'more than' elif occ < amount: msg = 'less than' elif not occ: msg = 'no' else: msg = None if msg: raise CommandExecutionError('Found {0} expected occurrences in "{1}" expression'.format(msg, target)) return occ def _set_line_indent(src, line, indent): ''' Indent the line with the source line. ''' if not indent: return line idt = [] for c in src: if c not in ['\t', ' ']: break idt.append(c) return ''.join(idt) + line.lstrip() def _get_eol(line): match = re.search('((?<!\r)\n|\r(?!\n)|\r\n)$', line) return match and match.group() or '' def _set_line_eol(src, line): ''' Add line ending ''' line_ending = _get_eol(src) or os.linesep return line.rstrip() + line_ending def _insert_line_before(idx, body, content, indent): if not idx or (idx and _starts_till(body[idx - 1], content) < 0): cnd = _set_line_indent(body[idx], content, indent) body.insert(idx, cnd) return body def _insert_line_after(idx, body, content, indent): # No duplicates or append, if "after" is the last line next_line = idx + 1 < len(body) and body[idx + 1] or None if next_line is None or _starts_till(next_line, content) < 0: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) return body def line(path, content=None, match=None, mode=None, location=None, before=None, after=None, show_changes=True, backup=False, quiet=False, indent=True): ''' .. versionadded:: 2015.8.0 Edit a line in the configuration file. The ``path`` and ``content`` arguments are required, as well as passing in one of the ``mode`` options. path Filesystem path to the file to be edited. content Content of the line. Allowed to be empty if mode=delete. match Match the target line for an action by a fragment of a string or regular expression. If neither ``before`` nor ``after`` are provided, and ``match`` is also ``None``, match becomes the ``content`` value. mode Defines how to edit a line. One of the following options is required: - ensure If line does not exist, it will be added. This is based on the ``content`` argument. - replace If line already exists, it will be replaced. - delete Delete the line, once found. - insert Insert a line. .. note:: If ``mode=insert`` is used, at least one of the following options must also be defined: ``location``, ``before``, or ``after``. If ``location`` is used, it takes precedence over the other two options. location Defines where to place content in the line. Note this option is only used when ``mode=insert`` is specified. If a location is passed in, it takes precedence over both the ``before`` and ``after`` kwargs. Valid locations are: - start Place the content at the beginning of the file. - end Place the content at the end of the file. before Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. after Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. show_changes Output a unified diff of the old file and the new file. If ``False`` return a boolean if any changes were made. Default is ``True`` .. note:: Using this option will store two copies of the file in-memory (the original version and the edited version) in order to generate the diff. backup Create a backup of the original file with the extension: "Year-Month-Day-Hour-Minutes-Seconds". quiet Do not raise any exceptions. E.g. ignore the fact that the file that is tried to be edited does not exist and nothing really happened. indent Keep indentation with the previous line. This option is not considered when the ``delete`` mode is specified. CLI Example: .. code-block:: bash salt '*' file.line /etc/nsswitch.conf "networks:\tfiles dns" after="hosts:.*?" mode='ensure' .. note:: If an equal sign (``=``) appears in an argument to a Salt command, it is interpreted as a keyword argument in the format of ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.line /path/to/file content="CREATEMAIL_SPOOL=no" match="CREATE_MAIL_SPOOL=yes" mode="replace" ''' path = os.path.realpath(os.path.expanduser(path)) if not os.path.isfile(path): if not quiet: raise CommandExecutionError('File "{0}" does not exists or is not a file.'.format(path)) return False # No changes had happened mode = mode and mode.lower() or mode if mode not in ['insert', 'ensure', 'delete', 'replace']: if mode is None: raise CommandExecutionError('Mode was not defined. How to process the file?') else: raise CommandExecutionError('Unknown mode: "{0}"'.format(mode)) # We've set the content to be empty in the function params but we want to make sure # it gets passed when needed. Feature #37092 empty_content_modes = ['delete'] if mode not in empty_content_modes and content is None: raise CommandExecutionError('Content can only be empty if mode is "{0}"'.format(', '.join(empty_content_modes))) del empty_content_modes # Before/after has privilege. If nothing defined, match is used by content. if before is None and after is None and not match: match = content with salt.utils.files.fopen(path, mode='r') as fp_: body = salt.utils.data.decode_list(fp_.readlines()) body_before = hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() # Add empty line at the end if last line ends with eol. # Allows simpler code if body and _get_eol(body[-1]): body.append('') after = _regex_to_static(body, after) before = _regex_to_static(body, before) match = _regex_to_static(body, match) if os.stat(path).st_size == 0 and mode in ('delete', 'replace'): log.warning('Cannot find text to %s. File \'%s\' is empty.', mode, path) body = [] elif mode == 'delete' and match: body = [line for line in body if line != match[0]] elif mode == 'replace' and match: idx = body.index(match[0]) file_line = body.pop(idx) body.insert(idx, _set_line_indent(file_line, content, indent)) elif mode == 'insert': if not location and not before and not after: raise CommandExecutionError('On insert must be defined either "location" or "before/after" conditions.') if not location: if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') out = [] in_range = False for line in body: if line == after[0]: in_range = True elif line == before[0] and in_range: cnd = _set_line_indent(line, content, indent) out.append(cnd) out.append(line) body = out if before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif after and not before: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: if location == 'start': if body: body.insert(0, _set_line_eol(body[0], content)) else: body.append(content + os.linesep) elif location == 'end': body.append(_set_line_indent(body[-1], content, indent) if body else content) elif mode == 'ensure': if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') is_there = bool([l for l in body if l.count(content)]) if not is_there: idx = body.index(after[0]) if idx < (len(body) - 1) and body[idx + 1] == before[0]: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) else: raise CommandExecutionError('Found more than one line between ' 'boundaries "before" and "after".') elif before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif not before and after: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: raise CommandExecutionError("Wrong conditions? " "Unable to ensure line without knowing " "where to put it before and/or after.") if body: for idx, line in enumerate(body): if not _get_eol(line) and idx+1 < len(body): prev = idx and idx-1 or 1 body[idx] = _set_line_eol(body[prev], line) # We do not need empty line at the end anymore if '' == body[-1]: body.pop() changed = body_before != hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() if backup and changed and __opts__['test'] is False: try: temp_file = _mkstemp_copy(path=path, preserve_inode=True) shutil.move(temp_file, '{0}.{1}'.format(path, time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime()))) except (OSError, IOError) as exc: raise CommandExecutionError("Unable to create the backup file of {0}. Exception: {1}".format(path, exc)) changes_diff = None if changed: if show_changes: with salt.utils.files.fopen(path, 'r') as fp_: path_content = salt.utils.data.decode_list(fp_.read().splitlines(True)) changes_diff = __utils__['stringutils.get_diff'](path_content, body) if __opts__['test'] is False: fh_ = None try: # Make sure we match the file mode from salt.utils.files.fopen if six.PY2 and salt.utils.platform.is_windows(): mode = 'wb' body = salt.utils.data.encode_list(body) else: mode = 'w' body = salt.utils.data.decode_list(body, to_str=True) fh_ = salt.utils.atomicfile.atomic_open(path, mode) fh_.writelines(body) finally: if fh_: fh_.close() return show_changes and changes_diff or changed def replace(path, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, backup='.bak', dry_run=False, search_only=False, show_changes=True, ignore_if_missing=False, preserve_inode=True, backslash_literal=False, ): ''' .. versionadded:: 0.17.0 Replace occurrences of a pattern in a file. If ``show_changes`` is ``True``, then a diff of what changed will be returned, otherwise a ``True`` will be returned when changes are made, and ``False`` when no changes are made. This is a pure Python implementation that wraps Python's :py:func:`~re.sub`. path Filesystem path to the file to be edited. If a symlink is specified, it will be resolved to its target. pattern A regular expression, to be matched using Python's :py:func:`~re.search`. repl The replacement text count : 0 Maximum number of pattern occurrences to be replaced. If count is a positive integer ``n``, only ``n`` occurrences will be replaced, otherwise all occurrences will be replaced. flags (list or int) A list of flags defined in the ``re`` module documentation from the Python standard library. Each list item should be a string that will correlate to the human-friendly flag name. E.g., ``['IGNORECASE', 'MULTILINE']``. Optionally, ``flags`` may be an int, with a value corresponding to the XOR (``|``) of all the desired flags. Defaults to 8 (which supports 'MULTILINE'). bufsize (int or str) How much of the file to buffer into memory at once. The default value ``1`` processes one line at a time. The special value ``file`` may be specified which will read the entire file into memory before processing. append_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True``, and pattern is not found, then the content will be appended to the file. prepend_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True`` and pattern is not found, then the content will be prepended to the file. not_found_content .. versionadded:: 2014.7.0 Content to use for append/prepend if not found. If None (default), uses ``repl``. Useful when ``repl`` uses references to group in pattern. backup : .bak The file extension to use for a backup of the file before editing. Set to ``False`` to skip making a backup. dry_run : False If set to ``True``, no changes will be made to the file, the function will just return the changes that would have been made (or a ``True``/``False`` value if ``show_changes`` is set to ``False``). search_only : False If set to true, this no changes will be performed on the file, and this function will simply return ``True`` if the pattern was matched, and ``False`` if not. show_changes : True If ``True``, return a diff of changes made. Otherwise, return ``True`` if changes were made, and ``False`` if not. .. note:: Using this option will store two copies of the file in memory (the original version and the edited version) in order to generate the diff. This may not normally be a concern, but could impact performance if used with large files. ignore_if_missing : False .. versionadded:: 2015.8.0 If set to ``True``, this function will simply return ``False`` if the file doesn't exist. Otherwise, an error will be thrown. preserve_inode : True .. versionadded:: 2015.8.0 Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). backslash_literal : False .. versionadded:: 2016.11.7 Interpret backslashes as literal backslashes for the repl and not escape characters. This will help when using append/prepend so that the backslashes are not interpreted for the repl on the second run of the state. If an equal sign (``=``) appears in an argument to a Salt command it is interpreted as a keyword argument in the format ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.replace /path/to/file pattern='=' repl=':' salt '*' file.replace /path/to/file pattern="bind-address\\s*=" repl='bind-address:' CLI Examples: .. code-block:: bash salt '*' file.replace /etc/httpd/httpd.conf pattern='LogLevel warn' repl='LogLevel info' salt '*' file.replace /some/file pattern='before' repl='after' flags='[MULTILINE, IGNORECASE]' ''' symlink = False if is_link(path): symlink = True target_path = os.readlink(path) given_path = os.path.expanduser(path) path = os.path.realpath(os.path.expanduser(path)) if not os.path.exists(path): if ignore_if_missing: return False else: raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if search_only and (append_if_not_found or prepend_if_not_found): raise SaltInvocationError( 'search_only cannot be used with append/prepend_if_not_found' ) if append_if_not_found and prepend_if_not_found: raise SaltInvocationError( 'Only one of append and prepend_if_not_found is permitted' ) flags_num = _get_flags(flags) cpattern = re.compile(salt.utils.stringutils.to_bytes(pattern), flags_num) filesize = os.path.getsize(path) if bufsize == 'file': bufsize = filesize # Search the file; track if any changes have been made for the return val has_changes = False orig_file = [] # used for show_changes and change detection new_file = [] # used for show_changes and change detection if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Avoid TypeErrors by forcing repl to be bytearray related to mmap # Replacement text may contains integer: 123 for example repl = salt.utils.stringutils.to_bytes(six.text_type(repl)) if not_found_content: not_found_content = salt.utils.stringutils.to_bytes(not_found_content) found = False temp_file = None content = salt.utils.stringutils.to_unicode(not_found_content) \ if not_found_content and (prepend_if_not_found or append_if_not_found) \ else salt.utils.stringutils.to_unicode(repl) try: # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes r_data = None # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: try: # mmap throws a ValueError if the file is empty. r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) except (ValueError, mmap.error): # size of file in /proc is 0, but contains data r_data = salt.utils.stringutils.to_bytes("".join(r_file)) if search_only: # Just search; bail as early as a match is found if re.search(cpattern, r_data): return True # `with` block handles file closure else: return False else: result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) # found anything? (even if no change) if nrepl > 0: found = True # Identity check the potential change has_changes = True if pattern != repl else has_changes if prepend_if_not_found or append_if_not_found: # Search for content, to avoid pre/appending the # content if it was pre/appended in a previous run. if re.search(salt.utils.stringutils.to_bytes('^{0}($|(?=\r\n))'.format(re.escape(content))), r_data, flags=flags_num): # Content was found, so set found. found = True orig_file = r_data.read(filesize).splitlines(True) \ if isinstance(r_data, mmap.mmap) \ else r_data.splitlines(True) new_file = result.splitlines(True) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() if has_changes and not dry_run: # Write the replacement text in this block. try: # Create a copy to read from and to use as a backup later temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) r_data = None try: # Open the file in write mode with salt.utils.files.fopen(path, mode='w', buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='r', buffering=bufsize) as r_file: r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) try: w_file.write(salt.utils.stringutils.to_str(result)) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if not found and (append_if_not_found or prepend_if_not_found): if not_found_content is None: not_found_content = repl if prepend_if_not_found: new_file.insert(0, not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) else: # append_if_not_found # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(salt.utils.stringutils.to_bytes(os.linesep)): new_file[-1] += salt.utils.stringutils.to_bytes(os.linesep) new_file.append(not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) has_changes = True if not dry_run: try: # Create a copy to read from and for later use as a backup temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line)) finally: fh_.close() if backup and has_changes and not dry_run: # keep the backup only if it was requested # and only if there were any changes backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) if symlink: symlink_backup = '{0}{1}'.format(given_path, backup) target_backup = '{0}{1}'.format(target_path, backup) # Always clobber any existing symlink backup # to match the behaviour of the 'backup' option try: os.symlink(target_backup, symlink_backup) except OSError: os.remove(symlink_backup) os.symlink(target_backup, symlink_backup) except Exception: raise CommandExecutionError( "Unable create backup symlink '{0}'. " "Target was '{1}'. " "Exception: {2}".format(symlink_backup, target_backup, exc) ) elif temp_file: try: os.remove(temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to delete temp file '{0}'. " "Exception: {1}".format(temp_file, exc) ) if not dry_run and not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) differences = __utils__['stringutils.get_diff'](orig_file, new_file) if show_changes: return differences # We may have found a regex line match but don't need to change the line # (for situations where the pattern also matches the repl). Revert the # has_changes flag to False if the final result is unchanged. if not differences: has_changes = False return has_changes def blockreplace(path, marker_start='#-- start managed zone --', marker_end='#-- end managed zone --', content='', append_if_not_found=False, prepend_if_not_found=False, backup='.bak', dry_run=False, show_changes=True, append_newline=False, insert_before_match=None, insert_after_match=None): ''' .. versionadded:: 2014.1.0 Replace content of a text block in a file, delimited by line markers A block of content delimited by comments can help you manage several lines entries without worrying about old entries removal. .. note:: This function will store two copies of the file in-memory (the original version and the edited version) in order to detect changes and only edit the targeted file if necessary. path Filesystem path to the file to be edited marker_start The line content identifying a line as the start of the content block. Note that the whole line containing this marker will be considered, so whitespace or extra content before or after the marker is included in final output marker_end The line content identifying the end of the content block. As of versions 2017.7.5 and 2018.3.1, everything up to the text matching the marker will be replaced, so it's important to ensure that your marker includes the beginning of the text you wish to replace. content The content to be used between the two lines identified by marker_start and marker_stop. append_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be appended to the file. prepend_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be prepended to the file. insert_before_match If markers are not found, this parameter can be set to a regex which will insert the block before the first found occurrence in the file. .. versionadded:: Neon insert_after_match If markers are not found, this parameter can be set to a regex which will insert the block after the first found occurrence in the file. .. versionadded:: Neon backup The file extension to use for a backup of the file if any edit is made. Set to ``False`` to skip making a backup. dry_run : False If ``True``, do not make any edits to the file and simply return the changes that *would* be made. show_changes : True Controls how changes are presented. If ``True``, this function will return a unified diff of the changes made. If False, then it will return a boolean (``True`` if any changes were made, otherwise ``False``). append_newline : False Controls whether or not a newline is appended to the content block. If the value of this argument is ``True`` then a newline will be added to the content block. If it is ``False``, then a newline will *not* be added to the content block. If it is ``None`` then a newline will only be added to the content block if it does not already end in a newline. .. versionadded:: 2016.3.4 .. versionchanged:: 2017.7.5,2018.3.1 New behavior added when value is ``None``. .. versionchanged:: 2019.2.0 The default value of this argument will change to ``None`` to match the behavior of the :py:func:`file.blockreplace state <salt.states.file.blockreplace>` CLI Example: .. code-block:: bash salt '*' file.blockreplace /etc/hosts '#-- start managed zone foobar : DO NOT EDIT --' \\ '#-- end managed zone foobar --' $'10.0.1.1 foo.foobar\\n10.0.1.2 bar.foobar' True ''' exclusive_params = [append_if_not_found, prepend_if_not_found, bool(insert_before_match), bool(insert_after_match)] if sum(exclusive_params) > 1: raise SaltInvocationError( 'Only one of append_if_not_found, prepend_if_not_found,' ' insert_before_match, and insert_after_match is permitted' ) path = os.path.expanduser(path) if not os.path.exists(path): raise SaltInvocationError('File not found: {0}'.format(path)) try: file_encoding = __utils__['files.get_encoding'](path) except CommandExecutionError: file_encoding = None if __utils__['files.is_binary'](path): if not file_encoding: raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if insert_before_match or insert_after_match: if insert_before_match: if not isinstance(insert_before_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_before_match parameter.' ) elif insert_after_match: if not isinstance(insert_after_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_after_match parameter.' ) if append_newline is None and not content.endswith((os.linesep, '\n')): append_newline = True # Split the content into a list of lines, removing newline characters. To # ensure that we handle both Windows and POSIX newlines, first split on # Windows newlines, and then split on POSIX newlines. split_content = [] for win_line in content.split('\r\n'): for content_line in win_line.split('\n'): split_content.append(content_line) line_count = len(split_content) has_changes = False orig_file = [] new_file = [] in_block = False block_found = False linesep = None def _add_content(linesep, lines=None, include_marker_start=True, end_line=None): if lines is None: lines = [] include_marker_start = True if end_line is None: end_line = marker_end end_line = end_line.rstrip('\r\n') + linesep if include_marker_start: lines.append(marker_start + linesep) if split_content: for index, content_line in enumerate(split_content, 1): if index != line_count: lines.append(content_line + linesep) else: # We're on the last line of the content block if append_newline: lines.append(content_line + linesep) lines.append(end_line) else: lines.append(content_line + end_line) else: lines.append(end_line) return lines # We do not use in-place editing to avoid file attrs modifications when # no changes are required and to avoid any file access on a partially # written file. try: fi_file = io.open(path, mode='r', encoding=file_encoding, newline='') for line in fi_file: write_line_to_new_file = True if linesep is None: # Auto-detect line separator if line.endswith('\r\n'): linesep = '\r\n' elif line.endswith('\n'): linesep = '\n' else: # No newline(s) in file, fall back to system's linesep linesep = os.linesep if marker_start in line: # We've entered the content block in_block = True else: if in_block: # We're not going to write the lines from the old file to # the new file until we have exited the block. write_line_to_new_file = False marker_end_pos = line.find(marker_end) if marker_end_pos != -1: # End of block detected in_block = False # We've found and exited the block block_found = True _add_content(linesep, lines=new_file, include_marker_start=False, end_line=line[marker_end_pos:]) # Save the line from the original file orig_file.append(line) if write_line_to_new_file: new_file.append(line) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read from {0}: {1}'.format(path, exc) ) finally: if linesep is None: # If the file was empty, we will not have set linesep yet. Assume # the system's line separator. This is needed for when we # prepend/append later on. linesep = os.linesep try: fi_file.close() except Exception: pass if in_block: # unterminated block => bad, always fail raise CommandExecutionError( 'Unterminated marked block. End of file reached before marker_end.' ) if not block_found: if prepend_if_not_found: # add the markers and content at the beginning of file prepended_content = _add_content(linesep) prepended_content.extend(new_file) new_file = prepended_content block_found = True elif append_if_not_found: # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(linesep): new_file[-1] += linesep # add the markers and content at the end of file _add_content(linesep, lines=new_file) block_found = True elif insert_before_match or insert_after_match: match_regex = insert_before_match or insert_after_match match_idx = [i for i, item in enumerate(orig_file) if re.search(match_regex, item)] if match_idx: match_idx = match_idx[0] for line in _add_content(linesep): if insert_after_match: match_idx += 1 new_file.insert(match_idx, line) if insert_before_match: match_idx += 1 block_found = True if not block_found: raise CommandExecutionError( 'Cannot edit marked block. Markers were not found in file.' ) diff = __utils__['stringutils.get_diff'](orig_file, new_file) has_changes = diff is not '' if has_changes and not dry_run: # changes detected # backup file attrs perms = {} perms['user'] = get_user(path) perms['group'] = get_group(path) perms['mode'] = salt.utils.files.normalize_mode(get_mode(path)) # backup old content if backup is not False: backup_path = '{0}{1}'.format(path, backup) shutil.copy2(path, backup_path) # copy2 does not preserve ownership check_perms(backup_path, None, perms['user'], perms['group'], perms['mode']) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line, encoding=file_encoding)) finally: fh_.close() # this may have overwritten file attrs check_perms(path, None, perms['user'], perms['group'], perms['mode']) if show_changes: return diff return has_changes def search(path, pattern, flags=8, bufsize=1, ignore_if_missing=False, multiline=False ): ''' .. versionadded:: 0.17.0 Search for occurrences of a pattern in a file Except for multiline, params are identical to :py:func:`~salt.modules.file.replace`. multiline If true, inserts 'MULTILINE' into ``flags`` and sets ``bufsize`` to 'file'. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' file.search /etc/crontab 'mymaintenance.sh' ''' if multiline: flags = _add_flags(flags, 'MULTILINE') bufsize = 'file' # This function wraps file.replace on purpose in order to enforce # consistent usage, compatible regex's, expected behavior, *and* bugs. :) # Any enhancements or fixes to one should affect the other. return replace(path, pattern, '', flags=flags, bufsize=bufsize, dry_run=True, search_only=True, show_changes=False, ignore_if_missing=ignore_if_missing) def patch(originalfile, patchfile, options='', dry_run=False): ''' .. versionadded:: 0.10.4 Apply a patch to a file or directory. Equivalent to: .. code-block:: bash patch <options> -i <patchfile> <originalfile> Or, when a directory is patched: .. code-block:: bash patch <options> -i <patchfile> -d <originalfile> -p0 originalfile The full path to the file or directory to be patched patchfile A patch file to apply to ``originalfile`` options Options to pass to patch. CLI Example: .. code-block:: bash salt '*' file.patch /opt/file.txt /tmp/file.txt.patch ''' patchpath = salt.utils.path.which('patch') if not patchpath: raise CommandExecutionError( 'patch executable not found. Is the distribution\'s patch ' 'package installed?' ) cmd = [patchpath] cmd.extend(salt.utils.args.shlex_split(options)) if dry_run: if __grains__['kernel'] in ('FreeBSD', 'OpenBSD'): cmd.append('-C') else: cmd.append('--dry-run') # this argument prevents interactive prompts when the patch fails to apply. # the exit code will still be greater than 0 if that is the case. if '-N' not in cmd and '--forward' not in cmd: cmd.append('--forward') has_rejectfile_option = False for option in cmd: if option == '-r' or option.startswith('-r ') \ or option.startswith('--reject-file'): has_rejectfile_option = True break # by default, patch will write rejected patch files to <filename>.rej. # this option prevents that. if not has_rejectfile_option: cmd.append('--reject-file=-') cmd.extend(['-i', patchfile]) if os.path.isdir(originalfile): cmd.extend(['-d', originalfile]) has_strip_option = False for option in cmd: if option.startswith('-p') or option.startswith('--strip='): has_strip_option = True break if not has_strip_option: cmd.append('--strip=0') else: cmd.append(originalfile) return __salt__['cmd.run_all'](cmd, python_shell=False) def contains(path, text): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the file at ``path`` contains ``text`` CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False stripped_text = six.text_type(text).strip() try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if stripped_text in chunk: return True return False except (IOError, OSError): return False def contains_regex(path, regex, lchar=''): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the given regular expression matches on any line in the text of a given file. If the lchar argument (leading char) is specified, it will strip `lchar` from the left side of each line before trying to match CLI Example: .. code-block:: bash salt '*' file.contains_regex /etc/crontab ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.files.fopen(path, 'r') as target: for line in target: line = salt.utils.stringutils.to_unicode(line) if lchar: line = line.lstrip(lchar) if re.search(regex, line): return True return False except (IOError, OSError): return False def contains_glob(path, glob_expr): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the given glob matches a string in the named file CLI Example: .. code-block:: bash salt '*' file.contains_glob /etc/foobar '*cheese*' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if fnmatch.fnmatch(chunk, glob_expr): return True return False except (IOError, OSError): return False def append(path, *args, **kwargs): ''' .. versionadded:: 0.9.5 Append text to the end of a file path path to file `*args` strings to append to file CLI Example: .. code-block:: bash salt '*' file.append /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.append /etc/motd args='cheese=spam' salt '*' file.append /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) # Largely inspired by Fabric's contrib.files.append() if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] # Make sure we have a newline at the end of the file. Do this in binary # mode so SEEK_END with nonzero offset will work. with salt.utils.files.fopen(path, 'rb+') as ofile: linesep = salt.utils.stringutils.to_bytes(os.linesep) try: ofile.seek(-len(linesep), os.SEEK_END) except IOError as exc: if exc.errno in (errno.EINVAL, errno.ESPIPE): # Empty file, simply append lines at the beginning of the file pass else: raise else: if ofile.read(len(linesep)) != linesep: ofile.seek(0, os.SEEK_END) ofile.write(linesep) # Append lines in text mode with salt.utils.files.fopen(path, 'a') as ofile: for new_line in args: ofile.write( salt.utils.stringutils.to_str( '{0}{1}'.format(new_line, os.linesep) ) ) return 'Wrote {0} lines to "{1}"'.format(len(args), path) def prepend(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Prepend text to the beginning of a file path path to file `*args` strings to prepend to the file CLI Example: .. code-block:: bash salt '*' file.prepend /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.prepend /etc/motd args='cheese=spam' salt '*' file.prepend /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] try: with salt.utils.files.fopen(path) as fhr: contents = [salt.utils.stringutils.to_unicode(line) for line in fhr.readlines()] except IOError: contents = [] preface = [] for line in args: preface.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, 'w') as ofile: contents = preface + contents ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Prepended {0} lines to "{1}"'.format(len(args), path) def write(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Write text to a file, overwriting any existing contents. path path to file `*args` strings to write to the file CLI Example: .. code-block:: bash salt '*' file.write /etc/motd \\ "With all thine offerings thou shalt offer salt." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.write /etc/motd args='cheese=spam' salt '*' file.write /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] contents = [] for line in args: contents.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, "w") as ofile: ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Wrote {0} lines to "{1}"'.format(len(contents), path) def touch(name, atime=None, mtime=None): ''' .. versionadded:: 0.9.5 Just like the ``touch`` command, create a file if it doesn't exist or simply update the atime and mtime if it already does. atime: Access time in Unix epoch time. Set it to 0 to set atime of the file with Unix date of birth. If this parameter isn't set, atime will be set with current time. mtime: Last modification in Unix epoch time. Set it to 0 to set mtime of the file with Unix date of birth. If this parameter isn't set, mtime will be set with current time. CLI Example: .. code-block:: bash salt '*' file.touch /var/log/emptyfile ''' name = os.path.expanduser(name) if atime and atime.isdigit(): atime = int(atime) if mtime and mtime.isdigit(): mtime = int(mtime) try: if not os.path.exists(name): with salt.utils.files.fopen(name, 'a'): pass if atime is None and mtime is None: times = None elif mtime is None and atime is not None: times = (atime, time.time()) elif atime is None and mtime is not None: times = (time.time(), mtime) else: times = (atime, mtime) os.utime(name, times) except TypeError: raise SaltInvocationError('atime and mtime must be integers') except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return os.path.exists(name) def tail(path, lines): ''' .. versionadded:: Neon Read the last n lines from a file path path to file lines number of lines to read CLI Example: .. code-block:: bash salt '*' file.tail /path/to/file 10 ''' path = os.path.expanduser(path) lines_found = [] buffer_size = 4098 if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot tail a binary file: {0}'.format(path)) try: lines = int(lines) except ValueError: raise SaltInvocationError('file.tail: \'lines\' value must be an integer') try: with salt.utils.fopen(path) as tail_fh: blk_cnt = 1 size = os.stat(path).st_size if size > buffer_size: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size), os.linesep) for i in range(lines): while len(data) == 1 and ((blk_cnt * buffer_size) < size): blk_cnt += 1 line = data[0] try: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size) + line, os.linesep) except IOError: tail_fh.seek(0) data = string.split(tail_fh.read(size - (buffer_size * (blk_cnt - 1))) + line, os.linesep) line = data[-1] data.pop() lines_found.append(line) return lines_found[-lines:] except (OSError, IOError): raise CommandExecutionError('Could not tail \'{0}\''.format(path)) def seek_read(path, size, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and read it path path to file seek amount to read at once offset offset to start into the file CLI Example: .. code-block:: bash salt '*' file.seek_read /path/to/file 4096 0 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_RDONLY) try: os.lseek(seek_fh, int(offset), 0) data = os.read(seek_fh, int(size)) finally: os.close(seek_fh) return data def seek_write(path, data, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and write to it path path to file data data to write to file offset position in file to start writing CLI Example: .. code-block:: bash salt '*' file.seek_write /path/to/file 'some data' 4096 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_WRONLY) try: os.lseek(seek_fh, int(offset), 0) ret = os.write(seek_fh, data) os.fsync(seek_fh) finally: os.close(seek_fh) return ret def truncate(path, length): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and delete everything after that point path path to file length offset into file to truncate CLI Example: .. code-block:: bash salt '*' file.truncate /path/to/file 512 ''' path = os.path.expanduser(path) with salt.utils.files.fopen(path, 'rb+') as seek_fh: seek_fh.truncate(int(length)) def link(src, path): ''' .. versionadded:: 2014.1.0 Create a hard link to a file CLI Example: .. code-block:: bash salt '*' file.link /path/to/file /path/to/link ''' src = os.path.expanduser(src) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.link(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def is_link(path): ''' Check if the path is a symbolic link CLI Example: .. code-block:: bash salt '*' file.is_link /path/to/link ''' # This function exists because os.path.islink does not support Windows, # therefore a custom function will need to be called. This function # therefore helps API consistency by providing a single function to call for # both operating systems. return os.path.islink(os.path.expanduser(path)) def symlink(src, path): ''' Create a symbolic link (symlink, soft link) to a file CLI Example: .. code-block:: bash salt '*' file.symlink /path/to/file /path/to/link ''' path = os.path.expanduser(path) try: if os.path.normpath(os.readlink(path)) == os.path.normpath(src): log.debug('link already in correct state: %s -> %s', path, src) return True except OSError: pass if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: os.symlink(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def rename(src, dst): ''' Rename a file or directory CLI Example: .. code-block:: bash salt '*' file.rename /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.rename(src, dst) return True except OSError: raise CommandExecutionError( 'Could not rename \'{0}\' to \'{1}\''.format(src, dst) ) return False def copy(src, dst, recurse=False, remove_existing=False): ''' Copy a file or directory from source to dst In order to copy a directory, the recurse flag is required, and will by default overwrite files in the destination with the same path, and retain all other existing files. (similar to cp -r on unix) remove_existing will remove all files in the target directory, and then copy files from the source. .. note:: The copy function accepts paths that are local to the Salt minion. This function does not support salt://, http://, or the other additional file paths that are supported by :mod:`states.file.managed <salt.states.file.managed>` and :mod:`states.file.recurse <salt.states.file.recurse>`. CLI Example: .. code-block:: bash salt '*' file.copy /path/to/src /path/to/dst salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True remove_existing=True ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') if not os.path.exists(src): raise CommandExecutionError('No such file or directory \'{0}\''.format(src)) if not salt.utils.platform.is_windows(): pre_user = get_user(src) pre_group = get_group(src) pre_mode = salt.utils.files.normalize_mode(get_mode(src)) try: if (os.path.exists(dst) and os.path.isdir(dst)) or os.path.isdir(src): if not recurse: raise SaltInvocationError( "Cannot copy overwriting a directory without recurse flag set to true!") if remove_existing: if os.path.exists(dst): shutil.rmtree(dst) shutil.copytree(src, dst) else: salt.utils.files.recursive_copy(src, dst) else: shutil.copyfile(src, dst) except OSError: raise CommandExecutionError( 'Could not copy \'{0}\' to \'{1}\''.format(src, dst) ) if not salt.utils.platform.is_windows(): check_perms(dst, None, pre_user, pre_group, pre_mode) return True def lstat(path): ''' .. versionadded:: 2014.1.0 Returns the lstat attributes for the given file or dir. Does not support symbolic links. CLI Example: .. code-block:: bash salt '*' file.lstat /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to file must be absolute.') try: lst = os.lstat(path) return dict((key, getattr(lst, key)) for key in ('st_atime', 'st_ctime', 'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid')) except Exception: return {} def access(path, mode): ''' .. versionadded:: 2014.1.0 Test whether the Salt process has the specified access to the file. One of the following modes must be specified: .. code-block::text f: Test the existence of the path r: Test the readability of the path w: Test the writability of the path x: Test whether the path can be executed CLI Example: .. code-block:: bash salt '*' file.access /path/to/file f salt '*' file.access /path/to/file x ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') modes = {'f': os.F_OK, 'r': os.R_OK, 'w': os.W_OK, 'x': os.X_OK} if mode in modes: return os.access(path, modes[mode]) elif mode in six.itervalues(modes): return os.access(path, mode) else: raise SaltInvocationError('Invalid mode specified.') def read(path, binary=False): ''' .. versionadded:: 2017.7.0 Return the content of the file. CLI Example: .. code-block:: bash salt '*' file.read /path/to/file ''' access_mode = 'r' if binary is True: access_mode += 'b' with salt.utils.files.fopen(path, access_mode) as file_obj: return salt.utils.stringutils.to_unicode(file_obj.read()) def readlink(path, canonicalize=False): ''' .. versionadded:: 2014.1.0 Return the path that a symlink points to If canonicalize is set to True, then it return the final target CLI Example: .. code-block:: bash salt '*' file.readlink /path/to/link ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') if not os.path.islink(path): raise SaltInvocationError('A valid link was not specified.') if canonicalize: return os.path.realpath(path) else: return os.readlink(path) def readdir(path): ''' .. versionadded:: 2014.1.0 Return a list containing the contents of a directory CLI Example: .. code-block:: bash salt '*' file.readdir /path/to/dir/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Dir path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') dirents = ['.', '..'] dirents.extend(os.listdir(path)) return dirents def statvfs(path): ''' .. versionadded:: 2014.1.0 Perform a statvfs call against the filesystem that the file resides on CLI Example: .. code-block:: bash salt '*' file.statvfs /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: stv = os.statvfs(path) return dict((key, getattr(stv, key)) for key in ('f_bavail', 'f_bfree', 'f_blocks', 'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag', 'f_frsize', 'f_namemax')) except (OSError, IOError): raise CommandExecutionError('Could not statvfs \'{0}\''.format(path)) return False def stats(path, hash_type=None, follow_symlinks=True): ''' Return a dict containing the stats for a given file CLI Example: .. code-block:: bash salt '*' file.stats /etc/passwd ''' path = os.path.expanduser(path) ret = {} if not os.path.exists(path): try: # Broken symlinks will return False for os.path.exists(), but still # have a uid and gid pstat = os.lstat(path) except OSError: # Not a broken symlink, just a nonexistent path # NOTE: The file.directory state checks the content of the error # message in this exception. Any changes made to the message for this # exception will reflect the file.directory state as well, and will # likely require changes there. raise CommandExecutionError('Path not found: {0}'.format(path)) else: if follow_symlinks: pstat = os.stat(path) else: pstat = os.lstat(path) ret['inode'] = pstat.st_ino ret['uid'] = pstat.st_uid ret['gid'] = pstat.st_gid ret['group'] = gid_to_group(pstat.st_gid) ret['user'] = uid_to_user(pstat.st_uid) ret['atime'] = pstat.st_atime ret['mtime'] = pstat.st_mtime ret['ctime'] = pstat.st_ctime ret['size'] = pstat.st_size ret['mode'] = six.text_type(oct(stat.S_IMODE(pstat.st_mode))) if hash_type: ret['sum'] = get_hash(path, hash_type) ret['type'] = 'file' if stat.S_ISDIR(pstat.st_mode): ret['type'] = 'dir' if stat.S_ISCHR(pstat.st_mode): ret['type'] = 'char' if stat.S_ISBLK(pstat.st_mode): ret['type'] = 'block' if stat.S_ISREG(pstat.st_mode): ret['type'] = 'file' if stat.S_ISLNK(pstat.st_mode): ret['type'] = 'link' if stat.S_ISFIFO(pstat.st_mode): ret['type'] = 'pipe' if stat.S_ISSOCK(pstat.st_mode): ret['type'] = 'socket' ret['target'] = os.path.realpath(path) return ret def rmdir(path): ''' .. versionadded:: 2014.1.0 Remove the specified directory. Fails if a directory is not empty. CLI Example: .. code-block:: bash salt '*' file.rmdir /tmp/foo/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') try: os.rmdir(path) return True except OSError as exc: return exc.strerror def remove(path, **kwargs): ''' Remove the named file. If a directory is supplied, it will be recursively deleted. CLI Example: .. code-block:: bash salt '*' file.remove /tmp/foo ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute: {0}'.format(path)) try: if os.path.isfile(path) or os.path.islink(path): os.remove(path) return True elif os.path.isdir(path): shutil.rmtree(path) return True except (OSError, IOError) as exc: raise CommandExecutionError( 'Could not remove \'{0}\': {1}'.format(path, exc) ) return False def directory_exists(path): ''' Tests to see if path is a valid directory. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.directory_exists /etc ''' return os.path.isdir(os.path.expanduser(path)) def file_exists(path): ''' Tests to see if path is a valid file. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.file_exists /etc/passwd ''' return os.path.isfile(os.path.expanduser(path)) def path_exists_glob(path): ''' Tests to see if path after expansion is a valid path (file or directory). Expansion allows usage of ? * and character ranges []. Tilde expansion is not supported. Returns True/False. .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' file.path_exists_glob /etc/pam*/pass* ''' return True if glob.glob(os.path.expanduser(path)) else False def restorecon(path, recursive=False): ''' Reset the SELinux context on a given path CLI Example: .. code-block:: bash salt '*' file.restorecon /home/user/.ssh/authorized_keys ''' if recursive: cmd = ['restorecon', '-FR', path] else: cmd = ['restorecon', '-F', path] return not __salt__['cmd.retcode'](cmd, python_shell=False) def get_selinux_context(path): ''' Get an SELinux context from a given path CLI Example: .. code-block:: bash salt '*' file.get_selinux_context /etc/hosts ''' out = __salt__['cmd.run'](['ls', '-Z', path], python_shell=False) try: ret = re.search(r'\w+:\w+:\w+:\w+', out).group(0) except AttributeError: ret = ( 'No selinux context information is available for {0}'.format(path) ) return ret def set_selinux_context(path, user=None, role=None, type=None, # pylint: disable=W0622 range=None, # pylint: disable=W0622 persist=False): ''' .. versionchanged:: Neon Added persist option Set a specific SELinux label on a given path CLI Example: .. code-block:: bash salt '*' file.set_selinux_context path <user> <role> <type> <range> salt '*' file.set_selinux_context /etc/yum.repos.d/epel.repo system_u object_r system_conf_t s0 ''' if not any((user, role, type, range)): return False if persist: fcontext_result = __salt__['selinux.fcontext_add_policy'](path, sel_type=type, sel_user=user, sel_level=range) if fcontext_result.get('retcode', None) is not 0: # Problem setting fcontext policy raise CommandExecutionError( 'Problem setting fcontext: {0}'.format(fcontext_result) ) cmd = ['chcon'] if user: cmd.extend(['-u', user]) if role: cmd.extend(['-r', role]) if type: cmd.extend(['-t', type]) if range: cmd.extend(['-l', range]) cmd.append(path) ret = not __salt__['cmd.retcode'](cmd, python_shell=False) if ret: return get_selinux_context(path) else: return ret def source_list(source, source_hash, saltenv): ''' Check the source list and return the source to use CLI Example: .. code-block:: bash salt '*' file.source_list salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' base ''' contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv) if contextkey in __context__: return __context__[contextkey] # get the master file list if isinstance(source, list): mfiles = [(f, saltenv) for f in __salt__['cp.list_master'](saltenv)] mdirs = [(d, saltenv) for d in __salt__['cp.list_master_dirs'](saltenv)] for single in source: if isinstance(single, dict): single = next(iter(single)) path, senv = salt.utils.url.parse(single) if senv: mfiles += [(f, senv) for f in __salt__['cp.list_master'](senv)] mdirs += [(d, senv) for d in __salt__['cp.list_master_dirs'](senv)] ret = None for single in source: if isinstance(single, dict): # check the proto, if it is http or ftp then download the file # to check, if it is salt then check the master list # if it is a local file, check if the file exists if len(single) != 1: continue single_src = next(iter(single)) single_hash = single[single_src] if single[single_src] else source_hash urlparsed_single_src = _urlparse(single_src) # Fix this for Windows if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_single_src.scheme.lower() in string.ascii_lowercase: urlparsed_single_src = _urlparse('file://' + single_src) proto = urlparsed_single_src.scheme if proto == 'salt': path, senv = salt.utils.url.parse(single_src) if not senv: senv = saltenv if (path, saltenv) in mfiles or (path, saltenv) in mdirs: ret = (single_src, single_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single_src, single_hash) break elif proto == 'file' and ( os.path.exists(urlparsed_single_src.netloc) or os.path.exists(urlparsed_single_src.path) or os.path.exists(os.path.join( urlparsed_single_src.netloc, urlparsed_single_src.path))): ret = (single_src, single_hash) break elif single_src.startswith(os.sep) and os.path.exists(single_src): ret = (single_src, single_hash) break elif isinstance(single, six.string_types): path, senv = salt.utils.url.parse(single) if not senv: senv = saltenv if (path, senv) in mfiles or (path, senv) in mdirs: ret = (single, source_hash) break urlparsed_src = _urlparse(single) if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_src.scheme.lower() in string.ascii_lowercase: urlparsed_src = _urlparse('file://' + single) proto = urlparsed_src.scheme if proto == 'file' and ( os.path.exists(urlparsed_src.netloc) or os.path.exists(urlparsed_src.path) or os.path.exists(os.path.join( urlparsed_src.netloc, urlparsed_src.path))): ret = (single, source_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single, source_hash) break elif single.startswith(os.sep) and os.path.exists(single): ret = (single, source_hash) break if ret is None: # None of the list items matched raise CommandExecutionError( 'none of the specified sources were found' ) else: ret = (source, source_hash) __context__[contextkey] = ret return ret def apply_template_on_contents( contents, template, context, defaults, saltenv): ''' Return the contents after applying the templating engine contents template string template template format context Overrides default context variables passed to the template. defaults Default context passed to the template. CLI Example: .. code-block:: bash salt '*' file.apply_template_on_contents \\ contents='This is a {{ template }} string.' \\ template=jinja \\ "context={}" "defaults={'template': 'cool'}" \\ saltenv=base ''' if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) # Apply templating contents = salt.utils.templates.TEMPLATE_REGISTRY[template]( contents, from_str=True, to_str=True, context=context_dict, saltenv=saltenv, grains=__opts__['grains'], pillar=__pillar__, salt=__salt__, opts=__opts__)['data'] if six.PY2: contents = contents.encode('utf-8') elif six.PY3 and isinstance(contents, bytes): # bytes -> str contents = contents.decode('utf-8') else: ret = {} ret['result'] = False ret['comment'] = ('Specified template format {0} is not supported' ).format(template) return ret return contents def get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify=False, **kwargs): ''' Return the managed file data for file.managed name location where the file lives on the server template template format source managed source file source_hash hash of the source file source_hash_name When ``source_hash`` refers to a remote file, this specifies the filename to look for in that file. .. versionadded:: 2016.3.5 user Owner of file group Group owner of file mode Permissions of file attrs Attributes of file .. versionadded:: 2018.3.0 context Variables to add to the template context defaults Default values of for context_dict skip_verify If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' file.get_managed /etc/httpd/conf.d/httpd.conf jinja salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' None root root '755' base None None ''' # Copy the file to the minion and templatize it sfn = '' source_sum = {} def _get_local_file_source_sum(path): ''' DRY helper for getting the source_sum value from a locally cached path. ''' return {'hsum': get_hash(path, form='sha256'), 'hash_type': 'sha256'} # If we have a source defined, let's figure out what the hash is if source: urlparsed_source = _urlparse(source) if urlparsed_source.scheme in salt.utils.files.VALID_PROTOS: parsed_scheme = urlparsed_source.scheme else: parsed_scheme = '' parsed_path = os.path.join( urlparsed_source.netloc, urlparsed_source.path).rstrip(os.sep) unix_local_source = parsed_scheme in ('file', '') if parsed_scheme == '': parsed_path = sfn = source if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg elif parsed_scheme == 'file': sfn = parsed_path if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg if parsed_scheme and parsed_scheme.lower() in string.ascii_lowercase: parsed_path = ':'.join([parsed_scheme, parsed_path]) parsed_scheme = 'file' if parsed_scheme == 'salt': source_sum = __salt__['cp.hash_file'](source, saltenv) if not source_sum: return '', {}, 'Source file {0} not found in saltenv \'{1}\''.format(source, saltenv) elif not source_hash and unix_local_source: source_sum = _get_local_file_source_sum(parsed_path) elif not source_hash and source.startswith(os.sep): # This should happen on Windows source_sum = _get_local_file_source_sum(source) else: if not skip_verify: if source_hash: try: source_sum = get_source_sum(name, source, source_hash, source_hash_name, saltenv) except CommandExecutionError as exc: return '', {}, exc.strerror else: msg = ( 'Unable to verify upstream hash of source file {0}, ' 'please set source_hash or set skip_verify to True' .format(salt.utils.url.redact_http_basic_auth(source)) ) return '', {}, msg if source and (template or parsed_scheme in salt.utils.files.REMOTE_PROTOS): # Check if we have the template or remote file cached cache_refetch = False cached_dest = __salt__['cp.is_cached'](source, saltenv) if cached_dest and (source_hash or skip_verify): htype = source_sum.get('hash_type', 'sha256') cached_sum = get_hash(cached_dest, form=htype) if skip_verify: # prev: if skip_verify or cached_sum == source_sum['hsum']: # but `cached_sum == source_sum['hsum']` is elliptical as prev if sfn = cached_dest source_sum = {'hsum': cached_sum, 'hash_type': htype} elif cached_sum != source_sum.get('hsum', __opts__['hash_type']): cache_refetch = True else: sfn = cached_dest # If we didn't have the template or remote file, or the file has been # updated and the cache has to be refreshed, download the file. if not sfn or cache_refetch: try: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum.get('hsum')) except Exception as exc: # A 404 or other error code may raise an exception, catch it # and return a comment that will fail the calling state. _source = salt.utils.url.redact_http_basic_auth(source) return '', {}, 'Failed to cache {0}: {1}'.format(_source, exc) # If cache failed, sfn will be False, so do a truth check on sfn first # as invoking os.path.exists() on a bool raises a TypeError. if not sfn or not os.path.exists(sfn): _source = salt.utils.url.redact_http_basic_auth(source) return sfn, {}, 'Source file \'{0}\' not found'.format(_source) if sfn == name: raise SaltInvocationError( 'Source file cannot be the same as destination' ) if template: if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, name=name, source=source, user=user, group=group, mode=mode, attrs=attrs, saltenv=saltenv, context=context_dict, salt=__salt__, pillar=__pillar__, grains=__opts__['grains'], opts=__opts__, **kwargs) else: return sfn, {}, ('Specified template format {0} is not supported' ).format(template) if data['result']: sfn = data['data'] hsum = get_hash(sfn, form='sha256') source_sum = {'hash_type': 'sha256', 'hsum': hsum} else: __clean_tmp(sfn) return sfn, {}, data['data'] return sfn, source_sum, '' def extract_hash(hash_fn, hash_type='sha256', file_name='', source='', source_hash_name=None): ''' .. versionchanged:: 2016.3.5 Prior to this version, only the ``file_name`` argument was considered for filename matches in the hash file. This would be problematic for cases in which the user was relying on a remote checksum file that they do not control, and they wished to use a different name for that file on the minion from the filename on the remote server (and in the checksum file). For example, managing ``/tmp/myfile.tar.gz`` when the remote file was at ``https://mydomain.tld/different_name.tar.gz``. The :py:func:`file.managed <salt.states.file.managed>` state now also passes this function the source URI as well as the ``source_hash_name`` (if specified). In cases where ``source_hash_name`` is specified, it takes precedence over both the ``file_name`` and ``source``. When it is not specified, ``file_name`` takes precedence over ``source``. This allows for better capability for matching hashes. .. versionchanged:: 2016.11.0 File name and source URI matches are no longer disregarded when ``source_hash_name`` is specified. They will be used as fallback matches if there is no match to the ``source_hash_name`` value. This routine is called from the :mod:`file.managed <salt.states.file.managed>` state to pull a hash from a remote file. Regular expressions are used line by line on the ``source_hash`` file, to find a potential candidate of the indicated hash type. This avoids many problems of arbitrary file layout rules. It specifically permits pulling hash codes from debian ``*.dsc`` files. If no exact match of a hash and filename are found, then the first hash found (if any) will be returned. If no hashes at all are found, then ``None`` will be returned. For example: .. code-block:: yaml openerp_7.0-latest-1.tar.gz: file.managed: - name: /tmp/openerp_7.0-20121227-075624-1_all.deb - source: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.tar.gz - source_hash: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.dsc CLI Example: .. code-block:: bash salt '*' file.extract_hash /path/to/hash/file sha512 /etc/foo ''' hash_len = HASHES.get(hash_type) if hash_len is None: if hash_type: log.warning( 'file.extract_hash: Unsupported hash_type \'%s\', falling ' 'back to matching any supported hash_type', hash_type ) hash_type = '' hash_len_expr = '{0},{1}'.format(min(HASHES_REVMAP), max(HASHES_REVMAP)) else: hash_len_expr = six.text_type(hash_len) filename_separators = string.whitespace + r'\/' if source_hash_name: if not isinstance(source_hash_name, six.string_types): source_hash_name = six.text_type(source_hash_name) source_hash_name_idx = (len(source_hash_name) + 1) * -1 log.debug( 'file.extract_hash: Extracting %s hash for file matching ' 'source_hash_name \'%s\'', 'any supported' if not hash_type else hash_type, source_hash_name ) if file_name: if not isinstance(file_name, six.string_types): file_name = six.text_type(file_name) file_name_basename = os.path.basename(file_name) file_name_idx = (len(file_name_basename) + 1) * -1 if source: if not isinstance(source, six.string_types): source = six.text_type(source) urlparsed_source = _urlparse(source) source_basename = os.path.basename( urlparsed_source.path or urlparsed_source.netloc ) source_idx = (len(source_basename) + 1) * -1 basename_searches = [x for x in (file_name, source) if x] if basename_searches: log.debug( 'file.extract_hash: %s %s hash for file matching%s: %s', 'If no source_hash_name match found, will extract' if source_hash_name else 'Extracting', 'any supported' if not hash_type else hash_type, '' if len(basename_searches) == 1 else ' either of the following', ', '.join(basename_searches) ) partial = None found = {} with salt.utils.files.fopen(hash_fn, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line.strip()) hash_re = r'(?i)(?<![a-z0-9])([a-f0-9]{' + hash_len_expr + '})(?![a-z0-9])' hash_match = re.search(hash_re, line) matched = None if hash_match: matched_hsum = hash_match.group(1) if matched_hsum is not None: matched_type = HASHES_REVMAP.get(len(matched_hsum)) if matched_type is None: # There was a match, but it's not of the correct length # to match one of the supported hash types. matched = None else: matched = {'hsum': matched_hsum, 'hash_type': matched_type} if matched is None: log.debug( 'file.extract_hash: In line \'%s\', no %shash found', line, '' if not hash_type else hash_type + ' ' ) continue if partial is None: partial = matched def _add_to_matches(found, line, match_type, value, matched): log.debug( 'file.extract_hash: Line \'%s\' matches %s \'%s\'', line, match_type, value ) found.setdefault(match_type, []).append(matched) hash_matched = False if source_hash_name: if line.endswith(source_hash_name): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[source_hash_name_idx] in string.whitespace: _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source_hash_name) + r'\s+', line): _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True if file_name: if line.endswith(file_name_basename): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[file_name_idx] in filename_separators: _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(file_name) + r'\s+', line): _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True if source: if line.endswith(source_basename): # Same as above, we can't just do an rsplit here. try: if line[source_idx] in filename_separators: _add_to_matches(found, line, 'source', source, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source) + r'\s+', line): _add_to_matches(found, line, 'source', source, matched) hash_matched = True if not hash_matched: log.debug( 'file.extract_hash: Line \'%s\' contains %s hash ' '\'%s\', but line did not meet the search criteria', line, matched['hash_type'], matched['hsum'] ) for found_type, found_str in (('source_hash_name', source_hash_name), ('file_name', file_name), ('source', source)): if found_type in found: if len(found[found_type]) > 1: log.debug( 'file.extract_hash: Multiple %s matches for %s: %s', found_type, found_str, ', '.join( ['{0} ({1})'.format(x['hsum'], x['hash_type']) for x in found[found_type]] ) ) ret = found[found_type][0] log.debug( 'file.extract_hash: Returning %s hash \'%s\' as a match of %s', ret['hash_type'], ret['hsum'], found_str ) return ret if partial: log.debug( 'file.extract_hash: Returning the partially identified %s hash ' '\'%s\'', partial['hash_type'], partial['hsum'] ) return partial log.debug('file.extract_hash: No matches, returning None') return None def check_perms(name, ret, user, group, mode, attrs=None, follow_symlinks=False, seuser=None, serole=None, setype=None, serange=None): ''' .. versionchanged:: Neon Added selinux options Check the permissions on files, modify attributes and chown if needed. File attributes are only verified if lsattr(1) is installed. CLI Example: .. code-block:: bash salt '*' file.check_perms /etc/sudoers '{}' root root 400 ai .. versionchanged:: 2014.1.3 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': [], 'result': True} orig_comment = '' else: orig_comment = ret['comment'] ret['comment'] = [] # Check permissions perms = {} cur = stats(name, follow_symlinks=follow_symlinks) perms['luser'] = cur['user'] perms['lgroup'] = cur['group'] perms['lmode'] = salt.utils.files.normalize_mode(cur['mode']) is_dir = os.path.isdir(name) is_link = os.path.islink(name) if attrs is not None \ and not salt.utils.platform.is_windows() \ and not is_dir and not is_link: try: lattrs = lsattr(name) except SaltInvocationError: lattrs = None if lattrs is not None: # List attributes on file perms['lattrs'] = ''.join(lattrs.get(name, '')) # Remove attributes on file so changes can be enforced. if perms['lattrs']: chattr(name, operator='remove', attributes=perms['lattrs']) # user/group changes if needed, then check if it worked if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid(perms['luser']) ) or ( not salt.utils.platform.is_windows() and user != perms['luser'] ): perms['cuser'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid(perms['lgroup']) ) or ( not salt.utils.platform.is_windows() and group != perms['lgroup'] ): perms['cgroup'] = group if 'cuser' in perms or 'cgroup' in perms: if not __opts__['test']: if os.path.islink(name) and not follow_symlinks: chown_func = lchown else: chown_func = chown if user is None: user = perms['luser'] if group is None: group = perms['lgroup'] try: chown_func(name, user, group) # Python os.chown() does reset the suid and sgid, # that's why setting the right mode again is needed here. set_mode(name, mode) except OSError: ret['result'] = False if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid( get_user(name, follow_symlinks=follow_symlinks)) and user != '' ) or ( not salt.utils.platform.is_windows() and user != get_user(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['user'] = user else: ret['result'] = False ret['comment'].append('Failed to change user to {0}' .format(user)) elif 'cuser' in perms and user != '': ret['changes']['user'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid( get_group(name, follow_symlinks=follow_symlinks)) and user != '') or ( not salt.utils.platform.is_windows() and group != get_group(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['group'] = group else: ret['result'] = False ret['comment'].append('Failed to change group to {0}' .format(group)) elif 'cgroup' in perms and user != '': ret['changes']['group'] = group if not salt.utils.platform.is_windows() and not is_dir: # Replace attributes on file if it had been removed if perms.get('lattrs', ''): chattr(name, operator='add', attributes=perms['lattrs']) # Mode changes if needed if mode is not None: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: mode = salt.utils.files.normalize_mode(mode) if mode != perms['lmode']: if __opts__['test'] is True: ret['changes']['mode'] = mode else: set_mode(name, mode) if mode != salt.utils.files.normalize_mode(get_mode(name)): ret['result'] = False ret['comment'].append( 'Failed to change mode to {0}'.format(mode) ) else: ret['changes']['mode'] = mode # Modify attributes of file if needed if attrs is not None and not is_dir: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if diff_attrs[0] is not None or diff_attrs[1] is not None: if __opts__['test'] is True: ret['changes']['attrs'] = attrs else: if diff_attrs[0] is not None: chattr(name, operator="add", attributes=diff_attrs[0]) if diff_attrs[1] is not None: chattr(name, operator="remove", attributes=diff_attrs[1]) cmp_attrs = _cmp_attrs(name, attrs) if cmp_attrs[0] is not None or cmp_attrs[1] is not None: ret['result'] = False ret['comment'].append( 'Failed to change attributes to {0}'.format(attrs) ) else: ret['changes']['attrs'] = attrs # Set selinux attributes if needed if salt.utils.platform.is_linux() and (seuser or serole or setype or serange): selinux_error = False try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError: log.error('Unable to get current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to get selinux attributes' ) selinux_error = True if not selinux_error: requested_seuser = None requested_serole = None requested_setype = None requested_serange = None # Only set new selinux variables if updates are needed if seuser and seuser != current_seuser: requested_seuser = seuser if serole and serole != current_serole: requested_serole = serole if setype and setype != current_setype: requested_setype = setype if serange and serange != current_serange: requested_serange = serange if requested_seuser or requested_serole or requested_setype or requested_serange: # selinux updates needed, prep changes output selinux_change_new = '' selinux_change_orig = '' if requested_seuser: selinux_change_new += "User: {0} ".format(requested_seuser) selinux_change_orig += "User: {0} ".format(current_seuser) if requested_serole: selinux_change_new += "Role: {0} ".format(requested_serole) selinux_change_orig += "Role: {0} ".format(current_serole) if requested_setype: selinux_change_new += "Type: {0} ".format(requested_setype) selinux_change_orig += "Type: {0} ".format(current_setype) if requested_serange: selinux_change_new += "Range: {0} ".format(requested_serange) selinux_change_orig += "Range: {0} ".format(current_serange) if __opts__['test']: ret['comment'] = 'File {0} selinux context to be updated'.format(name) ret['result'] = None ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} else: try: # set_selinux_context requires type to be set on any other change if (requested_seuser or requested_serole or requested_serange) and not requested_setype: requested_setype = current_setype result = set_selinux_context(name, user=requested_seuser, role=requested_serole, type=requested_setype, range=requested_serange, persist=True) log.debug('selinux set result: %s', result) current_seuser, current_serole, current_setype, current_serange = result.split(':') except ValueError: log.error('Unable to set current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to set selinux attributes' ) selinux_error = True if not selinux_error: ret['comment'].append('The file {0} is set to be changed'.format(name)) if requested_seuser: if current_seuser != requested_seuser: ret['comment'].append("Unable to update seuser context") ret['result'] = False if requested_serole: if current_serole != requested_serole: ret['comment'].append("Unable to update serole context") ret['result'] = False if requested_setype: if current_setype != requested_setype: ret['comment'].append("Unable to update setype context") ret['result'] = False if requested_serange: if current_serange != requested_serange: ret['comment'].append("Unable to update serange context") ret['result'] = False ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} # Only combine the comment list into a string # after all comments are added above if isinstance(orig_comment, six.string_types): if orig_comment: ret['comment'].insert(0, orig_comment) ret['comment'] = '; '.join(ret['comment']) # Set result to None at the very end of the function, # after all changes have been recorded above if __opts__['test'] is True and ret['changes']: ret['result'] = None return ret, perms def check_managed( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Check to see what changes need to be made for a file CLI Example: .. code-block:: bash salt '*' file.check_managed /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) if comments: __clean_tmp(sfn) return False, comments changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) # Ignore permission for files written temporary directories # Files in any path will still be set correctly using get_managed() if name.startswith(tempfile.gettempdir()): for key in ['user', 'group', 'mode']: changes.pop(key, None) __clean_tmp(sfn) if changes: log.info(changes) comments = ['The following values are set to be changed:\n'] comments.extend('{0}: {1}\n'.format(key, val) for key, val in six.iteritems(changes)) return None, ''.join(comments) return True, 'The file {0} is in the correct state'.format(name) def check_managed_changes( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, keep_mode=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Return a dictionary of what changes need to be made for a file .. versionchanged:: Neon selinux attributes added CLI Example: .. code-block:: bash salt '*' file.check_managed_changes /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if comments: __clean_tmp(sfn) raise CommandExecutionError(comments) if sfn and source and keep_mode: if _urlparse(source).scheme in ('salt', 'file') \ or source.startswith('/'): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) __clean_tmp(sfn) return changes def check_file_meta( name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents=None, seuser=None, serole=None, setype=None, serange=None): ''' Check for the changes in the file metadata. CLI Example: .. code-block:: bash salt '*' file.check_file_meta /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' base .. note:: Supported hash types include sha512, sha384, sha256, sha224, sha1, and md5. name Path to file destination sfn Template-processed source file contents source URL to file source source_sum File checksum information as a dictionary .. code-block:: yaml {hash_type: md5, hsum: <md5sum>} user Destination file user owner group Destination file group owner mode Destination file permissions mode attrs Destination file attributes .. versionadded:: 2018.3.0 saltenv Salt environment used to resolve source files contents File contents seuser selinux user attribute .. versionadded:: Neon serole selinux role attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon ''' changes = {} if not source_sum: source_sum = dict() try: lstats = stats(name, hash_type=source_sum.get('hash_type', None), follow_symlinks=False) except CommandExecutionError: lstats = {} if not lstats: changes['newfile'] = name return changes if 'hsum' in source_sum: if source_sum['hsum'] != lstats['sum']: if not sfn and source: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum['hsum']) if sfn: try: changes['diff'] = get_diff( name, sfn, template=True, show_filenames=False) except CommandExecutionError as exc: changes['diff'] = exc.strerror else: changes['sum'] = 'Checksum differs' if contents is not None: # Write a tempfile with the static contents tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'w') as tmp_: tmp_.write(salt.utils.stringutils.to_str(contents)) # Compare the static contents with the named file try: differences = get_diff(name, tmp, show_filenames=False) except CommandExecutionError as exc: log.error('Failed to diff files: %s', exc) differences = exc.strerror __clean_tmp(tmp) if differences: if __salt__['config.option']('obfuscate_templates'): changes['diff'] = '<Obfuscated Template>' else: changes['diff'] = differences if not salt.utils.platform.is_windows(): # Check owner if (user is not None and user != lstats['user'] and user != lstats['uid']): changes['user'] = user # Check group if (group is not None and group != lstats['group'] and group != lstats['gid']): changes['group'] = group # Normalize the file mode smode = salt.utils.files.normalize_mode(lstats['mode']) mode = salt.utils.files.normalize_mode(mode) if mode is not None and mode != smode: changes['mode'] = mode if attrs: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if attrs is not None \ and (diff_attrs[0] is not None or diff_attrs[1] is not None): changes['attrs'] = attrs # Check selinux if seuser or serole or setype or serange: try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError as exc: log.error('Unable to get current selinux attributes') changes['selinux'] = exc.strerror if seuser and seuser != current_seuser: changes['selinux'] = {"user": seuser} if serole and serole != current_serole: changes['selinux'] = {"role": serole} if setype and setype != current_setype: changes['selinux'] = {"type": setype} if serange and serange != current_serange: changes['selinux'] = {"range": serange} return changes def get_diff(file1, file2, saltenv='base', show_filenames=True, show_changes=True, template=False, source_hash_file1=None, source_hash_file2=None): ''' Return unified diff of two files file1 The first file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, thuis had to be a file local to the minion. file2 The second file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, this had to be a file on the salt fileserver (i.e. ``salt://somefile.txt``) show_filenames : True Set to ``False`` to hide the filenames in the top two lines of the diff. show_changes : True If set to ``False``, and there are differences, then instead of a diff a simple message stating that show_changes is set to ``False`` will be returned. template : False Set to ``True`` if two templates are being compared. This is not useful except for within states, with the ``obfuscate_templates`` option set to ``True``. .. versionadded:: 2018.3.0 source_hash_file1 If ``file1`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 source_hash_file2 If ``file2`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 CLI Examples: .. code-block:: bash salt '*' file.get_diff /home/fred/.vimrc salt://users/fred/.vimrc salt '*' file.get_diff /tmp/foo.txt /tmp/bar.txt ''' files = (file1, file2) source_hashes = (source_hash_file1, source_hash_file2) paths = [] errors = [] for filename, source_hash in zip(files, source_hashes): try: # Local file paths will just return the same path back when passed # to cp.cache_file. cached_path = __salt__['cp.cache_file'](filename, saltenv, source_hash=source_hash) if cached_path is False: errors.append( 'File {0} not found'.format( salt.utils.stringutils.to_unicode(filename) ) ) continue paths.append(cached_path) except MinionError as exc: errors.append(salt.utils.stringutils.to_unicode(exc.__str__())) continue if errors: raise CommandExecutionError( 'Failed to cache one or more files', info=errors ) args = [] for filename in paths: try: with salt.utils.files.fopen(filename, 'rb') as fp_: args.append(fp_.readlines()) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read {0}: {1}'.format( salt.utils.stringutils.to_unicode(filename), exc.strerror ) ) if args[0] != args[1]: if template and __salt__['config.option']('obfuscate_templates'): ret = '<Obfuscated Template>' elif not show_changes: ret = '<show_changes=False>' else: bdiff = _binary_replace(*paths) # pylint: disable=no-value-for-parameter if bdiff: ret = bdiff else: if show_filenames: args.extend(paths) ret = __utils__['stringutils.get_diff'](*args) return ret return '' def manage_file(name, sfn, ret, source, source_sum, user, group, mode, attrs, saltenv, backup, makedirs=False, template=None, # pylint: disable=W0613 show_changes=True, contents=None, dir_mode=None, follow_symlinks=True, skip_verify=False, keep_mode=False, encoding=None, encoding_errors='strict', seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Checks the destination against what was retrieved with get_managed and makes the appropriate modifications (if necessary). name location to place the file sfn location of cached file on the minion This is the path to the file stored on the minion. This file is placed on the minion using cp.cache_file. If the hash sum of that file matches the source_sum, we do not transfer the file to the minion again. This file is then grabbed and if it has template set, it renders the file to be placed into the correct place on the system using salt.files.utils.copyfile() ret The initial state return data structure. Pass in ``None`` to use the default structure. source file reference on the master source_sum sum hash for source user user owner group group owner backup backup_mode attrs attributes to be set on file: '' means remove all of them .. versionadded:: 2018.3.0 makedirs make directories if they do not exist template format of templating show_changes Include diff in state return contents: contents to be placed in the file dir_mode mode for directories created with makedirs skip_verify : False If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 keep_mode : False If ``True``, and the ``source`` is a file from the Salt fileserver (or a local file on the minion), the mode of the destination file will be set to the mode of the source file. .. note:: keep_mode does not work with salt-ssh. As a consequence of how the files are transferred to the minion, and the inability to connect back to the master with salt-ssh, salt is unable to stat the file as it exists on the fileserver and thus cannot mirror the mode on the salt-ssh minion encoding If specified, then the specified encoding will be used. Otherwise, the file will be encoded using the system locale (usually UTF-8). See https://docs.python.org/3/library/codecs.html#standard-encodings for the list of available encodings. .. versionadded:: 2017.7.0 encoding_errors : 'strict' Default is ```'strict'```. See https://docs.python.org/2/library/codecs.html#codec-base-classes for the error handling schemes. .. versionadded:: 2017.7.0 seuser selinux user attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon CLI Example: .. code-block:: bash salt '*' file.manage_file /etc/httpd/conf.d/httpd.conf '' '{}' salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' '' base '' .. versionchanged:: 2014.7.0 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if source: if not sfn: # File is not present, cache it sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) htype = source_sum.get('hash_type', __opts__['hash_type']) # Recalculate source sum now that file has been cached source_sum = { 'hash_type': htype, 'hsum': get_hash(sfn, form=htype) } if keep_mode: if _urlparse(source).scheme in ('salt', 'file', ''): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) # Check changes if the target file exists if os.path.isfile(name) or os.path.islink(name): if os.path.islink(name) and follow_symlinks: real_name = os.path.realpath(name) else: real_name = name # Only test the checksums on files with managed contents if source and not (not follow_symlinks and os.path.islink(real_name)): name_sum = get_hash(real_name, source_sum.get('hash_type', __opts__['hash_type'])) else: name_sum = None # Check if file needs to be replaced if source and (name_sum is None or source_sum.get('hsum', __opts__['hash_type']) != name_sum): if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server or local # source, and we are not skipping checksum verification, then # verify that it matches the specified checksum. if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3}). If the \'source_hash\' value ' 'refers to a remote file with multiple possible ' 'matches, then it may be necessary to set ' '\'source_hash_name\'.'.format( source_sum['hash_type'], source, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # Print a diff equivalent to diff -u old new if __salt__['config.option']('obfuscate_templates'): ret['changes']['diff'] = '<Obfuscated Template>' elif not show_changes: ret['changes']['diff'] = '<show_changes=False>' else: try: ret['changes']['diff'] = get_diff( real_name, sfn, show_filenames=False) except CommandExecutionError as exc: ret['changes']['diff'] = exc.strerror # Pre requisites are met, and the file needs to be replaced, do it try: salt.utils.files.copyfile(sfn, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) try: differences = get_diff( real_name, tmp, show_filenames=False, show_changes=show_changes, template=True) except CommandExecutionError as exc: ret.setdefault('warnings', []).append( 'Failed to detect changes to file: {0}'.format(exc.strerror) ) differences = '' if differences: ret['changes']['diff'] = differences # Pre requisites are met, the file needs to be replaced, do it try: salt.utils.files.copyfile(tmp, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(tmp) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) __clean_tmp(tmp) # Check for changing symlink to regular file here if os.path.islink(name) and not follow_symlinks: if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret try: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) ret['changes']['diff'] = \ 'Replace symbolic link with regular file' if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, follow_symlinks, seuser=seuser, serole=serole, setype=setype, serange=serange) if ret['changes']: ret['comment'] = 'File {0} updated'.format( salt.utils.data.decode(name) ) elif not ret['changes'] and ret['result']: ret['comment'] = 'File {0} is in the correct state'.format( salt.utils.data.decode(name) ) if sfn: __clean_tmp(sfn) return ret else: # target file does not exist contain_dir = os.path.dirname(name) def _set_mode_and_make_dirs(name, dir_mode, mode, user, group): # check for existence of windows drive letter if salt.utils.platform.is_windows(): drive, _ = os.path.splitdrive(name) if drive and not os.path.exists(drive): __clean_tmp(sfn) return _error(ret, '{0} drive not present'.format(drive)) if dir_mode is None and mode is not None: # Add execute bit to each nonzero digit in the mode, if # dir_mode was not specified. Otherwise, any # directories created with makedirs_() below can't be # listed via a shell. mode_list = [x for x in six.text_type(mode)][-3:] for idx in range(len(mode_list)): if mode_list[idx] != '0': mode_list[idx] = six.text_type(int(mode_list[idx]) | 1) dir_mode = ''.join(mode_list) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 makedirs_( path=name, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: makedirs_(name, user=user, group=group, mode=dir_mode) if source: # Apply the new file if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # It is a new file, set the diff accordingly ret['changes']['diff'] = 'New file' if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') else: # source != True if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') # Create the file, user rw-only if mode will be set to prevent # a small security race problem before the permissions are set with salt.utils.files.set_umask(0o077 if mode else None): # Create a new file when test is False and source is None if contents is None: if not __opts__['test']: if touch(name): ret['changes']['new'] = 'file {0} created'.format(name) ret['comment'] = 'Empty file' else: return _error( ret, 'Empty file {0} not created'.format(name) ) else: if not __opts__['test']: if touch(name): ret['changes']['diff'] = 'New file' else: return _error( ret, 'File {0} not created'.format(name) ) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) # Copy into place salt.utils.files.copyfile(tmp, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(tmp) # Now copy the file contents if there is a source file elif sfn: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(sfn) # This is a new file, if no mode specified, use the umask to figure # out what mode to use for the new file. if mode is None and not salt.utils.platform.is_windows(): # Get current umask mask = salt.utils.files.get_umask() # Calculate the mode value that results from the umask mode = oct((0o777 ^ mask) & 0o666) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, seuser=seuser, serole=serole, setype=setype, serange=serange) if not ret['comment']: ret['comment'] = 'File ' + name + ' updated' if __opts__['test']: ret['comment'] = 'File ' + name + ' not updated' elif not ret['changes'] and ret['result']: ret['comment'] = 'File ' + name + ' is in the correct state' if sfn: __clean_tmp(sfn) return ret def mkdir(dir_path, user=None, group=None, mode=None): ''' Ensure that a directory is available. CLI Example: .. code-block:: bash salt '*' file.mkdir /opt/jetty/context ''' dir_path = os.path.expanduser(dir_path) directory = os.path.normpath(dir_path) if not os.path.isdir(directory): # If a caller such as managed() is invoked with makedirs=True, make # sure that any created dirs are created with the same user and group # to follow the principal of least surprise method. makedirs_perms(directory, user, group, mode) return True def makedirs_(path, user=None, group=None, mode=None): ''' Ensure that the directory containing this path is available. .. note:: The path must end with a trailing slash otherwise the directory/directories will be created up to the parent directory. For example if path is ``/opt/code``, then it would be treated as ``/opt/`` but if the path ends with a trailing slash like ``/opt/code/``, then it would be treated as ``/opt/code/``. CLI Example: .. code-block:: bash salt '*' file.makedirs /opt/code/ ''' path = os.path.expanduser(path) if mode: mode = salt.utils.files.normalize_mode(mode) # walk up the directory structure until we find the first existing # directory dirname = os.path.normpath(os.path.dirname(path)) if os.path.isdir(dirname): # There's nothing for us to do msg = 'Directory \'{0}\' already exists'.format(dirname) log.debug(msg) return msg if os.path.exists(dirname): msg = 'The path \'{0}\' already exists and is not a directory'.format( dirname ) log.debug(msg) return msg directories_to_create = [] while True: if os.path.isdir(dirname): break directories_to_create.append(dirname) current_dirname = dirname dirname = os.path.dirname(dirname) if current_dirname == dirname: raise SaltInvocationError( 'Recursive creation for path \'{0}\' would result in an ' 'infinite loop. Please use an absolute path.'.format(dirname) ) # create parent directories from the topmost to the most deeply nested one directories_to_create.reverse() for directory_to_create in directories_to_create: # all directories have the user, group and mode set!! log.debug('Creating directory: %s', directory_to_create) mkdir(directory_to_create, user=user, group=group, mode=mode) def makedirs_perms(name, user=None, group=None, mode='0755'): ''' Taken and modified from os.makedirs to set user, group and mode for each directory created. CLI Example: .. code-block:: bash salt '*' file.makedirs_perms /opt/code ''' name = os.path.expanduser(name) path = os.path head, tail = path.split(name) if not tail: head, tail = path.split(head) if head and tail and not path.exists(head): try: makedirs_perms(head, user, group, mode) except OSError as exc: # be happy if someone already created the path if exc.errno != errno.EEXIST: raise if tail == os.curdir: # xxx/newdir/. exists if xxx/newdir exists return os.mkdir(name) check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) def get_devmm(name): ''' Get major/minor info from a device CLI Example: .. code-block:: bash salt '*' file.get_devmm /dev/chr ''' name = os.path.expanduser(name) if is_chrdev(name) or is_blkdev(name): stat_structure = os.stat(name) return ( os.major(stat_structure.st_rdev), os.minor(stat_structure.st_rdev)) else: return (0, 0) def is_chrdev(name): ''' Check if a file exists and is a character device. CLI Example: .. code-block:: bash salt '*' file.is_chrdev /dev/chr ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the character device does not exist in the first place return False else: raise return stat.S_ISCHR(stat_structure.st_mode) def mknod_chrdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a character device. CLI Example: .. code-block:: bash salt '*' file.mknod_chrdev /dev/chr 180 31 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating character device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFCHR, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created character device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_blkdev(name): ''' Check if a file exists and is a block device. CLI Example: .. code-block:: bash salt '*' file.is_blkdev /dev/blk ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the block device does not exist in the first place return False else: raise return stat.S_ISBLK(stat_structure.st_mode) def mknod_blkdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a block device. CLI Example: .. code-block:: bash salt '*' file.mknod_blkdev /dev/blk 8 999 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating block device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFBLK, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created block device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_fifo(name): ''' Check if a file exists and is a FIFO. CLI Example: .. code-block:: bash salt '*' file.is_fifo /dev/fifo ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the fifo does not exist in the first place return False else: raise return stat.S_ISFIFO(stat_structure.st_mode) def mknod_fifo(name, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a FIFO pipe. CLI Example: .. code-block:: bash salt '*' file.mknod_fifo /dev/fifo ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating FIFO name: %s', name) try: if __opts__['test']: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = None else: if os.mkfifo(name, int(six.text_type(mode).lstrip('0Oo'), 8)) is None: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created fifo check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def mknod(name, ntype, major=0, minor=0, user=None, group=None, mode='0600'): ''' .. versionadded:: 0.17.0 Create a block device, character device, or fifo pipe. Identical to the gnu mknod. CLI Examples: .. code-block:: bash salt '*' file.mknod /dev/chr c 180 31 salt '*' file.mknod /dev/blk b 8 999 salt '*' file.nknod /dev/fifo p ''' ret = False makedirs_(name, user, group) if ntype == 'c': ret = mknod_chrdev(name, major, minor, user, group, mode) elif ntype == 'b': ret = mknod_blkdev(name, major, minor, user, group, mode) elif ntype == 'p': ret = mknod_fifo(name, user, group, mode) else: raise SaltInvocationError( 'Node type unavailable: \'{0}\'. Available node types are ' 'character (\'c\'), block (\'b\'), and pipe (\'p\').'.format(ntype) ) return ret def list_backups(path, limit=None): ''' .. versionadded:: 0.17.0 Lists the previous versions of a file backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups /foo/bar/baz.txt ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows src_dir = parent_dir.replace(':', '_') else: src_dir = parent_dir[1:] # Figure out full path of location of backup file in minion cache bkdir = os.path.join(bkroot, src_dir) if not os.path.isdir(bkdir): return {} files = {} for fname in [x for x in os.listdir(bkdir) if os.path.isfile(os.path.join(bkdir, x))]: if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows strpfmt = '{0}_%a_%b_%d_%H-%M-%S_%f_%Y'.format(basename) else: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(fname, strpfmt) except ValueError: # File didn't match the strp format string, so it's not a backup # for this file. Move on to the next one. continue if salt.utils.platform.is_windows(): str_format = '%a %b %d %Y %H-%M-%S.%f' else: str_format = '%a %b %d %Y %H:%M:%S.%f' files.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime(str_format) location = os.path.join(bkdir, fname) files[timestamp]['Size'] = os.stat(location).st_size files[timestamp]['Location'] = location return dict(list(zip( list(range(len(files))), [files[x] for x in sorted(files, reverse=True)[:limit]] ))) list_backup = salt.utils.functools.alias_function(list_backups, 'list_backup') def list_backups_dir(path, limit=None): ''' Lists the previous versions of a directory backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The directory on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups_dir /foo/bar/baz/ ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups_dir: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) # Figure out full path of location of backup folder in minion cache bkdir = os.path.join(bkroot, parent_dir[1:]) if not os.path.isdir(bkdir): return {} files = {} f = dict([(i, len(list(n))) for i, n in itertools.groupby([x.split("_")[0] for x in sorted(os.listdir(bkdir))])]) ff = os.listdir(bkdir) for i, n in six.iteritems(f): ssfile = {} for x in sorted(ff): basename = x.split('_')[0] if i == basename: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(x, strpfmt) except ValueError: # Folder didn't match the strp format string, so it's not a backup # for this folder. Move on to the next one. continue ssfile.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime('%a %b %d %Y %H:%M:%S.%f') location = os.path.join(bkdir, x) ssfile[timestamp]['Size'] = os.stat(location).st_size ssfile[timestamp]['Location'] = location sfiles = dict(list(zip(list(range(n)), [ssfile[x] for x in sorted(ssfile, reverse=True)[:limit]]))) sefiles = {i: sfiles} files.update(sefiles) return files def restore_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Restore a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to restore, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.restore_backup /foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) # Note: This only supports minion backups, so this function will need to be # modified if/when master backups are implemented. ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret salt.utils.files.backup_minion(path, _get_bkroot()) try: shutil.copyfile(backup['Location'], path) except IOError as exc: ret['comment'] = \ 'Unable to restore {0} to {1}: ' \ '{2}'.format(backup['Location'], path, exc) return ret else: ret['result'] = True ret['comment'] = 'Successfully restored {0} to ' \ '{1}'.format(backup['Location'], path) # Try to set proper ownership if not salt.utils.platform.is_windows(): try: fstat = os.stat(path) except (OSError, IOError): ret['comment'] += ', but was unable to set ownership' else: os.chown(path, fstat.st_uid, fstat.st_gid) return ret def delete_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Delete a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to delete, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.delete_backup /var/cache/salt/minion/file_backup/home/foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret try: os.remove(backup['Location']) except IOError as exc: ret['comment'] = 'Unable to remove {0}: {1}'.format(backup['Location'], exc) else: ret['result'] = True ret['comment'] = 'Successfully removed {0}'.format(backup['Location']) return ret remove_backup = salt.utils.functools.alias_function(delete_backup, 'remove_backup') def grep(path, pattern, *opts): ''' Grep for a string in the specified file .. note:: This function's return value is slated for refinement in future versions of Salt path Path to the file to be searched .. note:: Globbing is supported (i.e. ``/var/log/foo/*.log``, but if globbing is being used then the path should be quoted to keep the shell from attempting to expand the glob expression. pattern Pattern to match. For example: ``test``, or ``a[0-5]`` opts Additional command-line flags to pass to the grep command. For example: ``-v``, or ``-i -B2`` .. note:: The options should come after a double-dash (as shown in the examples below) to keep Salt's own argument parser from interpreting them. CLI Example: .. code-block:: bash salt '*' file.grep /etc/passwd nobody salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i -B2 salt '*' file.grep "/etc/sysconfig/network-scripts/*" ipaddr -- -i -l ''' path = os.path.expanduser(path) # Backup the path in case the glob returns nothing _path = path path = glob.glob(path) # If the list is empty no files exist # so we revert back to the original path # so the result is an error. if not path: path = _path split_opts = [] for opt in opts: try: split = salt.utils.args.shlex_split(opt) except AttributeError: split = salt.utils.args.shlex_split(six.text_type(opt)) if len(split) > 1: raise SaltInvocationError( 'Passing multiple command line arguments in a single string ' 'is not supported, please pass the following arguments ' 'separately: {0}'.format(opt) ) split_opts.extend(split) if isinstance(path, list): cmd = ['grep'] + split_opts + [pattern] + path else: cmd = ['grep'] + split_opts + [pattern, path] try: ret = __salt__['cmd.run_all'](cmd, python_shell=False) except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return ret def open_files(by_pid=False): ''' Return a list of all physical open files on the system. CLI Examples: .. code-block:: bash salt '*' file.open_files salt '*' file.open_files by_pid=True ''' # First we collect valid PIDs pids = {} procfs = os.listdir('/proc/') for pfile in procfs: try: pids[int(pfile)] = [] except ValueError: # Not a valid PID, move on pass # Then we look at the open files for each PID files = {} for pid in pids: ppath = '/proc/{0}'.format(pid) try: tids = os.listdir('{0}/task'.format(ppath)) except OSError: continue # Collect the names of all of the file descriptors fd_ = [] #try: # fd_.append(os.path.realpath('{0}/task/{1}exe'.format(ppath, tid))) #except Exception: # pass for fpath in os.listdir('{0}/fd'.format(ppath)): fd_.append('{0}/fd/{1}'.format(ppath, fpath)) for tid in tids: try: fd_.append( os.path.realpath('{0}/task/{1}/exe'.format(ppath, tid)) ) except OSError: continue for tpath in os.listdir('{0}/task/{1}/fd'.format(ppath, tid)): fd_.append('{0}/task/{1}/fd/{2}'.format(ppath, tid, tpath)) fd_ = sorted(set(fd_)) # Loop through file descriptors and return useful data for each file for fdpath in fd_: # Sometimes PIDs and TIDs disappear before we can query them try: name = os.path.realpath(fdpath) # Running stat on the file cuts out all of the sockets and # deleted files from the list os.stat(name) except OSError: continue if name not in files: files[name] = [pid] else: # We still want to know which PIDs are using each file files[name].append(pid) files[name] = sorted(set(files[name])) pids[pid].append(name) pids[pid] = sorted(set(pids[pid])) if by_pid: return pids return files def pardir(): ''' Return the relative parent directory path symbol for underlying OS .. versionadded:: 2014.7.0 This can be useful when constructing Salt Formulas. .. code-block:: jinja {% set pardir = salt['file.pardir']() %} {% set final_path = salt['file.join']('subdir', pardir, 'confdir') %} CLI Example: .. code-block:: bash salt '*' file.pardir ''' return os.path.pardir def normpath(path): ''' Returns Normalize path, eliminating double slashes, etc. .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.normpath'](tpldir + '/../vars.jinja') import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.normpath 'a/b/c/..' ''' return os.path.normpath(path) def basename(path): ''' Returns the final component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- set filename = salt['file.basename'](source_file) %} CLI Example: .. code-block:: bash salt '*' file.basename 'test/test.config' ''' return os.path.basename(path) def dirname(path): ''' Returns the directory component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.dirname'](tpldir) + '/vars.jinja' import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.dirname 'test/path/filename.config' ''' return os.path.dirname(path) def join(*args): ''' Return a normalized file system path for the underlying OS .. versionadded:: 2014.7.0 This can be useful at the CLI but is frequently useful when scripting combining path variables: .. code-block:: jinja {% set www_root = '/var' %} {% set app_dir = 'myapp' %} myapp_config: file: - managed - name: {{ salt['file.join'](www_root, app_dir, 'config.yaml') }} CLI Example: .. code-block:: bash salt '*' file.join '/' 'usr' 'local' 'bin' ''' return os.path.join(*args) def move(src, dst): ''' Move a file or directory CLI Example: .. code-block:: bash salt '*' file.move /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('Source path must be absolute.') if not os.path.isabs(dst): raise SaltInvocationError('Destination path must be absolute.') ret = { 'result': True, 'comment': "'{0}' moved to '{1}'".format(src, dst), } try: shutil.move(src, dst) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move '{0}' to '{1}': {2}".format(src, dst, exc) ) return ret def diskusage(path): ''' Recursively calculate disk usage of path and return it in bytes CLI Example: .. code-block:: bash salt '*' file.diskusage /path/to/check ''' total_size = 0 seen = set() if os.path.isfile(path): stat_structure = os.stat(path) ret = stat_structure.st_size return ret for dirpath, dirnames, filenames in salt.utils.path.os_walk(path): for f in filenames: fp = os.path.join(dirpath, f) try: stat_structure = os.stat(fp) except OSError: continue if stat_structure.st_ino in seen: continue seen.add(stat_structure.st_ino) total_size += stat_structure.st_size ret = total_size return ret
saltstack/salt
salt/modules/file.py
set_mode
python
def set_mode(path, mode): ''' Set the mode of a file path file or directory of which to set the mode mode mode to set the path to CLI Example: .. code-block:: bash salt '*' file.set_mode /etc/passwd 0644 ''' path = os.path.expanduser(path) mode = six.text_type(mode).lstrip('0Oo') if not mode: mode = '0' if not os.path.exists(path): raise CommandExecutionError('{0}: File not found'.format(path)) try: os.chmod(path, int(mode, 8)) except Exception: return 'Invalid Mode ' + mode return get_mode(path)
Set the mode of a file path file or directory of which to set the mode mode mode to set the path to CLI Example: .. code-block:: bash salt '*' file.set_mode /etc/passwd 0644
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L369-L396
[ "def get_mode(path, follow_symlinks=True):\n '''\n Return the mode of a file\n\n path\n file or directory of which to get the mode\n\n follow_symlinks\n indicated if symlinks should be followed\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' file.get_mode /etc/passwd\n\n .. versionchanged:: 2014.1.0\n ``follow_symlinks`` option added\n '''\n return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('mode', '')\n" ]
# -*- coding: utf-8 -*- ''' Manage information about regular files, directories, and special files on the minion, set/read user, group, mode, and data ''' # TODO: We should add the capability to do u+r type operations here # some time in the future from __future__ import absolute_import, print_function, unicode_literals # Import python libs import datetime import errno import fnmatch import io import itertools import logging import operator import os import re import shutil import stat import string import sys import tempfile import time import glob import hashlib import mmap from collections import Iterable, Mapping from functools import reduce # pylint: disable=redefined-builtin # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import range, zip from salt.ext.six.moves.urllib.parse import urlparse as _urlparse # pylint: enable=import-error,no-name-in-module,redefined-builtin try: import grp import pwd except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.atomicfile import salt.utils.data import salt.utils.dictupdate import salt.utils.filebuffer import salt.utils.files import salt.utils.find import salt.utils.functools import salt.utils.hashutils import salt.utils.itertools import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.templates import salt.utils.url import salt.utils.user from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError, get_error_message as _get_error_message from salt.utils.files import HASHES, HASHES_REVMAP log = logging.getLogger(__name__) __func_alias__ = { 'makedirs_': 'makedirs' } def __virtual__(): ''' Only work on POSIX-like systems ''' # win_file takes care of windows if salt.utils.platform.is_windows(): return ( False, 'The file execution module cannot be loaded: only available on ' 'non-Windows systems - use win_file instead.' ) return True def __clean_tmp(sfn): ''' Clean out a template temp file ''' if sfn.startswith(os.path.join(tempfile.gettempdir(), salt.utils.files.TEMPFILE_PREFIX)): # Don't remove if it exists in file_roots (any saltenv) all_roots = itertools.chain.from_iterable( six.itervalues(__opts__['file_roots'])) in_roots = any(sfn.startswith(root) for root in all_roots) # Only clean up files that exist if os.path.exists(sfn) and not in_roots: os.remove(sfn) def _error(ret, err_msg): ''' Common function for setting error information for return dicts ''' ret['result'] = False ret['comment'] = err_msg return ret def _binary_replace(old, new): ''' This function does NOT do any diffing, it just checks the old and new files to see if either is binary, and provides an appropriate string noting the difference between the two files. If neither file is binary, an empty string is returned. This function should only be run AFTER it has been determined that the files differ. ''' old_isbin = not __utils__['files.is_text'](old) new_isbin = not __utils__['files.is_text'](new) if any((old_isbin, new_isbin)): if all((old_isbin, new_isbin)): return 'Replace binary file' elif old_isbin: return 'Replace binary file with text file' elif new_isbin: return 'Replace text file with binary file' return '' def _get_bkroot(): ''' Get the location of the backup dir in the minion cache ''' # Get the cachedir from the minion config return os.path.join(__salt__['config.get']('cachedir'), 'file_backup') def _splitlines_preserving_trailing_newline(str): ''' Returns a list of the lines in the string, breaking at line boundaries and preserving a trailing newline (if present). Essentially, this works like ``str.striplines(False)`` but preserves an empty line at the end. This is equivalent to the following code: .. code-block:: python lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') ''' lines = str.splitlines() if str.endswith('\n') or str.endswith('\r'): lines.append('') return lines def gid_to_group(gid): ''' Convert the group id to the group name on this system gid gid to convert to a group name CLI Example: .. code-block:: bash salt '*' file.gid_to_group 0 ''' try: gid = int(gid) except ValueError: # This is not an integer, maybe it's already the group name? gid = group_to_gid(gid) if gid == '': # Don't even bother to feed it to grp return '' try: return grp.getgrgid(gid).gr_name except (KeyError, NameError): # If group is not present, fall back to the gid. return gid def group_to_gid(group): ''' Convert the group to the gid on this system group group to convert to its gid CLI Example: .. code-block:: bash salt '*' file.group_to_gid root ''' if group is None: return '' try: if isinstance(group, int): return group return grp.getgrnam(group).gr_gid except KeyError: return '' def get_gid(path, follow_symlinks=True): ''' Return the id of the group that owns a given file path file or directory of which to get the gid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_gid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('gid', -1) def get_group(path, follow_symlinks=True): ''' Return the group that owns a given file path file or directory of which to get the group follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_group /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('group', False) def uid_to_user(uid): ''' Convert a uid to a user name uid uid to convert to a username CLI Example: .. code-block:: bash salt '*' file.uid_to_user 0 ''' try: return pwd.getpwuid(uid).pw_name except (KeyError, NameError): # If user is not present, fall back to the uid. return uid def user_to_uid(user): ''' Convert user name to a uid user user name to convert to its uid CLI Example: .. code-block:: bash salt '*' file.user_to_uid root ''' if user is None: user = salt.utils.user.get_user() try: if isinstance(user, int): return user return pwd.getpwnam(user).pw_uid except KeyError: return '' def get_uid(path, follow_symlinks=True): ''' Return the id of the user that owns a given file path file or directory of which to get the uid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_uid /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('uid', -1) def get_user(path, follow_symlinks=True): ''' Return the user that owns a given file path file or directory of which to get the user follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_user /etc/passwd .. versionchanged:: 0.16.4 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('user', False) def get_mode(path, follow_symlinks=True): ''' Return the mode of a file path file or directory of which to get the mode follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_mode /etc/passwd .. versionchanged:: 2014.1.0 ``follow_symlinks`` option added ''' return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('mode', '') def lchown(path, user, group): ''' Chown a file, pass the file the desired user and group without following symlinks. path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 return os.lchown(path, uid, gid) def chown(path, user, group): ''' Chown a file, pass the file the desired user and group path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = os.path.expanduser(path) uid = user_to_uid(user) gid = group_to_gid(group) err = '' if uid == '': if user: err += 'User does not exist\n' else: uid = -1 if gid == '': if group: err += 'Group does not exist\n' else: gid = -1 if not os.path.exists(path): try: # Broken symlinks will return false, but still need to be chowned return os.lchown(path, uid, gid) except OSError: pass err += 'File not found' if err: return err return os.chown(path, uid, gid) def chgrp(path, group): ''' Change the group of a file path path to the file or directory group group owner CLI Example: .. code-block:: bash salt '*' file.chgrp /etc/passwd root ''' path = os.path.expanduser(path) user = get_user(path) return chown(path, user, group) def _cmp_attrs(path, attrs): ''' .. versionadded:: 2018.3.0 Compare attributes of a given file to given attributes. Returns a pair (list) where first item are attributes to add and second item are to be removed. Please take into account when using this function that some minions will not have lsattr installed. path path to file to compare attributes with. attrs string of attributes to compare against a given file ''' diff = [None, None] # lsattr for AIX is not the same thing as lsattr for linux. if salt.utils.platform.is_aix(): return None try: lattrs = lsattr(path).get(path, '') except AttributeError: # lsattr not installed return None old = [chr for chr in lattrs if chr not in attrs] if old: diff[1] = ''.join(old) new = [chr for chr in attrs if chr not in lattrs] if new: diff[0] = ''.join(new) return diff def lsattr(path): ''' .. versionadded:: 2018.3.0 .. versionchanged:: 2018.3.1 If ``lsattr`` is not installed on the system, ``None`` is returned. .. versionchanged:: 2018.3.4 If on ``AIX``, ``None`` is returned even if in filesystem as lsattr on ``AIX`` is not the same thing as the linux version. Obtain the modifiable attributes of the given file. If path is to a directory, an empty list is returned. path path to file to obtain attributes of. File/directory must exist. CLI Example: .. code-block:: bash salt '*' file.lsattr foo1.txt ''' if not salt.utils.path.which('lsattr') or salt.utils.platform.is_aix(): return None if not os.path.exists(path): raise SaltInvocationError("File or directory does not exist: " + path) cmd = ['lsattr', path] result = __salt__['cmd.run'](cmd, ignore_retcode=True, python_shell=False) results = {} for line in result.splitlines(): if not line.startswith('lsattr: '): vals = line.split(None, 1) results[vals[1]] = re.findall(r"[aAcCdDeijPsStTu]", vals[0]) return results def chattr(*files, **kwargs): ''' .. versionadded:: 2018.3.0 Change the attributes of files. This function accepts one or more files and the following options: operator Can be wither ``add`` or ``remove``. Determines whether attributes should be added or removed from files attributes One or more of the following characters: ``aAcCdDeijPsStTu``, representing attributes to add to/remove from files version a version number to assign to the file(s) flags One or more of the following characters: ``RVf``, representing flags to assign to chattr (recurse, verbose, suppress most errors) CLI Example: .. code-block:: bash salt '*' file.chattr foo1.txt foo2.txt operator=add attributes=ai salt '*' file.chattr foo3.txt operator=remove attributes=i version=2 ''' operator = kwargs.pop('operator', None) attributes = kwargs.pop('attributes', None) flags = kwargs.pop('flags', None) version = kwargs.pop('version', None) if (operator is None) or (operator not in ('add', 'remove')): raise SaltInvocationError( "Need an operator: 'add' or 'remove' to modify attributes.") if attributes is None: raise SaltInvocationError("Need attributes: [aAcCdDeijPsStTu]") cmd = ['chattr'] if operator == "add": attrs = '+{0}'.format(attributes) elif operator == "remove": attrs = '-{0}'.format(attributes) cmd.append(attrs) if flags is not None: cmd.append('-{0}'.format(flags)) if version is not None: cmd.extend(['-v', version]) cmd.extend(files) result = __salt__['cmd.run'](cmd, python_shell=False) if bool(result): raise CommandExecutionError( "chattr failed to run, possibly due to bad parameters.") return True def get_sum(path, form='sha256'): ''' Return the checksum for the given file. The following checksum algorithms are supported: * md5 * sha1 * sha224 * sha256 **(default)** * sha384 * sha512 path path to the file or directory form desired sum format CLI Example: .. code-block:: bash salt '*' file.get_sum /etc/passwd sha512 ''' path = os.path.expanduser(path) if not os.path.isfile(path): return 'File not found' return salt.utils.hashutils.get_hash(path, form, 4096) def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` path path to the file or directory form desired sum format chunk_size amount to sum at once CLI Example: .. code-block:: bash salt '*' file.get_hash /etc/shadow ''' return salt.utils.hashutils.get_hash(os.path.expanduser(path), form, chunk_size) def get_source_sum(file_name='', source='', source_hash=None, source_hash_name=None, saltenv='base'): ''' .. versionadded:: 2016.11.0 Used by :py:func:`file.get_managed <salt.modules.file.get_managed>` to obtain the hash and hash type from the parameters specified below. file_name Optional file name being managed, for matching with :py:func:`file.extract_hash <salt.modules.file.extract_hash>`. source Source file, as used in :py:mod:`file <salt.states.file>` and other states. If ``source_hash`` refers to a file containing hashes, then this filename will be used to match a filename in that file. If the ``source_hash`` is a hash expression, then this argument will be ignored. source_hash Hash file/expression, as used in :py:mod:`file <salt.states.file>` and other states. If this value refers to a remote URL or absolute path to a local file, it will be cached and :py:func:`file.extract_hash <salt.modules.file.extract_hash>` will be used to obtain a hash from it. source_hash_name Specific file name to look for when ``source_hash`` refers to a remote file, used to disambiguate ambiguous matches. saltenv : base Salt fileserver environment from which to retrieve the source_hash. This value will only be used when ``source_hash`` refers to a file on the Salt fileserver (i.e. one beginning with ``salt://``). CLI Example: .. code-block:: bash salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=499ae16dcae71eeb7c3a30c75ea7a1a6 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 source_hash_name=./dir2/foo.tar.gz ''' def _invalid_source_hash_format(): ''' DRY helper for reporting invalid source_hash input ''' raise CommandExecutionError( 'Source hash {0} format is invalid. The supported formats are: ' '1) a hash, 2) an expression in the format <hash_type>=<hash>, or ' '3) either a path to a local file containing hashes, or a URI of ' 'a remote hash file. Supported protocols for remote hash files ' 'are: {1}. The hash may also not be of a valid length, the ' 'following are supported hash types and lengths: {2}.'.format( source_hash, ', '.join(salt.utils.files.VALID_PROTOS), ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) hash_fn = None if os.path.isabs(source_hash): hash_fn = source_hash else: try: proto = _urlparse(source_hash).scheme if proto in salt.utils.files.VALID_PROTOS: hash_fn = __salt__['cp.cache_file'](source_hash, saltenv) if not hash_fn: raise CommandExecutionError( 'Source hash file {0} not found'.format(source_hash) ) else: if proto != '': # Some unsupported protocol (e.g. foo://) is being used. # We'll get into this else block if a hash expression # (like md5=<md5 checksum here>), but in those cases, the # protocol will be an empty string, in which case we avoid # this error condition. _invalid_source_hash_format() except (AttributeError, TypeError): _invalid_source_hash_format() if hash_fn is not None: ret = extract_hash(hash_fn, '', file_name, source, source_hash_name) if ret is None: _invalid_source_hash_format() ret['hsum'] = ret['hsum'].lower() return ret else: # The source_hash is a hash expression ret = {} try: ret['hash_type'], ret['hsum'] = \ [x.strip() for x in source_hash.split('=', 1)] except AttributeError: _invalid_source_hash_format() except ValueError: # No hash type, try to figure out by hash length if not re.match('^[{0}]+$'.format(string.hexdigits), source_hash): _invalid_source_hash_format() ret['hsum'] = source_hash source_hash_len = len(source_hash) if source_hash_len in HASHES_REVMAP: ret['hash_type'] = HASHES_REVMAP[source_hash_len] else: _invalid_source_hash_format() if ret['hash_type'] not in HASHES: raise CommandExecutionError( 'Invalid hash type \'{0}\'. Supported hash types are: {1}. ' 'Either remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to a supported type.' .format(ret['hash_type'], ', '.join(HASHES), ret['hsum']) ) else: hsum_len = len(ret['hsum']) if hsum_len not in HASHES_REVMAP: _invalid_source_hash_format() elif hsum_len != HASHES[ret['hash_type']]: raise CommandExecutionError( 'Invalid length ({0}) for hash type \'{1}\'. Either ' 'remove the hash type and simply use \'{2}\' as the ' 'source_hash, or change the hash type to \'{3}\''.format( hsum_len, ret['hash_type'], ret['hsum'], HASHES_REVMAP[hsum_len], ) ) ret['hsum'] = ret['hsum'].lower() return ret def check_hash(path, file_hash): ''' Check if a file matches the given hash string Returns ``True`` if the hash matches, otherwise ``False``. path Path to a file local to the minion. hash The hash to check against the file specified in the ``path`` argument. .. versionchanged:: 2016.11.4 For this and newer versions the hash can be specified without an accompanying hash type (e.g. ``e138491e9d5b97023cea823fe17bac22``), but for earlier releases it is necessary to also specify the hash type in the format ``<hash_type>=<hash_value>`` (e.g. ``md5=e138491e9d5b97023cea823fe17bac22``). CLI Example: .. code-block:: bash salt '*' file.check_hash /etc/fstab e138491e9d5b97023cea823fe17bac22 salt '*' file.check_hash /etc/fstab md5=e138491e9d5b97023cea823fe17bac22 ''' path = os.path.expanduser(path) if not isinstance(file_hash, six.string_types): raise SaltInvocationError('hash must be a string') for sep in (':', '='): if sep in file_hash: hash_type, hash_value = file_hash.split(sep, 1) break else: hash_value = file_hash hash_len = len(file_hash) hash_type = HASHES_REVMAP.get(hash_len) if hash_type is None: raise SaltInvocationError( 'Hash {0} (length: {1}) could not be matched to a supported ' 'hash type. The supported hash types and lengths are: ' '{2}'.format( file_hash, hash_len, ', '.join( ['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)] ), ) ) return get_hash(path, hash_type) == hash_value def find(path, *args, **kwargs): ''' Approximate the Unix ``find(1)`` command and return a list of paths that meet the specified criteria. The options include match criteria: .. code-block:: text name = path-glob # case sensitive iname = path-glob # case insensitive regex = path-regex # case sensitive iregex = path-regex # case insensitive type = file-types # match any listed type user = users # match any listed user group = groups # match any listed group size = [+-]number[size-unit] # default unit = byte mtime = interval # modified since date grep = regex # search file contents and/or actions: .. code-block:: text delete [= file-types] # default type = 'f' exec = command [arg ...] # where {} is replaced by pathname print [= print-opts] and/or depth criteria: .. code-block:: text maxdepth = maximum depth to transverse in path mindepth = minimum depth to transverse before checking files or directories The default action is ``print=path`` ``path-glob``: .. code-block:: text * = match zero or more chars ? = match any char [abc] = match a, b, or c [!abc] or [^abc] = match anything except a, b, and c [x-y] = match chars x through y [!x-y] or [^x-y] = match anything except chars x through y {a,b,c} = match a or b or c ``path-regex``: a Python Regex (regular expression) pattern to match pathnames ``file-types``: a string of one or more of the following: .. code-block:: text a: all file types b: block device c: character device d: directory p: FIFO (named pipe) f: plain file l: symlink s: socket ``users``: a space and/or comma separated list of user names and/or uids ``groups``: a space and/or comma separated list of group names and/or gids ``size-unit``: .. code-block:: text b: bytes k: kilobytes m: megabytes g: gigabytes t: terabytes interval: .. code-block:: text [<num>w] [<num>d] [<num>h] [<num>m] [<num>s] where: w: week d: day h: hour m: minute s: second print-opts: a comma and/or space separated list of one or more of the following: .. code-block:: text group: group name md5: MD5 digest of file contents mode: file permissions (as integer) mtime: last modification time (as time_t) name: file basename path: file absolute path size: file size in bytes type: file type user: user name CLI Examples: .. code-block:: bash salt '*' file.find / type=f name=\\*.bak size=+10m salt '*' file.find /var mtime=+30d size=+10m print=path,size,mtime salt '*' file.find /var/log name=\\*.[0-9] mtime=+30d size=+10m delete ''' if 'delete' in args: kwargs['delete'] = 'f' elif 'print' in args: kwargs['print'] = 'path' try: finder = salt.utils.find.Finder(kwargs) except ValueError as ex: return 'error: {0}'.format(ex) ret = [item for i in [finder.find(p) for p in glob.glob(os.path.expanduser(path))] for item in i] ret.sort() return ret def _sed_esc(string, escape_all=False): ''' Escape single quotes and forward slashes ''' special_chars = "^.[$()|*+?{" string = string.replace("'", "'\"'\"'").replace("/", "\\/") if escape_all is True: for char in special_chars: string = string.replace(char, "\\" + char) return string def sed(path, before, after, limit='', backup='.bak', options='-r -e', flags='g', escape_all=False, negate_match=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup options : ``-r -e`` Options to pass to sed flags : ``g`` Flags to modify the sed search; e.g., ``i`` for case-insensitive pattern matching negate_match : False Negate the search command (``!``) .. versionadded:: 0.17.0 Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # path = os.path.expanduser(path) if not os.path.exists(path): return False # Mandate that before and after are strings before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.append('-i{0}'.format(backup) if backup else '-i') cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}{negate_match}s/{before}/{after}/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', negate_match='!' if negate_match else '', before=before, after=after, flags=flags ) ) cmd.append(path) return __salt__['cmd.run_all'](cmd, python_shell=False) def sed_contains(path, text, limit='', flags='g'): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the file at ``path`` contains ``text``. Utilizes sed to perform the search (line-wise search). Note: the ``p`` flag will be added to any flags you pass in. CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' # Largely inspired by Fabric's contrib.files.contains() path = os.path.expanduser(path) if not os.path.exists(path): return False before = _sed_esc(six.text_type(text), False) limit = _sed_esc(six.text_type(limit), False) options = '-n -r -e' if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}s/{before}/$/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', before=before, flags='p{0}'.format(flags) ) ) cmd.append(path) result = __salt__['cmd.run'](cmd, python_shell=False) return bool(result) def psed(path, before, after, limit='', backup='.bak', flags='gMS', escape_all=False, multi=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file (pure Python version) Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup flags : ``gMS`` Flags to modify the search. Valid values are: - ``g``: Replace all occurrences of the pattern, not just the first. - ``I``: Ignore case. - ``L``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\s`` and ``\\S`` dependent on the locale. - ``M``: Treat multiple lines as a single line. - ``S``: Make `.` match all characters, including newlines. - ``U``: Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\d``, ``\\D``, ``\\s`` and ``\\S`` dependent on Unicode. - ``X``: Verbose (whitespace is ignored). multi: ``False`` If True, treat the entire file as a single line Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # # Mandate that before and after are strings path = os.path.expanduser(path) multi = bool(multi) before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) # The pattern to replace with does not need to be escaped!!! # after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) shutil.copy2(path, '{0}{1}'.format(path, backup)) with salt.utils.files.fopen(path, 'w') as ofile: with salt.utils.files.fopen('{0}{1}'.format(path, backup), 'r') as ifile: if multi is True: for line in ifile.readline(): ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(line), before, after, limit, flags ) ) ) else: ofile.write( salt.utils.stringutils.to_str( _psed( salt.utils.stringutils.to_unicode(ifile.read()), before, after, limit, flags ) ) ) RE_FLAG_TABLE = {'I': re.I, 'L': re.L, 'M': re.M, 'S': re.S, 'U': re.U, 'X': re.X} def _psed(text, before, after, limit, flags): ''' Does the actual work for file.psed, so that single lines can be passed in ''' atext = text if limit: limit = re.compile(limit) comps = text.split(limit) atext = ''.join(comps[1:]) count = 1 if 'g' in flags: count = 0 flags = flags.replace('g', '') aflags = 0 for flag in flags: aflags |= RE_FLAG_TABLE[flag] before = re.compile(before, flags=aflags) text = re.sub(before, after, atext, count=count) return text def uncomment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Uncomment specified commented lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be uncommented. This regex should not include the comment character. A leading ``^`` character will be stripped for convenience (for easily switching between comment() and uncomment()). char : ``#`` The character to remove in order to uncomment a line backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup CLI Example: .. code-block:: bash salt '*' file.uncomment /etc/hosts.deny 'ALL: PARANOID' ''' return comment_line(path=path, regex=regex, char=char, cmnt=False, backup=backup) def comment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Comment out specified lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be commented; this pattern will be wrapped in parenthesis and will move any preceding/trailing ``^`` or ``$`` characters outside the parenthesis (e.g., the pattern ``^foo$`` will be rewritten as ``^(foo)$``) char : ``#`` The character to be inserted at the beginning of a line in order to comment it out backup : ``.bak`` The file will be backed up before edit with this file extension .. warning:: This backup will be overwritten each time ``sed`` / ``comment`` / ``uncomment`` is called. Meaning the backup will only be useful after the first invocation. CLI Example: .. code-block:: bash salt '*' file.comment /etc/modules pcspkr ''' return comment_line(path=path, regex=regex, char=char, cmnt=True, backup=backup) def comment_line(path, regex, char='#', cmnt=True, backup='.bak'): r''' Comment or Uncomment a line in a text file. :param path: string The full path to the text file. :param regex: string A regex expression that begins with ``^`` that will find the line you wish to comment. Can be as simple as ``^color =`` :param char: string The character used to comment a line in the type of file you're referencing. Default is ``#`` :param cmnt: boolean True to comment the line. False to uncomment the line. Default is True. :param backup: string The file extension to give the backup file. Default is ``.bak`` Set to False/None to not keep a backup. :return: boolean Returns True if successful, False if not CLI Example: The following example will comment out the ``pcspkr`` line in the ``/etc/modules`` file using the default ``#`` character and create a backup file named ``modules.bak`` .. code-block:: bash salt '*' file.comment_line '/etc/modules' '^pcspkr' CLI Example: The following example will uncomment the ``log_level`` setting in ``minion`` config file if it is set to either ``warning``, ``info``, or ``debug`` using the ``#`` character and create a backup file named ``minion.bk`` .. code-block:: bash salt '*' file.comment_line 'C:\salt\conf\minion' '^log_level: (warning|info|debug)' '#' False '.bk' ''' # Get the regex for comment or uncomment if cmnt: regex = '{0}({1}){2}'.format( '^' if regex.startswith('^') else '', regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') else: regex = r'^{0}\s*({1}){2}'.format( char, regex.lstrip('^').rstrip('$'), '$' if regex.endswith('$') else '') # Load the real path to the file path = os.path.realpath(os.path.expanduser(path)) # Make sure the file exists if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) # Make sure it is a text file if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}'.format(path)) # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes found = False # Dictionaries for comparing changes orig_file = [] new_file = [] # Buffer size for fopen bufsize = os.path.getsize(path) try: # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: # Is it in this line line = salt.utils.stringutils.to_unicode(line) if re.match(regex, line): # Load lines into dictionaries, set found to True orig_file.append(line) if cmnt: new_file.append('{0}{1}'.format(char, line)) else: new_file.append(line.lstrip(char)) found = True except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) # We've searched the whole file. If we didn't find anything, return False if not found: return False if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Create a copy to read from and to use as a backup later try: temp_file = _mkstemp_copy(path=path, preserve_inode=False) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) try: # Open the file in write mode mode = 'wb' if six.PY2 and salt.utils.platform.is_windows() else 'w' with salt.utils.files.fopen(path, mode=mode, buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='rb', buffering=bufsize) as r_file: # Loop through each line of the file and look for a match for line in r_file: line = salt.utils.stringutils.to_unicode(line) try: # Is it in this line if re.match(regex, line): # Write the new line if cmnt: wline = '{0}{1}'.format(char, line) else: wline = line.lstrip(char) else: # Write the existing line (no change) wline = line wline = salt.utils.stringutils.to_bytes(wline) \ if six.PY2 and salt.utils.platform.is_windows() \ else salt.utils.stringutils.to_str(wline) w_file.write(wline) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if backup: # Move the backup file to the original directory backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: os.remove(temp_file) if not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) # Return a diff using the two dictionaries return __utils__['stringutils.get_diff'](orig_file, new_file) def _get_flags(flags): ''' Return an integer appropriate for use as a flag for the re module from a list of human-readable strings .. code-block:: python >>> _get_flags(['MULTILINE', 'IGNORECASE']) 10 >>> _get_flags('MULTILINE') 8 >>> _get_flags(2) 2 ''' if isinstance(flags, six.string_types): flags = [flags] if isinstance(flags, Iterable) and not isinstance(flags, Mapping): _flags_acc = [] for flag in flags: _flag = getattr(re, six.text_type(flag).upper()) if not isinstance(_flag, six.integer_types): raise SaltInvocationError( 'Invalid re flag given: {0}'.format(flag) ) _flags_acc.append(_flag) return reduce(operator.__or__, _flags_acc) elif isinstance(flags, six.integer_types): return flags else: raise SaltInvocationError( 'Invalid re flags: "{0}", must be given either as a single flag ' 'string, a list of strings, or as an integer'.format(flags) ) def _add_flags(flags, new_flags): ''' Combine ``flags`` and ``new_flags`` ''' flags = _get_flags(flags) new_flags = _get_flags(new_flags) return flags | new_flags def _mkstemp_copy(path, preserve_inode=True): ''' Create a temp file and move/copy the contents of ``path`` to the temp file. Return the path to the temp file. path The full path to the file whose contents will be moved/copied to a temp file. Whether it's moved or copied depends on the value of ``preserve_inode``. preserve_inode Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). Default is ``True``. ''' temp_file = None # Create the temp file try: temp_file = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to create temp file. " "Exception: {0}".format(exc) ) # use `copy` to preserve the inode of the # original file, and thus preserve hardlinks # to the inode. otherwise, use `move` to # preserve prior behavior, which results in # writing the file to a new inode. if preserve_inode: try: shutil.copy2(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to copy file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) else: try: shutil.move(path, temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move file '{0}' to the " "temp file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) return temp_file def _starts_till(src, probe, strip_comments=True): ''' Returns True if src and probe at least matches at the beginning till some point. ''' def _strip_comments(txt): ''' Strip possible comments. Usually comments are one or two symbols at the beginning of the line, separated with space ''' buff = txt.split(" ", 1) return len(buff) == 2 and len(buff[0]) < 2 and buff[1] or txt def _to_words(txt): ''' Split by words ''' return txt and [w for w in txt.strip().split(" ") if w.strip()] or txt no_match = -1 equal = 0 if not src or not probe: return no_match src = src.rstrip('\n\r') probe = probe.rstrip('\n\r') if src == probe: return equal src = _to_words(strip_comments and _strip_comments(src) or src) probe = _to_words(strip_comments and _strip_comments(probe) or probe) a_buff, b_buff = len(src) < len(probe) and (src, probe) or (probe, src) b_buff = ' '.join(b_buff) for idx in range(len(a_buff)): prb = ' '.join(a_buff[:-(idx + 1)]) if prb and b_buff.startswith(prb): return idx return no_match def _regex_to_static(src, regex): ''' Expand regular expression to static match. ''' if not src or not regex: return None try: compiled = re.compile(regex, re.DOTALL) src = [line for line in src if compiled.search(line) or line.count(regex)] except Exception as ex: raise CommandExecutionError("{0}: '{1}'".format(_get_error_message(ex), regex)) return src and src or [] def _assert_occurrence(probe, target, amount=1): ''' Raise an exception, if there are different amount of specified occurrences in src. ''' occ = len(probe) if occ > amount: msg = 'more than' elif occ < amount: msg = 'less than' elif not occ: msg = 'no' else: msg = None if msg: raise CommandExecutionError('Found {0} expected occurrences in "{1}" expression'.format(msg, target)) return occ def _set_line_indent(src, line, indent): ''' Indent the line with the source line. ''' if not indent: return line idt = [] for c in src: if c not in ['\t', ' ']: break idt.append(c) return ''.join(idt) + line.lstrip() def _get_eol(line): match = re.search('((?<!\r)\n|\r(?!\n)|\r\n)$', line) return match and match.group() or '' def _set_line_eol(src, line): ''' Add line ending ''' line_ending = _get_eol(src) or os.linesep return line.rstrip() + line_ending def _insert_line_before(idx, body, content, indent): if not idx or (idx and _starts_till(body[idx - 1], content) < 0): cnd = _set_line_indent(body[idx], content, indent) body.insert(idx, cnd) return body def _insert_line_after(idx, body, content, indent): # No duplicates or append, if "after" is the last line next_line = idx + 1 < len(body) and body[idx + 1] or None if next_line is None or _starts_till(next_line, content) < 0: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) return body def line(path, content=None, match=None, mode=None, location=None, before=None, after=None, show_changes=True, backup=False, quiet=False, indent=True): ''' .. versionadded:: 2015.8.0 Edit a line in the configuration file. The ``path`` and ``content`` arguments are required, as well as passing in one of the ``mode`` options. path Filesystem path to the file to be edited. content Content of the line. Allowed to be empty if mode=delete. match Match the target line for an action by a fragment of a string or regular expression. If neither ``before`` nor ``after`` are provided, and ``match`` is also ``None``, match becomes the ``content`` value. mode Defines how to edit a line. One of the following options is required: - ensure If line does not exist, it will be added. This is based on the ``content`` argument. - replace If line already exists, it will be replaced. - delete Delete the line, once found. - insert Insert a line. .. note:: If ``mode=insert`` is used, at least one of the following options must also be defined: ``location``, ``before``, or ``after``. If ``location`` is used, it takes precedence over the other two options. location Defines where to place content in the line. Note this option is only used when ``mode=insert`` is specified. If a location is passed in, it takes precedence over both the ``before`` and ``after`` kwargs. Valid locations are: - start Place the content at the beginning of the file. - end Place the content at the end of the file. before Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. after Regular expression or an exact case-sensitive fragment of the string. This option is only used when either the ``ensure`` or ``insert`` mode is defined. show_changes Output a unified diff of the old file and the new file. If ``False`` return a boolean if any changes were made. Default is ``True`` .. note:: Using this option will store two copies of the file in-memory (the original version and the edited version) in order to generate the diff. backup Create a backup of the original file with the extension: "Year-Month-Day-Hour-Minutes-Seconds". quiet Do not raise any exceptions. E.g. ignore the fact that the file that is tried to be edited does not exist and nothing really happened. indent Keep indentation with the previous line. This option is not considered when the ``delete`` mode is specified. CLI Example: .. code-block:: bash salt '*' file.line /etc/nsswitch.conf "networks:\tfiles dns" after="hosts:.*?" mode='ensure' .. note:: If an equal sign (``=``) appears in an argument to a Salt command, it is interpreted as a keyword argument in the format of ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.line /path/to/file content="CREATEMAIL_SPOOL=no" match="CREATE_MAIL_SPOOL=yes" mode="replace" ''' path = os.path.realpath(os.path.expanduser(path)) if not os.path.isfile(path): if not quiet: raise CommandExecutionError('File "{0}" does not exists or is not a file.'.format(path)) return False # No changes had happened mode = mode and mode.lower() or mode if mode not in ['insert', 'ensure', 'delete', 'replace']: if mode is None: raise CommandExecutionError('Mode was not defined. How to process the file?') else: raise CommandExecutionError('Unknown mode: "{0}"'.format(mode)) # We've set the content to be empty in the function params but we want to make sure # it gets passed when needed. Feature #37092 empty_content_modes = ['delete'] if mode not in empty_content_modes and content is None: raise CommandExecutionError('Content can only be empty if mode is "{0}"'.format(', '.join(empty_content_modes))) del empty_content_modes # Before/after has privilege. If nothing defined, match is used by content. if before is None and after is None and not match: match = content with salt.utils.files.fopen(path, mode='r') as fp_: body = salt.utils.data.decode_list(fp_.readlines()) body_before = hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() # Add empty line at the end if last line ends with eol. # Allows simpler code if body and _get_eol(body[-1]): body.append('') after = _regex_to_static(body, after) before = _regex_to_static(body, before) match = _regex_to_static(body, match) if os.stat(path).st_size == 0 and mode in ('delete', 'replace'): log.warning('Cannot find text to %s. File \'%s\' is empty.', mode, path) body = [] elif mode == 'delete' and match: body = [line for line in body if line != match[0]] elif mode == 'replace' and match: idx = body.index(match[0]) file_line = body.pop(idx) body.insert(idx, _set_line_indent(file_line, content, indent)) elif mode == 'insert': if not location and not before and not after: raise CommandExecutionError('On insert must be defined either "location" or "before/after" conditions.') if not location: if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') out = [] in_range = False for line in body: if line == after[0]: in_range = True elif line == before[0] and in_range: cnd = _set_line_indent(line, content, indent) out.append(cnd) out.append(line) body = out if before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif after and not before: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: if location == 'start': if body: body.insert(0, _set_line_eol(body[0], content)) else: body.append(content + os.linesep) elif location == 'end': body.append(_set_line_indent(body[-1], content, indent) if body else content) elif mode == 'ensure': if before and after: _assert_occurrence(before, 'before') _assert_occurrence(after, 'after') is_there = bool([l for l in body if l.count(content)]) if not is_there: idx = body.index(after[0]) if idx < (len(body) - 1) and body[idx + 1] == before[0]: cnd = _set_line_indent(body[idx], content, indent) body.insert(idx + 1, cnd) else: raise CommandExecutionError('Found more than one line between ' 'boundaries "before" and "after".') elif before and not after: _assert_occurrence(before, 'before') idx = body.index(before[0]) body = _insert_line_before(idx, body, content, indent) elif not before and after: _assert_occurrence(after, 'after') idx = body.index(after[0]) body = _insert_line_after(idx, body, content, indent) else: raise CommandExecutionError("Wrong conditions? " "Unable to ensure line without knowing " "where to put it before and/or after.") if body: for idx, line in enumerate(body): if not _get_eol(line) and idx+1 < len(body): prev = idx and idx-1 or 1 body[idx] = _set_line_eol(body[prev], line) # We do not need empty line at the end anymore if '' == body[-1]: body.pop() changed = body_before != hashlib.sha256(salt.utils.stringutils.to_bytes(''.join(body))).hexdigest() if backup and changed and __opts__['test'] is False: try: temp_file = _mkstemp_copy(path=path, preserve_inode=True) shutil.move(temp_file, '{0}.{1}'.format(path, time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime()))) except (OSError, IOError) as exc: raise CommandExecutionError("Unable to create the backup file of {0}. Exception: {1}".format(path, exc)) changes_diff = None if changed: if show_changes: with salt.utils.files.fopen(path, 'r') as fp_: path_content = salt.utils.data.decode_list(fp_.read().splitlines(True)) changes_diff = __utils__['stringutils.get_diff'](path_content, body) if __opts__['test'] is False: fh_ = None try: # Make sure we match the file mode from salt.utils.files.fopen if six.PY2 and salt.utils.platform.is_windows(): mode = 'wb' body = salt.utils.data.encode_list(body) else: mode = 'w' body = salt.utils.data.decode_list(body, to_str=True) fh_ = salt.utils.atomicfile.atomic_open(path, mode) fh_.writelines(body) finally: if fh_: fh_.close() return show_changes and changes_diff or changed def replace(path, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, backup='.bak', dry_run=False, search_only=False, show_changes=True, ignore_if_missing=False, preserve_inode=True, backslash_literal=False, ): ''' .. versionadded:: 0.17.0 Replace occurrences of a pattern in a file. If ``show_changes`` is ``True``, then a diff of what changed will be returned, otherwise a ``True`` will be returned when changes are made, and ``False`` when no changes are made. This is a pure Python implementation that wraps Python's :py:func:`~re.sub`. path Filesystem path to the file to be edited. If a symlink is specified, it will be resolved to its target. pattern A regular expression, to be matched using Python's :py:func:`~re.search`. repl The replacement text count : 0 Maximum number of pattern occurrences to be replaced. If count is a positive integer ``n``, only ``n`` occurrences will be replaced, otherwise all occurrences will be replaced. flags (list or int) A list of flags defined in the ``re`` module documentation from the Python standard library. Each list item should be a string that will correlate to the human-friendly flag name. E.g., ``['IGNORECASE', 'MULTILINE']``. Optionally, ``flags`` may be an int, with a value corresponding to the XOR (``|``) of all the desired flags. Defaults to 8 (which supports 'MULTILINE'). bufsize (int or str) How much of the file to buffer into memory at once. The default value ``1`` processes one line at a time. The special value ``file`` may be specified which will read the entire file into memory before processing. append_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True``, and pattern is not found, then the content will be appended to the file. prepend_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True`` and pattern is not found, then the content will be prepended to the file. not_found_content .. versionadded:: 2014.7.0 Content to use for append/prepend if not found. If None (default), uses ``repl``. Useful when ``repl`` uses references to group in pattern. backup : .bak The file extension to use for a backup of the file before editing. Set to ``False`` to skip making a backup. dry_run : False If set to ``True``, no changes will be made to the file, the function will just return the changes that would have been made (or a ``True``/``False`` value if ``show_changes`` is set to ``False``). search_only : False If set to true, this no changes will be performed on the file, and this function will simply return ``True`` if the pattern was matched, and ``False`` if not. show_changes : True If ``True``, return a diff of changes made. Otherwise, return ``True`` if changes were made, and ``False`` if not. .. note:: Using this option will store two copies of the file in memory (the original version and the edited version) in order to generate the diff. This may not normally be a concern, but could impact performance if used with large files. ignore_if_missing : False .. versionadded:: 2015.8.0 If set to ``True``, this function will simply return ``False`` if the file doesn't exist. Otherwise, an error will be thrown. preserve_inode : True .. versionadded:: 2015.8.0 Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). backslash_literal : False .. versionadded:: 2016.11.7 Interpret backslashes as literal backslashes for the repl and not escape characters. This will help when using append/prepend so that the backslashes are not interpreted for the repl on the second run of the state. If an equal sign (``=``) appears in an argument to a Salt command it is interpreted as a keyword argument in the format ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.replace /path/to/file pattern='=' repl=':' salt '*' file.replace /path/to/file pattern="bind-address\\s*=" repl='bind-address:' CLI Examples: .. code-block:: bash salt '*' file.replace /etc/httpd/httpd.conf pattern='LogLevel warn' repl='LogLevel info' salt '*' file.replace /some/file pattern='before' repl='after' flags='[MULTILINE, IGNORECASE]' ''' symlink = False if is_link(path): symlink = True target_path = os.readlink(path) given_path = os.path.expanduser(path) path = os.path.realpath(os.path.expanduser(path)) if not os.path.exists(path): if ignore_if_missing: return False else: raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if search_only and (append_if_not_found or prepend_if_not_found): raise SaltInvocationError( 'search_only cannot be used with append/prepend_if_not_found' ) if append_if_not_found and prepend_if_not_found: raise SaltInvocationError( 'Only one of append and prepend_if_not_found is permitted' ) flags_num = _get_flags(flags) cpattern = re.compile(salt.utils.stringutils.to_bytes(pattern), flags_num) filesize = os.path.getsize(path) if bufsize == 'file': bufsize = filesize # Search the file; track if any changes have been made for the return val has_changes = False orig_file = [] # used for show_changes and change detection new_file = [] # used for show_changes and change detection if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Avoid TypeErrors by forcing repl to be bytearray related to mmap # Replacement text may contains integer: 123 for example repl = salt.utils.stringutils.to_bytes(six.text_type(repl)) if not_found_content: not_found_content = salt.utils.stringutils.to_bytes(not_found_content) found = False temp_file = None content = salt.utils.stringutils.to_unicode(not_found_content) \ if not_found_content and (prepend_if_not_found or append_if_not_found) \ else salt.utils.stringutils.to_unicode(repl) try: # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes r_data = None # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: try: # mmap throws a ValueError if the file is empty. r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) except (ValueError, mmap.error): # size of file in /proc is 0, but contains data r_data = salt.utils.stringutils.to_bytes("".join(r_file)) if search_only: # Just search; bail as early as a match is found if re.search(cpattern, r_data): return True # `with` block handles file closure else: return False else: result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) # found anything? (even if no change) if nrepl > 0: found = True # Identity check the potential change has_changes = True if pattern != repl else has_changes if prepend_if_not_found or append_if_not_found: # Search for content, to avoid pre/appending the # content if it was pre/appended in a previous run. if re.search(salt.utils.stringutils.to_bytes('^{0}($|(?=\r\n))'.format(re.escape(content))), r_data, flags=flags_num): # Content was found, so set found. found = True orig_file = r_data.read(filesize).splitlines(True) \ if isinstance(r_data, mmap.mmap) \ else r_data.splitlines(True) new_file = result.splitlines(True) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() if has_changes and not dry_run: # Write the replacement text in this block. try: # Create a copy to read from and to use as a backup later temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) r_data = None try: # Open the file in write mode with salt.utils.files.fopen(path, mode='w', buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='r', buffering=bufsize) as r_file: r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) try: w_file.write(salt.utils.stringutils.to_str(result)) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if not found and (append_if_not_found or prepend_if_not_found): if not_found_content is None: not_found_content = repl if prepend_if_not_found: new_file.insert(0, not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) else: # append_if_not_found # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(salt.utils.stringutils.to_bytes(os.linesep)): new_file[-1] += salt.utils.stringutils.to_bytes(os.linesep) new_file.append(not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) has_changes = True if not dry_run: try: # Create a copy to read from and for later use as a backup temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line)) finally: fh_.close() if backup and has_changes and not dry_run: # keep the backup only if it was requested # and only if there were any changes backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) if symlink: symlink_backup = '{0}{1}'.format(given_path, backup) target_backup = '{0}{1}'.format(target_path, backup) # Always clobber any existing symlink backup # to match the behaviour of the 'backup' option try: os.symlink(target_backup, symlink_backup) except OSError: os.remove(symlink_backup) os.symlink(target_backup, symlink_backup) except Exception: raise CommandExecutionError( "Unable create backup symlink '{0}'. " "Target was '{1}'. " "Exception: {2}".format(symlink_backup, target_backup, exc) ) elif temp_file: try: os.remove(temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to delete temp file '{0}'. " "Exception: {1}".format(temp_file, exc) ) if not dry_run and not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) differences = __utils__['stringutils.get_diff'](orig_file, new_file) if show_changes: return differences # We may have found a regex line match but don't need to change the line # (for situations where the pattern also matches the repl). Revert the # has_changes flag to False if the final result is unchanged. if not differences: has_changes = False return has_changes def blockreplace(path, marker_start='#-- start managed zone --', marker_end='#-- end managed zone --', content='', append_if_not_found=False, prepend_if_not_found=False, backup='.bak', dry_run=False, show_changes=True, append_newline=False, insert_before_match=None, insert_after_match=None): ''' .. versionadded:: 2014.1.0 Replace content of a text block in a file, delimited by line markers A block of content delimited by comments can help you manage several lines entries without worrying about old entries removal. .. note:: This function will store two copies of the file in-memory (the original version and the edited version) in order to detect changes and only edit the targeted file if necessary. path Filesystem path to the file to be edited marker_start The line content identifying a line as the start of the content block. Note that the whole line containing this marker will be considered, so whitespace or extra content before or after the marker is included in final output marker_end The line content identifying the end of the content block. As of versions 2017.7.5 and 2018.3.1, everything up to the text matching the marker will be replaced, so it's important to ensure that your marker includes the beginning of the text you wish to replace. content The content to be used between the two lines identified by marker_start and marker_stop. append_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be appended to the file. prepend_if_not_found : False If markers are not found and set to ``True`` then, the markers and content will be prepended to the file. insert_before_match If markers are not found, this parameter can be set to a regex which will insert the block before the first found occurrence in the file. .. versionadded:: Neon insert_after_match If markers are not found, this parameter can be set to a regex which will insert the block after the first found occurrence in the file. .. versionadded:: Neon backup The file extension to use for a backup of the file if any edit is made. Set to ``False`` to skip making a backup. dry_run : False If ``True``, do not make any edits to the file and simply return the changes that *would* be made. show_changes : True Controls how changes are presented. If ``True``, this function will return a unified diff of the changes made. If False, then it will return a boolean (``True`` if any changes were made, otherwise ``False``). append_newline : False Controls whether or not a newline is appended to the content block. If the value of this argument is ``True`` then a newline will be added to the content block. If it is ``False``, then a newline will *not* be added to the content block. If it is ``None`` then a newline will only be added to the content block if it does not already end in a newline. .. versionadded:: 2016.3.4 .. versionchanged:: 2017.7.5,2018.3.1 New behavior added when value is ``None``. .. versionchanged:: 2019.2.0 The default value of this argument will change to ``None`` to match the behavior of the :py:func:`file.blockreplace state <salt.states.file.blockreplace>` CLI Example: .. code-block:: bash salt '*' file.blockreplace /etc/hosts '#-- start managed zone foobar : DO NOT EDIT --' \\ '#-- end managed zone foobar --' $'10.0.1.1 foo.foobar\\n10.0.1.2 bar.foobar' True ''' exclusive_params = [append_if_not_found, prepend_if_not_found, bool(insert_before_match), bool(insert_after_match)] if sum(exclusive_params) > 1: raise SaltInvocationError( 'Only one of append_if_not_found, prepend_if_not_found,' ' insert_before_match, and insert_after_match is permitted' ) path = os.path.expanduser(path) if not os.path.exists(path): raise SaltInvocationError('File not found: {0}'.format(path)) try: file_encoding = __utils__['files.get_encoding'](path) except CommandExecutionError: file_encoding = None if __utils__['files.is_binary'](path): if not file_encoding: raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if insert_before_match or insert_after_match: if insert_before_match: if not isinstance(insert_before_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_before_match parameter.' ) elif insert_after_match: if not isinstance(insert_after_match, six.string_types): raise CommandExecutionError( 'RegEx expected in insert_after_match parameter.' ) if append_newline is None and not content.endswith((os.linesep, '\n')): append_newline = True # Split the content into a list of lines, removing newline characters. To # ensure that we handle both Windows and POSIX newlines, first split on # Windows newlines, and then split on POSIX newlines. split_content = [] for win_line in content.split('\r\n'): for content_line in win_line.split('\n'): split_content.append(content_line) line_count = len(split_content) has_changes = False orig_file = [] new_file = [] in_block = False block_found = False linesep = None def _add_content(linesep, lines=None, include_marker_start=True, end_line=None): if lines is None: lines = [] include_marker_start = True if end_line is None: end_line = marker_end end_line = end_line.rstrip('\r\n') + linesep if include_marker_start: lines.append(marker_start + linesep) if split_content: for index, content_line in enumerate(split_content, 1): if index != line_count: lines.append(content_line + linesep) else: # We're on the last line of the content block if append_newline: lines.append(content_line + linesep) lines.append(end_line) else: lines.append(content_line + end_line) else: lines.append(end_line) return lines # We do not use in-place editing to avoid file attrs modifications when # no changes are required and to avoid any file access on a partially # written file. try: fi_file = io.open(path, mode='r', encoding=file_encoding, newline='') for line in fi_file: write_line_to_new_file = True if linesep is None: # Auto-detect line separator if line.endswith('\r\n'): linesep = '\r\n' elif line.endswith('\n'): linesep = '\n' else: # No newline(s) in file, fall back to system's linesep linesep = os.linesep if marker_start in line: # We've entered the content block in_block = True else: if in_block: # We're not going to write the lines from the old file to # the new file until we have exited the block. write_line_to_new_file = False marker_end_pos = line.find(marker_end) if marker_end_pos != -1: # End of block detected in_block = False # We've found and exited the block block_found = True _add_content(linesep, lines=new_file, include_marker_start=False, end_line=line[marker_end_pos:]) # Save the line from the original file orig_file.append(line) if write_line_to_new_file: new_file.append(line) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read from {0}: {1}'.format(path, exc) ) finally: if linesep is None: # If the file was empty, we will not have set linesep yet. Assume # the system's line separator. This is needed for when we # prepend/append later on. linesep = os.linesep try: fi_file.close() except Exception: pass if in_block: # unterminated block => bad, always fail raise CommandExecutionError( 'Unterminated marked block. End of file reached before marker_end.' ) if not block_found: if prepend_if_not_found: # add the markers and content at the beginning of file prepended_content = _add_content(linesep) prepended_content.extend(new_file) new_file = prepended_content block_found = True elif append_if_not_found: # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(linesep): new_file[-1] += linesep # add the markers and content at the end of file _add_content(linesep, lines=new_file) block_found = True elif insert_before_match or insert_after_match: match_regex = insert_before_match or insert_after_match match_idx = [i for i, item in enumerate(orig_file) if re.search(match_regex, item)] if match_idx: match_idx = match_idx[0] for line in _add_content(linesep): if insert_after_match: match_idx += 1 new_file.insert(match_idx, line) if insert_before_match: match_idx += 1 block_found = True if not block_found: raise CommandExecutionError( 'Cannot edit marked block. Markers were not found in file.' ) diff = __utils__['stringutils.get_diff'](orig_file, new_file) has_changes = diff is not '' if has_changes and not dry_run: # changes detected # backup file attrs perms = {} perms['user'] = get_user(path) perms['group'] = get_group(path) perms['mode'] = salt.utils.files.normalize_mode(get_mode(path)) # backup old content if backup is not False: backup_path = '{0}{1}'.format(path, backup) shutil.copy2(path, backup_path) # copy2 does not preserve ownership check_perms(backup_path, None, perms['user'], perms['group'], perms['mode']) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line, encoding=file_encoding)) finally: fh_.close() # this may have overwritten file attrs check_perms(path, None, perms['user'], perms['group'], perms['mode']) if show_changes: return diff return has_changes def search(path, pattern, flags=8, bufsize=1, ignore_if_missing=False, multiline=False ): ''' .. versionadded:: 0.17.0 Search for occurrences of a pattern in a file Except for multiline, params are identical to :py:func:`~salt.modules.file.replace`. multiline If true, inserts 'MULTILINE' into ``flags`` and sets ``bufsize`` to 'file'. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' file.search /etc/crontab 'mymaintenance.sh' ''' if multiline: flags = _add_flags(flags, 'MULTILINE') bufsize = 'file' # This function wraps file.replace on purpose in order to enforce # consistent usage, compatible regex's, expected behavior, *and* bugs. :) # Any enhancements or fixes to one should affect the other. return replace(path, pattern, '', flags=flags, bufsize=bufsize, dry_run=True, search_only=True, show_changes=False, ignore_if_missing=ignore_if_missing) def patch(originalfile, patchfile, options='', dry_run=False): ''' .. versionadded:: 0.10.4 Apply a patch to a file or directory. Equivalent to: .. code-block:: bash patch <options> -i <patchfile> <originalfile> Or, when a directory is patched: .. code-block:: bash patch <options> -i <patchfile> -d <originalfile> -p0 originalfile The full path to the file or directory to be patched patchfile A patch file to apply to ``originalfile`` options Options to pass to patch. CLI Example: .. code-block:: bash salt '*' file.patch /opt/file.txt /tmp/file.txt.patch ''' patchpath = salt.utils.path.which('patch') if not patchpath: raise CommandExecutionError( 'patch executable not found. Is the distribution\'s patch ' 'package installed?' ) cmd = [patchpath] cmd.extend(salt.utils.args.shlex_split(options)) if dry_run: if __grains__['kernel'] in ('FreeBSD', 'OpenBSD'): cmd.append('-C') else: cmd.append('--dry-run') # this argument prevents interactive prompts when the patch fails to apply. # the exit code will still be greater than 0 if that is the case. if '-N' not in cmd and '--forward' not in cmd: cmd.append('--forward') has_rejectfile_option = False for option in cmd: if option == '-r' or option.startswith('-r ') \ or option.startswith('--reject-file'): has_rejectfile_option = True break # by default, patch will write rejected patch files to <filename>.rej. # this option prevents that. if not has_rejectfile_option: cmd.append('--reject-file=-') cmd.extend(['-i', patchfile]) if os.path.isdir(originalfile): cmd.extend(['-d', originalfile]) has_strip_option = False for option in cmd: if option.startswith('-p') or option.startswith('--strip='): has_strip_option = True break if not has_strip_option: cmd.append('--strip=0') else: cmd.append(originalfile) return __salt__['cmd.run_all'](cmd, python_shell=False) def contains(path, text): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the file at ``path`` contains ``text`` CLI Example: .. code-block:: bash salt '*' file.contains /etc/crontab 'mymaintenance.sh' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False stripped_text = six.text_type(text).strip() try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if stripped_text in chunk: return True return False except (IOError, OSError): return False def contains_regex(path, regex, lchar=''): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return True if the given regular expression matches on any line in the text of a given file. If the lchar argument (leading char) is specified, it will strip `lchar` from the left side of each line before trying to match CLI Example: .. code-block:: bash salt '*' file.contains_regex /etc/crontab ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.files.fopen(path, 'r') as target: for line in target: line = salt.utils.stringutils.to_unicode(line) if lchar: line = line.lstrip(lchar) if re.search(regex, line): return True return False except (IOError, OSError): return False def contains_glob(path, glob_expr): ''' .. deprecated:: 0.17.0 Use :func:`search` instead. Return ``True`` if the given glob matches a string in the named file CLI Example: .. code-block:: bash salt '*' file.contains_glob /etc/foobar '*cheese*' ''' path = os.path.expanduser(path) if not os.path.exists(path): return False try: with salt.utils.filebuffer.BufferedReader(path) as breader: for chunk in breader: if fnmatch.fnmatch(chunk, glob_expr): return True return False except (IOError, OSError): return False def append(path, *args, **kwargs): ''' .. versionadded:: 0.9.5 Append text to the end of a file path path to file `*args` strings to append to file CLI Example: .. code-block:: bash salt '*' file.append /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.append /etc/motd args='cheese=spam' salt '*' file.append /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) # Largely inspired by Fabric's contrib.files.append() if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] # Make sure we have a newline at the end of the file. Do this in binary # mode so SEEK_END with nonzero offset will work. with salt.utils.files.fopen(path, 'rb+') as ofile: linesep = salt.utils.stringutils.to_bytes(os.linesep) try: ofile.seek(-len(linesep), os.SEEK_END) except IOError as exc: if exc.errno in (errno.EINVAL, errno.ESPIPE): # Empty file, simply append lines at the beginning of the file pass else: raise else: if ofile.read(len(linesep)) != linesep: ofile.seek(0, os.SEEK_END) ofile.write(linesep) # Append lines in text mode with salt.utils.files.fopen(path, 'a') as ofile: for new_line in args: ofile.write( salt.utils.stringutils.to_str( '{0}{1}'.format(new_line, os.linesep) ) ) return 'Wrote {0} lines to "{1}"'.format(len(args), path) def prepend(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Prepend text to the beginning of a file path path to file `*args` strings to prepend to the file CLI Example: .. code-block:: bash salt '*' file.prepend /etc/motd \\ "With all thine offerings thou shalt offer salt." \\ "Salt is what makes things taste bad when it isn't in them." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.prepend /etc/motd args='cheese=spam' salt '*' file.prepend /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] try: with salt.utils.files.fopen(path) as fhr: contents = [salt.utils.stringutils.to_unicode(line) for line in fhr.readlines()] except IOError: contents = [] preface = [] for line in args: preface.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, 'w') as ofile: contents = preface + contents ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Prepended {0} lines to "{1}"'.format(len(args), path) def write(path, *args, **kwargs): ''' .. versionadded:: 2014.7.0 Write text to a file, overwriting any existing contents. path path to file `*args` strings to write to the file CLI Example: .. code-block:: bash salt '*' file.write /etc/motd \\ "With all thine offerings thou shalt offer salt." .. admonition:: Attention If you need to pass a string to append and that string contains an equal sign, you **must** include the argument name, args. For example: .. code-block:: bash salt '*' file.write /etc/motd args='cheese=spam' salt '*' file.write /etc/motd args="['cheese=spam','spam=cheese']" ''' path = os.path.expanduser(path) if 'args' in kwargs: if isinstance(kwargs['args'], list): args = kwargs['args'] else: args = [kwargs['args']] contents = [] for line in args: contents.append('{0}\n'.format(line)) with salt.utils.files.fopen(path, "w") as ofile: ofile.write(salt.utils.stringutils.to_str(''.join(contents))) return 'Wrote {0} lines to "{1}"'.format(len(contents), path) def touch(name, atime=None, mtime=None): ''' .. versionadded:: 0.9.5 Just like the ``touch`` command, create a file if it doesn't exist or simply update the atime and mtime if it already does. atime: Access time in Unix epoch time. Set it to 0 to set atime of the file with Unix date of birth. If this parameter isn't set, atime will be set with current time. mtime: Last modification in Unix epoch time. Set it to 0 to set mtime of the file with Unix date of birth. If this parameter isn't set, mtime will be set with current time. CLI Example: .. code-block:: bash salt '*' file.touch /var/log/emptyfile ''' name = os.path.expanduser(name) if atime and atime.isdigit(): atime = int(atime) if mtime and mtime.isdigit(): mtime = int(mtime) try: if not os.path.exists(name): with salt.utils.files.fopen(name, 'a'): pass if atime is None and mtime is None: times = None elif mtime is None and atime is not None: times = (atime, time.time()) elif atime is None and mtime is not None: times = (time.time(), mtime) else: times = (atime, mtime) os.utime(name, times) except TypeError: raise SaltInvocationError('atime and mtime must be integers') except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return os.path.exists(name) def tail(path, lines): ''' .. versionadded:: Neon Read the last n lines from a file path path to file lines number of lines to read CLI Example: .. code-block:: bash salt '*' file.tail /path/to/file 10 ''' path = os.path.expanduser(path) lines_found = [] buffer_size = 4098 if not os.path.isfile(path): raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot tail a binary file: {0}'.format(path)) try: lines = int(lines) except ValueError: raise SaltInvocationError('file.tail: \'lines\' value must be an integer') try: with salt.utils.fopen(path) as tail_fh: blk_cnt = 1 size = os.stat(path).st_size if size > buffer_size: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size), os.linesep) for i in range(lines): while len(data) == 1 and ((blk_cnt * buffer_size) < size): blk_cnt += 1 line = data[0] try: tail_fh.seek(-buffer_size * blk_cnt, os.SEEK_END) data = string.split(tail_fh.read(buffer_size) + line, os.linesep) except IOError: tail_fh.seek(0) data = string.split(tail_fh.read(size - (buffer_size * (blk_cnt - 1))) + line, os.linesep) line = data[-1] data.pop() lines_found.append(line) return lines_found[-lines:] except (OSError, IOError): raise CommandExecutionError('Could not tail \'{0}\''.format(path)) def seek_read(path, size, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and read it path path to file seek amount to read at once offset offset to start into the file CLI Example: .. code-block:: bash salt '*' file.seek_read /path/to/file 4096 0 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_RDONLY) try: os.lseek(seek_fh, int(offset), 0) data = os.read(seek_fh, int(size)) finally: os.close(seek_fh) return data def seek_write(path, data, offset): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and write to it path path to file data data to write to file offset position in file to start writing CLI Example: .. code-block:: bash salt '*' file.seek_write /path/to/file 'some data' 4096 ''' path = os.path.expanduser(path) seek_fh = os.open(path, os.O_WRONLY) try: os.lseek(seek_fh, int(offset), 0) ret = os.write(seek_fh, data) os.fsync(seek_fh) finally: os.close(seek_fh) return ret def truncate(path, length): ''' .. versionadded:: 2014.1.0 Seek to a position on a file and delete everything after that point path path to file length offset into file to truncate CLI Example: .. code-block:: bash salt '*' file.truncate /path/to/file 512 ''' path = os.path.expanduser(path) with salt.utils.files.fopen(path, 'rb+') as seek_fh: seek_fh.truncate(int(length)) def link(src, path): ''' .. versionadded:: 2014.1.0 Create a hard link to a file CLI Example: .. code-block:: bash salt '*' file.link /path/to/file /path/to/link ''' src = os.path.expanduser(src) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.link(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def is_link(path): ''' Check if the path is a symbolic link CLI Example: .. code-block:: bash salt '*' file.is_link /path/to/link ''' # This function exists because os.path.islink does not support Windows, # therefore a custom function will need to be called. This function # therefore helps API consistency by providing a single function to call for # both operating systems. return os.path.islink(os.path.expanduser(path)) def symlink(src, path): ''' Create a symbolic link (symlink, soft link) to a file CLI Example: .. code-block:: bash salt '*' file.symlink /path/to/file /path/to/link ''' path = os.path.expanduser(path) try: if os.path.normpath(os.readlink(path)) == os.path.normpath(src): log.debug('link already in correct state: %s -> %s', path, src) return True except OSError: pass if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: os.symlink(src, path) return True except (OSError, IOError): raise CommandExecutionError('Could not create \'{0}\''.format(path)) return False def rename(src, dst): ''' Rename a file or directory CLI Example: .. code-block:: bash salt '*' file.rename /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') try: os.rename(src, dst) return True except OSError: raise CommandExecutionError( 'Could not rename \'{0}\' to \'{1}\''.format(src, dst) ) return False def copy(src, dst, recurse=False, remove_existing=False): ''' Copy a file or directory from source to dst In order to copy a directory, the recurse flag is required, and will by default overwrite files in the destination with the same path, and retain all other existing files. (similar to cp -r on unix) remove_existing will remove all files in the target directory, and then copy files from the source. .. note:: The copy function accepts paths that are local to the Salt minion. This function does not support salt://, http://, or the other additional file paths that are supported by :mod:`states.file.managed <salt.states.file.managed>` and :mod:`states.file.recurse <salt.states.file.recurse>`. CLI Example: .. code-block:: bash salt '*' file.copy /path/to/src /path/to/dst salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True remove_existing=True ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must be absolute.') if not os.path.exists(src): raise CommandExecutionError('No such file or directory \'{0}\''.format(src)) if not salt.utils.platform.is_windows(): pre_user = get_user(src) pre_group = get_group(src) pre_mode = salt.utils.files.normalize_mode(get_mode(src)) try: if (os.path.exists(dst) and os.path.isdir(dst)) or os.path.isdir(src): if not recurse: raise SaltInvocationError( "Cannot copy overwriting a directory without recurse flag set to true!") if remove_existing: if os.path.exists(dst): shutil.rmtree(dst) shutil.copytree(src, dst) else: salt.utils.files.recursive_copy(src, dst) else: shutil.copyfile(src, dst) except OSError: raise CommandExecutionError( 'Could not copy \'{0}\' to \'{1}\''.format(src, dst) ) if not salt.utils.platform.is_windows(): check_perms(dst, None, pre_user, pre_group, pre_mode) return True def lstat(path): ''' .. versionadded:: 2014.1.0 Returns the lstat attributes for the given file or dir. Does not support symbolic links. CLI Example: .. code-block:: bash salt '*' file.lstat /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to file must be absolute.') try: lst = os.lstat(path) return dict((key, getattr(lst, key)) for key in ('st_atime', 'st_ctime', 'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid')) except Exception: return {} def access(path, mode): ''' .. versionadded:: 2014.1.0 Test whether the Salt process has the specified access to the file. One of the following modes must be specified: .. code-block::text f: Test the existence of the path r: Test the readability of the path w: Test the writability of the path x: Test whether the path can be executed CLI Example: .. code-block:: bash salt '*' file.access /path/to/file f salt '*' file.access /path/to/file x ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') modes = {'f': os.F_OK, 'r': os.R_OK, 'w': os.W_OK, 'x': os.X_OK} if mode in modes: return os.access(path, modes[mode]) elif mode in six.itervalues(modes): return os.access(path, mode) else: raise SaltInvocationError('Invalid mode specified.') def read(path, binary=False): ''' .. versionadded:: 2017.7.0 Return the content of the file. CLI Example: .. code-block:: bash salt '*' file.read /path/to/file ''' access_mode = 'r' if binary is True: access_mode += 'b' with salt.utils.files.fopen(path, access_mode) as file_obj: return salt.utils.stringutils.to_unicode(file_obj.read()) def readlink(path, canonicalize=False): ''' .. versionadded:: 2014.1.0 Return the path that a symlink points to If canonicalize is set to True, then it return the final target CLI Example: .. code-block:: bash salt '*' file.readlink /path/to/link ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Path to link must be absolute.') if not os.path.islink(path): raise SaltInvocationError('A valid link was not specified.') if canonicalize: return os.path.realpath(path) else: return os.readlink(path) def readdir(path): ''' .. versionadded:: 2014.1.0 Return a list containing the contents of a directory CLI Example: .. code-block:: bash salt '*' file.readdir /path/to/dir/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('Dir path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') dirents = ['.', '..'] dirents.extend(os.listdir(path)) return dirents def statvfs(path): ''' .. versionadded:: 2014.1.0 Perform a statvfs call against the filesystem that the file resides on CLI Example: .. code-block:: bash salt '*' file.statvfs /path/to/file ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') try: stv = os.statvfs(path) return dict((key, getattr(stv, key)) for key in ('f_bavail', 'f_bfree', 'f_blocks', 'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag', 'f_frsize', 'f_namemax')) except (OSError, IOError): raise CommandExecutionError('Could not statvfs \'{0}\''.format(path)) return False def stats(path, hash_type=None, follow_symlinks=True): ''' Return a dict containing the stats for a given file CLI Example: .. code-block:: bash salt '*' file.stats /etc/passwd ''' path = os.path.expanduser(path) ret = {} if not os.path.exists(path): try: # Broken symlinks will return False for os.path.exists(), but still # have a uid and gid pstat = os.lstat(path) except OSError: # Not a broken symlink, just a nonexistent path # NOTE: The file.directory state checks the content of the error # message in this exception. Any changes made to the message for this # exception will reflect the file.directory state as well, and will # likely require changes there. raise CommandExecutionError('Path not found: {0}'.format(path)) else: if follow_symlinks: pstat = os.stat(path) else: pstat = os.lstat(path) ret['inode'] = pstat.st_ino ret['uid'] = pstat.st_uid ret['gid'] = pstat.st_gid ret['group'] = gid_to_group(pstat.st_gid) ret['user'] = uid_to_user(pstat.st_uid) ret['atime'] = pstat.st_atime ret['mtime'] = pstat.st_mtime ret['ctime'] = pstat.st_ctime ret['size'] = pstat.st_size ret['mode'] = six.text_type(oct(stat.S_IMODE(pstat.st_mode))) if hash_type: ret['sum'] = get_hash(path, hash_type) ret['type'] = 'file' if stat.S_ISDIR(pstat.st_mode): ret['type'] = 'dir' if stat.S_ISCHR(pstat.st_mode): ret['type'] = 'char' if stat.S_ISBLK(pstat.st_mode): ret['type'] = 'block' if stat.S_ISREG(pstat.st_mode): ret['type'] = 'file' if stat.S_ISLNK(pstat.st_mode): ret['type'] = 'link' if stat.S_ISFIFO(pstat.st_mode): ret['type'] = 'pipe' if stat.S_ISSOCK(pstat.st_mode): ret['type'] = 'socket' ret['target'] = os.path.realpath(path) return ret def rmdir(path): ''' .. versionadded:: 2014.1.0 Remove the specified directory. Fails if a directory is not empty. CLI Example: .. code-block:: bash salt '*' file.rmdir /tmp/foo/ ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') if not os.path.isdir(path): raise SaltInvocationError('A valid directory was not specified.') try: os.rmdir(path) return True except OSError as exc: return exc.strerror def remove(path, **kwargs): ''' Remove the named file. If a directory is supplied, it will be recursively deleted. CLI Example: .. code-block:: bash salt '*' file.remove /tmp/foo ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute: {0}'.format(path)) try: if os.path.isfile(path) or os.path.islink(path): os.remove(path) return True elif os.path.isdir(path): shutil.rmtree(path) return True except (OSError, IOError) as exc: raise CommandExecutionError( 'Could not remove \'{0}\': {1}'.format(path, exc) ) return False def directory_exists(path): ''' Tests to see if path is a valid directory. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.directory_exists /etc ''' return os.path.isdir(os.path.expanduser(path)) def file_exists(path): ''' Tests to see if path is a valid file. Returns True/False. CLI Example: .. code-block:: bash salt '*' file.file_exists /etc/passwd ''' return os.path.isfile(os.path.expanduser(path)) def path_exists_glob(path): ''' Tests to see if path after expansion is a valid path (file or directory). Expansion allows usage of ? * and character ranges []. Tilde expansion is not supported. Returns True/False. .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' file.path_exists_glob /etc/pam*/pass* ''' return True if glob.glob(os.path.expanduser(path)) else False def restorecon(path, recursive=False): ''' Reset the SELinux context on a given path CLI Example: .. code-block:: bash salt '*' file.restorecon /home/user/.ssh/authorized_keys ''' if recursive: cmd = ['restorecon', '-FR', path] else: cmd = ['restorecon', '-F', path] return not __salt__['cmd.retcode'](cmd, python_shell=False) def get_selinux_context(path): ''' Get an SELinux context from a given path CLI Example: .. code-block:: bash salt '*' file.get_selinux_context /etc/hosts ''' out = __salt__['cmd.run'](['ls', '-Z', path], python_shell=False) try: ret = re.search(r'\w+:\w+:\w+:\w+', out).group(0) except AttributeError: ret = ( 'No selinux context information is available for {0}'.format(path) ) return ret def set_selinux_context(path, user=None, role=None, type=None, # pylint: disable=W0622 range=None, # pylint: disable=W0622 persist=False): ''' .. versionchanged:: Neon Added persist option Set a specific SELinux label on a given path CLI Example: .. code-block:: bash salt '*' file.set_selinux_context path <user> <role> <type> <range> salt '*' file.set_selinux_context /etc/yum.repos.d/epel.repo system_u object_r system_conf_t s0 ''' if not any((user, role, type, range)): return False if persist: fcontext_result = __salt__['selinux.fcontext_add_policy'](path, sel_type=type, sel_user=user, sel_level=range) if fcontext_result.get('retcode', None) is not 0: # Problem setting fcontext policy raise CommandExecutionError( 'Problem setting fcontext: {0}'.format(fcontext_result) ) cmd = ['chcon'] if user: cmd.extend(['-u', user]) if role: cmd.extend(['-r', role]) if type: cmd.extend(['-t', type]) if range: cmd.extend(['-l', range]) cmd.append(path) ret = not __salt__['cmd.retcode'](cmd, python_shell=False) if ret: return get_selinux_context(path) else: return ret def source_list(source, source_hash, saltenv): ''' Check the source list and return the source to use CLI Example: .. code-block:: bash salt '*' file.source_list salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' base ''' contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv) if contextkey in __context__: return __context__[contextkey] # get the master file list if isinstance(source, list): mfiles = [(f, saltenv) for f in __salt__['cp.list_master'](saltenv)] mdirs = [(d, saltenv) for d in __salt__['cp.list_master_dirs'](saltenv)] for single in source: if isinstance(single, dict): single = next(iter(single)) path, senv = salt.utils.url.parse(single) if senv: mfiles += [(f, senv) for f in __salt__['cp.list_master'](senv)] mdirs += [(d, senv) for d in __salt__['cp.list_master_dirs'](senv)] ret = None for single in source: if isinstance(single, dict): # check the proto, if it is http or ftp then download the file # to check, if it is salt then check the master list # if it is a local file, check if the file exists if len(single) != 1: continue single_src = next(iter(single)) single_hash = single[single_src] if single[single_src] else source_hash urlparsed_single_src = _urlparse(single_src) # Fix this for Windows if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_single_src.scheme.lower() in string.ascii_lowercase: urlparsed_single_src = _urlparse('file://' + single_src) proto = urlparsed_single_src.scheme if proto == 'salt': path, senv = salt.utils.url.parse(single_src) if not senv: senv = saltenv if (path, saltenv) in mfiles or (path, saltenv) in mdirs: ret = (single_src, single_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single_src, single_hash) break elif proto == 'file' and ( os.path.exists(urlparsed_single_src.netloc) or os.path.exists(urlparsed_single_src.path) or os.path.exists(os.path.join( urlparsed_single_src.netloc, urlparsed_single_src.path))): ret = (single_src, single_hash) break elif single_src.startswith(os.sep) and os.path.exists(single_src): ret = (single_src, single_hash) break elif isinstance(single, six.string_types): path, senv = salt.utils.url.parse(single) if not senv: senv = saltenv if (path, senv) in mfiles or (path, senv) in mdirs: ret = (single, source_hash) break urlparsed_src = _urlparse(single) if salt.utils.platform.is_windows(): # urlparse doesn't handle a local Windows path without the # protocol indicator (file://). The scheme will be the # drive letter instead of the protocol. So, we'll add the # protocol and re-parse if urlparsed_src.scheme.lower() in string.ascii_lowercase: urlparsed_src = _urlparse('file://' + single) proto = urlparsed_src.scheme if proto == 'file' and ( os.path.exists(urlparsed_src.netloc) or os.path.exists(urlparsed_src.path) or os.path.exists(os.path.join( urlparsed_src.netloc, urlparsed_src.path))): ret = (single, source_hash) break elif proto.startswith('http') or proto == 'ftp': ret = (single, source_hash) break elif single.startswith(os.sep) and os.path.exists(single): ret = (single, source_hash) break if ret is None: # None of the list items matched raise CommandExecutionError( 'none of the specified sources were found' ) else: ret = (source, source_hash) __context__[contextkey] = ret return ret def apply_template_on_contents( contents, template, context, defaults, saltenv): ''' Return the contents after applying the templating engine contents template string template template format context Overrides default context variables passed to the template. defaults Default context passed to the template. CLI Example: .. code-block:: bash salt '*' file.apply_template_on_contents \\ contents='This is a {{ template }} string.' \\ template=jinja \\ "context={}" "defaults={'template': 'cool'}" \\ saltenv=base ''' if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) # Apply templating contents = salt.utils.templates.TEMPLATE_REGISTRY[template]( contents, from_str=True, to_str=True, context=context_dict, saltenv=saltenv, grains=__opts__['grains'], pillar=__pillar__, salt=__salt__, opts=__opts__)['data'] if six.PY2: contents = contents.encode('utf-8') elif six.PY3 and isinstance(contents, bytes): # bytes -> str contents = contents.decode('utf-8') else: ret = {} ret['result'] = False ret['comment'] = ('Specified template format {0} is not supported' ).format(template) return ret return contents def get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify=False, **kwargs): ''' Return the managed file data for file.managed name location where the file lives on the server template template format source managed source file source_hash hash of the source file source_hash_name When ``source_hash`` refers to a remote file, this specifies the filename to look for in that file. .. versionadded:: 2016.3.5 user Owner of file group Group owner of file mode Permissions of file attrs Attributes of file .. versionadded:: 2018.3.0 context Variables to add to the template context defaults Default values of for context_dict skip_verify If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' file.get_managed /etc/httpd/conf.d/httpd.conf jinja salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' None root root '755' base None None ''' # Copy the file to the minion and templatize it sfn = '' source_sum = {} def _get_local_file_source_sum(path): ''' DRY helper for getting the source_sum value from a locally cached path. ''' return {'hsum': get_hash(path, form='sha256'), 'hash_type': 'sha256'} # If we have a source defined, let's figure out what the hash is if source: urlparsed_source = _urlparse(source) if urlparsed_source.scheme in salt.utils.files.VALID_PROTOS: parsed_scheme = urlparsed_source.scheme else: parsed_scheme = '' parsed_path = os.path.join( urlparsed_source.netloc, urlparsed_source.path).rstrip(os.sep) unix_local_source = parsed_scheme in ('file', '') if parsed_scheme == '': parsed_path = sfn = source if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg elif parsed_scheme == 'file': sfn = parsed_path if not os.path.exists(sfn): msg = 'Local file source {0} does not exist'.format(sfn) return '', {}, msg if parsed_scheme and parsed_scheme.lower() in string.ascii_lowercase: parsed_path = ':'.join([parsed_scheme, parsed_path]) parsed_scheme = 'file' if parsed_scheme == 'salt': source_sum = __salt__['cp.hash_file'](source, saltenv) if not source_sum: return '', {}, 'Source file {0} not found in saltenv \'{1}\''.format(source, saltenv) elif not source_hash and unix_local_source: source_sum = _get_local_file_source_sum(parsed_path) elif not source_hash and source.startswith(os.sep): # This should happen on Windows source_sum = _get_local_file_source_sum(source) else: if not skip_verify: if source_hash: try: source_sum = get_source_sum(name, source, source_hash, source_hash_name, saltenv) except CommandExecutionError as exc: return '', {}, exc.strerror else: msg = ( 'Unable to verify upstream hash of source file {0}, ' 'please set source_hash or set skip_verify to True' .format(salt.utils.url.redact_http_basic_auth(source)) ) return '', {}, msg if source and (template or parsed_scheme in salt.utils.files.REMOTE_PROTOS): # Check if we have the template or remote file cached cache_refetch = False cached_dest = __salt__['cp.is_cached'](source, saltenv) if cached_dest and (source_hash or skip_verify): htype = source_sum.get('hash_type', 'sha256') cached_sum = get_hash(cached_dest, form=htype) if skip_verify: # prev: if skip_verify or cached_sum == source_sum['hsum']: # but `cached_sum == source_sum['hsum']` is elliptical as prev if sfn = cached_dest source_sum = {'hsum': cached_sum, 'hash_type': htype} elif cached_sum != source_sum.get('hsum', __opts__['hash_type']): cache_refetch = True else: sfn = cached_dest # If we didn't have the template or remote file, or the file has been # updated and the cache has to be refreshed, download the file. if not sfn or cache_refetch: try: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum.get('hsum')) except Exception as exc: # A 404 or other error code may raise an exception, catch it # and return a comment that will fail the calling state. _source = salt.utils.url.redact_http_basic_auth(source) return '', {}, 'Failed to cache {0}: {1}'.format(_source, exc) # If cache failed, sfn will be False, so do a truth check on sfn first # as invoking os.path.exists() on a bool raises a TypeError. if not sfn or not os.path.exists(sfn): _source = salt.utils.url.redact_http_basic_auth(source) return sfn, {}, 'Source file \'{0}\' not found'.format(_source) if sfn == name: raise SaltInvocationError( 'Source file cannot be the same as destination' ) if template: if template in salt.utils.templates.TEMPLATE_REGISTRY: context_dict = defaults if defaults else {} if context: context_dict = salt.utils.dictupdate.merge(context_dict, context) data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, name=name, source=source, user=user, group=group, mode=mode, attrs=attrs, saltenv=saltenv, context=context_dict, salt=__salt__, pillar=__pillar__, grains=__opts__['grains'], opts=__opts__, **kwargs) else: return sfn, {}, ('Specified template format {0} is not supported' ).format(template) if data['result']: sfn = data['data'] hsum = get_hash(sfn, form='sha256') source_sum = {'hash_type': 'sha256', 'hsum': hsum} else: __clean_tmp(sfn) return sfn, {}, data['data'] return sfn, source_sum, '' def extract_hash(hash_fn, hash_type='sha256', file_name='', source='', source_hash_name=None): ''' .. versionchanged:: 2016.3.5 Prior to this version, only the ``file_name`` argument was considered for filename matches in the hash file. This would be problematic for cases in which the user was relying on a remote checksum file that they do not control, and they wished to use a different name for that file on the minion from the filename on the remote server (and in the checksum file). For example, managing ``/tmp/myfile.tar.gz`` when the remote file was at ``https://mydomain.tld/different_name.tar.gz``. The :py:func:`file.managed <salt.states.file.managed>` state now also passes this function the source URI as well as the ``source_hash_name`` (if specified). In cases where ``source_hash_name`` is specified, it takes precedence over both the ``file_name`` and ``source``. When it is not specified, ``file_name`` takes precedence over ``source``. This allows for better capability for matching hashes. .. versionchanged:: 2016.11.0 File name and source URI matches are no longer disregarded when ``source_hash_name`` is specified. They will be used as fallback matches if there is no match to the ``source_hash_name`` value. This routine is called from the :mod:`file.managed <salt.states.file.managed>` state to pull a hash from a remote file. Regular expressions are used line by line on the ``source_hash`` file, to find a potential candidate of the indicated hash type. This avoids many problems of arbitrary file layout rules. It specifically permits pulling hash codes from debian ``*.dsc`` files. If no exact match of a hash and filename are found, then the first hash found (if any) will be returned. If no hashes at all are found, then ``None`` will be returned. For example: .. code-block:: yaml openerp_7.0-latest-1.tar.gz: file.managed: - name: /tmp/openerp_7.0-20121227-075624-1_all.deb - source: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.tar.gz - source_hash: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.dsc CLI Example: .. code-block:: bash salt '*' file.extract_hash /path/to/hash/file sha512 /etc/foo ''' hash_len = HASHES.get(hash_type) if hash_len is None: if hash_type: log.warning( 'file.extract_hash: Unsupported hash_type \'%s\', falling ' 'back to matching any supported hash_type', hash_type ) hash_type = '' hash_len_expr = '{0},{1}'.format(min(HASHES_REVMAP), max(HASHES_REVMAP)) else: hash_len_expr = six.text_type(hash_len) filename_separators = string.whitespace + r'\/' if source_hash_name: if not isinstance(source_hash_name, six.string_types): source_hash_name = six.text_type(source_hash_name) source_hash_name_idx = (len(source_hash_name) + 1) * -1 log.debug( 'file.extract_hash: Extracting %s hash for file matching ' 'source_hash_name \'%s\'', 'any supported' if not hash_type else hash_type, source_hash_name ) if file_name: if not isinstance(file_name, six.string_types): file_name = six.text_type(file_name) file_name_basename = os.path.basename(file_name) file_name_idx = (len(file_name_basename) + 1) * -1 if source: if not isinstance(source, six.string_types): source = six.text_type(source) urlparsed_source = _urlparse(source) source_basename = os.path.basename( urlparsed_source.path or urlparsed_source.netloc ) source_idx = (len(source_basename) + 1) * -1 basename_searches = [x for x in (file_name, source) if x] if basename_searches: log.debug( 'file.extract_hash: %s %s hash for file matching%s: %s', 'If no source_hash_name match found, will extract' if source_hash_name else 'Extracting', 'any supported' if not hash_type else hash_type, '' if len(basename_searches) == 1 else ' either of the following', ', '.join(basename_searches) ) partial = None found = {} with salt.utils.files.fopen(hash_fn, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line.strip()) hash_re = r'(?i)(?<![a-z0-9])([a-f0-9]{' + hash_len_expr + '})(?![a-z0-9])' hash_match = re.search(hash_re, line) matched = None if hash_match: matched_hsum = hash_match.group(1) if matched_hsum is not None: matched_type = HASHES_REVMAP.get(len(matched_hsum)) if matched_type is None: # There was a match, but it's not of the correct length # to match one of the supported hash types. matched = None else: matched = {'hsum': matched_hsum, 'hash_type': matched_type} if matched is None: log.debug( 'file.extract_hash: In line \'%s\', no %shash found', line, '' if not hash_type else hash_type + ' ' ) continue if partial is None: partial = matched def _add_to_matches(found, line, match_type, value, matched): log.debug( 'file.extract_hash: Line \'%s\' matches %s \'%s\'', line, match_type, value ) found.setdefault(match_type, []).append(matched) hash_matched = False if source_hash_name: if line.endswith(source_hash_name): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[source_hash_name_idx] in string.whitespace: _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source_hash_name) + r'\s+', line): _add_to_matches(found, line, 'source_hash_name', source_hash_name, matched) hash_matched = True if file_name: if line.endswith(file_name_basename): # Checking the character before where the basename # should start for either whitespace or a path # separator. We can't just rsplit on spaces/whitespace, # because the filename may contain spaces. try: if line[file_name_idx] in filename_separators: _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(file_name) + r'\s+', line): _add_to_matches(found, line, 'file_name', file_name, matched) hash_matched = True if source: if line.endswith(source_basename): # Same as above, we can't just do an rsplit here. try: if line[source_idx] in filename_separators: _add_to_matches(found, line, 'source', source, matched) hash_matched = True except IndexError: pass elif re.match(re.escape(source) + r'\s+', line): _add_to_matches(found, line, 'source', source, matched) hash_matched = True if not hash_matched: log.debug( 'file.extract_hash: Line \'%s\' contains %s hash ' '\'%s\', but line did not meet the search criteria', line, matched['hash_type'], matched['hsum'] ) for found_type, found_str in (('source_hash_name', source_hash_name), ('file_name', file_name), ('source', source)): if found_type in found: if len(found[found_type]) > 1: log.debug( 'file.extract_hash: Multiple %s matches for %s: %s', found_type, found_str, ', '.join( ['{0} ({1})'.format(x['hsum'], x['hash_type']) for x in found[found_type]] ) ) ret = found[found_type][0] log.debug( 'file.extract_hash: Returning %s hash \'%s\' as a match of %s', ret['hash_type'], ret['hsum'], found_str ) return ret if partial: log.debug( 'file.extract_hash: Returning the partially identified %s hash ' '\'%s\'', partial['hash_type'], partial['hsum'] ) return partial log.debug('file.extract_hash: No matches, returning None') return None def check_perms(name, ret, user, group, mode, attrs=None, follow_symlinks=False, seuser=None, serole=None, setype=None, serange=None): ''' .. versionchanged:: Neon Added selinux options Check the permissions on files, modify attributes and chown if needed. File attributes are only verified if lsattr(1) is installed. CLI Example: .. code-block:: bash salt '*' file.check_perms /etc/sudoers '{}' root root 400 ai .. versionchanged:: 2014.1.3 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': [], 'result': True} orig_comment = '' else: orig_comment = ret['comment'] ret['comment'] = [] # Check permissions perms = {} cur = stats(name, follow_symlinks=follow_symlinks) perms['luser'] = cur['user'] perms['lgroup'] = cur['group'] perms['lmode'] = salt.utils.files.normalize_mode(cur['mode']) is_dir = os.path.isdir(name) is_link = os.path.islink(name) if attrs is not None \ and not salt.utils.platform.is_windows() \ and not is_dir and not is_link: try: lattrs = lsattr(name) except SaltInvocationError: lattrs = None if lattrs is not None: # List attributes on file perms['lattrs'] = ''.join(lattrs.get(name, '')) # Remove attributes on file so changes can be enforced. if perms['lattrs']: chattr(name, operator='remove', attributes=perms['lattrs']) # user/group changes if needed, then check if it worked if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid(perms['luser']) ) or ( not salt.utils.platform.is_windows() and user != perms['luser'] ): perms['cuser'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid(perms['lgroup']) ) or ( not salt.utils.platform.is_windows() and group != perms['lgroup'] ): perms['cgroup'] = group if 'cuser' in perms or 'cgroup' in perms: if not __opts__['test']: if os.path.islink(name) and not follow_symlinks: chown_func = lchown else: chown_func = chown if user is None: user = perms['luser'] if group is None: group = perms['lgroup'] try: chown_func(name, user, group) # Python os.chown() does reset the suid and sgid, # that's why setting the right mode again is needed here. set_mode(name, mode) except OSError: ret['result'] = False if user: if isinstance(user, int): user = uid_to_user(user) if (salt.utils.platform.is_windows() and user_to_uid(user) != user_to_uid( get_user(name, follow_symlinks=follow_symlinks)) and user != '' ) or ( not salt.utils.platform.is_windows() and user != get_user(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['user'] = user else: ret['result'] = False ret['comment'].append('Failed to change user to {0}' .format(user)) elif 'cuser' in perms and user != '': ret['changes']['user'] = user if group: if isinstance(group, int): group = gid_to_group(group) if (salt.utils.platform.is_windows() and group_to_gid(group) != group_to_gid( get_group(name, follow_symlinks=follow_symlinks)) and user != '') or ( not salt.utils.platform.is_windows() and group != get_group(name, follow_symlinks=follow_symlinks) and user != '' ): if __opts__['test'] is True: ret['changes']['group'] = group else: ret['result'] = False ret['comment'].append('Failed to change group to {0}' .format(group)) elif 'cgroup' in perms and user != '': ret['changes']['group'] = group if not salt.utils.platform.is_windows() and not is_dir: # Replace attributes on file if it had been removed if perms.get('lattrs', ''): chattr(name, operator='add', attributes=perms['lattrs']) # Mode changes if needed if mode is not None: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: mode = salt.utils.files.normalize_mode(mode) if mode != perms['lmode']: if __opts__['test'] is True: ret['changes']['mode'] = mode else: set_mode(name, mode) if mode != salt.utils.files.normalize_mode(get_mode(name)): ret['result'] = False ret['comment'].append( 'Failed to change mode to {0}'.format(mode) ) else: ret['changes']['mode'] = mode # Modify attributes of file if needed if attrs is not None and not is_dir: # File is a symlink, ignore the mode setting # if follow_symlinks is False if os.path.islink(name) and not follow_symlinks: pass else: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if diff_attrs[0] is not None or diff_attrs[1] is not None: if __opts__['test'] is True: ret['changes']['attrs'] = attrs else: if diff_attrs[0] is not None: chattr(name, operator="add", attributes=diff_attrs[0]) if diff_attrs[1] is not None: chattr(name, operator="remove", attributes=diff_attrs[1]) cmp_attrs = _cmp_attrs(name, attrs) if cmp_attrs[0] is not None or cmp_attrs[1] is not None: ret['result'] = False ret['comment'].append( 'Failed to change attributes to {0}'.format(attrs) ) else: ret['changes']['attrs'] = attrs # Set selinux attributes if needed if salt.utils.platform.is_linux() and (seuser or serole or setype or serange): selinux_error = False try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError: log.error('Unable to get current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to get selinux attributes' ) selinux_error = True if not selinux_error: requested_seuser = None requested_serole = None requested_setype = None requested_serange = None # Only set new selinux variables if updates are needed if seuser and seuser != current_seuser: requested_seuser = seuser if serole and serole != current_serole: requested_serole = serole if setype and setype != current_setype: requested_setype = setype if serange and serange != current_serange: requested_serange = serange if requested_seuser or requested_serole or requested_setype or requested_serange: # selinux updates needed, prep changes output selinux_change_new = '' selinux_change_orig = '' if requested_seuser: selinux_change_new += "User: {0} ".format(requested_seuser) selinux_change_orig += "User: {0} ".format(current_seuser) if requested_serole: selinux_change_new += "Role: {0} ".format(requested_serole) selinux_change_orig += "Role: {0} ".format(current_serole) if requested_setype: selinux_change_new += "Type: {0} ".format(requested_setype) selinux_change_orig += "Type: {0} ".format(current_setype) if requested_serange: selinux_change_new += "Range: {0} ".format(requested_serange) selinux_change_orig += "Range: {0} ".format(current_serange) if __opts__['test']: ret['comment'] = 'File {0} selinux context to be updated'.format(name) ret['result'] = None ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} else: try: # set_selinux_context requires type to be set on any other change if (requested_seuser or requested_serole or requested_serange) and not requested_setype: requested_setype = current_setype result = set_selinux_context(name, user=requested_seuser, role=requested_serole, type=requested_setype, range=requested_serange, persist=True) log.debug('selinux set result: %s', result) current_seuser, current_serole, current_setype, current_serange = result.split(':') except ValueError: log.error('Unable to set current selinux attributes') ret['result'] = False ret['comment'].append( 'Failed to set selinux attributes' ) selinux_error = True if not selinux_error: ret['comment'].append('The file {0} is set to be changed'.format(name)) if requested_seuser: if current_seuser != requested_seuser: ret['comment'].append("Unable to update seuser context") ret['result'] = False if requested_serole: if current_serole != requested_serole: ret['comment'].append("Unable to update serole context") ret['result'] = False if requested_setype: if current_setype != requested_setype: ret['comment'].append("Unable to update setype context") ret['result'] = False if requested_serange: if current_serange != requested_serange: ret['comment'].append("Unable to update serange context") ret['result'] = False ret['changes']['selinux'] = {'Old': selinux_change_orig.strip(), 'New': selinux_change_new.strip()} # Only combine the comment list into a string # after all comments are added above if isinstance(orig_comment, six.string_types): if orig_comment: ret['comment'].insert(0, orig_comment) ret['comment'] = '; '.join(ret['comment']) # Set result to None at the very end of the function, # after all changes have been recorded above if __opts__['test'] is True and ret['changes']: ret['result'] = None return ret, perms def check_managed( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Check to see what changes need to be made for a file CLI Example: .. code-block:: bash salt '*' file.check_managed /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) if comments: __clean_tmp(sfn) return False, comments changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) # Ignore permission for files written temporary directories # Files in any path will still be set correctly using get_managed() if name.startswith(tempfile.gettempdir()): for key in ['user', 'group', 'mode']: changes.pop(key, None) __clean_tmp(sfn) if changes: log.info(changes) comments = ['The following values are set to be changed:\n'] comments.extend('{0}: {1}\n'.format(key, val) for key, val in six.iteritems(changes)) return None, ''.join(comments) return True, 'The file {0} is in the correct state'.format(name) def check_managed_changes( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, keep_mode=False, seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Return a dictionary of what changes need to be made for a file .. versionchanged:: Neon selinux attributes added CLI Example: .. code-block:: bash salt '*' file.check_managed_changes /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base ''' # If the source is a list then find which file exists source, source_hash = source_list(source, # pylint: disable=W0633 source_hash, saltenv) sfn = '' source_sum = None if contents is None: # Gather the source file from the server sfn, source_sum, comments = get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify, **kwargs) # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if comments: __clean_tmp(sfn) raise CommandExecutionError(comments) if sfn and source and keep_mode: if _urlparse(source).scheme in ('salt', 'file') \ or source.startswith('/'): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) changes = check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents, seuser=seuser, serole=serole, setype=setype, serange=serange) __clean_tmp(sfn) return changes def check_file_meta( name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents=None, seuser=None, serole=None, setype=None, serange=None): ''' Check for the changes in the file metadata. CLI Example: .. code-block:: bash salt '*' file.check_file_meta /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' base .. note:: Supported hash types include sha512, sha384, sha256, sha224, sha1, and md5. name Path to file destination sfn Template-processed source file contents source URL to file source source_sum File checksum information as a dictionary .. code-block:: yaml {hash_type: md5, hsum: <md5sum>} user Destination file user owner group Destination file group owner mode Destination file permissions mode attrs Destination file attributes .. versionadded:: 2018.3.0 saltenv Salt environment used to resolve source files contents File contents seuser selinux user attribute .. versionadded:: Neon serole selinux role attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon ''' changes = {} if not source_sum: source_sum = dict() try: lstats = stats(name, hash_type=source_sum.get('hash_type', None), follow_symlinks=False) except CommandExecutionError: lstats = {} if not lstats: changes['newfile'] = name return changes if 'hsum' in source_sum: if source_sum['hsum'] != lstats['sum']: if not sfn and source: sfn = __salt__['cp.cache_file']( source, saltenv, source_hash=source_sum['hsum']) if sfn: try: changes['diff'] = get_diff( name, sfn, template=True, show_filenames=False) except CommandExecutionError as exc: changes['diff'] = exc.strerror else: changes['sum'] = 'Checksum differs' if contents is not None: # Write a tempfile with the static contents tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'w') as tmp_: tmp_.write(salt.utils.stringutils.to_str(contents)) # Compare the static contents with the named file try: differences = get_diff(name, tmp, show_filenames=False) except CommandExecutionError as exc: log.error('Failed to diff files: %s', exc) differences = exc.strerror __clean_tmp(tmp) if differences: if __salt__['config.option']('obfuscate_templates'): changes['diff'] = '<Obfuscated Template>' else: changes['diff'] = differences if not salt.utils.platform.is_windows(): # Check owner if (user is not None and user != lstats['user'] and user != lstats['uid']): changes['user'] = user # Check group if (group is not None and group != lstats['group'] and group != lstats['gid']): changes['group'] = group # Normalize the file mode smode = salt.utils.files.normalize_mode(lstats['mode']) mode = salt.utils.files.normalize_mode(mode) if mode is not None and mode != smode: changes['mode'] = mode if attrs: diff_attrs = _cmp_attrs(name, attrs) if diff_attrs is not None: if attrs is not None \ and (diff_attrs[0] is not None or diff_attrs[1] is not None): changes['attrs'] = attrs # Check selinux if seuser or serole or setype or serange: try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') log.debug( 'Current selinux context user:%s role:%s type:%s range:%s', current_seuser, current_serole, current_setype, current_serange ) except ValueError as exc: log.error('Unable to get current selinux attributes') changes['selinux'] = exc.strerror if seuser and seuser != current_seuser: changes['selinux'] = {"user": seuser} if serole and serole != current_serole: changes['selinux'] = {"role": serole} if setype and setype != current_setype: changes['selinux'] = {"type": setype} if serange and serange != current_serange: changes['selinux'] = {"range": serange} return changes def get_diff(file1, file2, saltenv='base', show_filenames=True, show_changes=True, template=False, source_hash_file1=None, source_hash_file2=None): ''' Return unified diff of two files file1 The first file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, thuis had to be a file local to the minion. file2 The second file to feed into the diff utility .. versionchanged:: 2018.3.0 Can now be either a local or remote file. In earlier releases, this had to be a file on the salt fileserver (i.e. ``salt://somefile.txt``) show_filenames : True Set to ``False`` to hide the filenames in the top two lines of the diff. show_changes : True If set to ``False``, and there are differences, then instead of a diff a simple message stating that show_changes is set to ``False`` will be returned. template : False Set to ``True`` if two templates are being compared. This is not useful except for within states, with the ``obfuscate_templates`` option set to ``True``. .. versionadded:: 2018.3.0 source_hash_file1 If ``file1`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 source_hash_file2 If ``file2`` is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash. .. versionadded:: 2018.3.0 CLI Examples: .. code-block:: bash salt '*' file.get_diff /home/fred/.vimrc salt://users/fred/.vimrc salt '*' file.get_diff /tmp/foo.txt /tmp/bar.txt ''' files = (file1, file2) source_hashes = (source_hash_file1, source_hash_file2) paths = [] errors = [] for filename, source_hash in zip(files, source_hashes): try: # Local file paths will just return the same path back when passed # to cp.cache_file. cached_path = __salt__['cp.cache_file'](filename, saltenv, source_hash=source_hash) if cached_path is False: errors.append( 'File {0} not found'.format( salt.utils.stringutils.to_unicode(filename) ) ) continue paths.append(cached_path) except MinionError as exc: errors.append(salt.utils.stringutils.to_unicode(exc.__str__())) continue if errors: raise CommandExecutionError( 'Failed to cache one or more files', info=errors ) args = [] for filename in paths: try: with salt.utils.files.fopen(filename, 'rb') as fp_: args.append(fp_.readlines()) except (IOError, OSError) as exc: raise CommandExecutionError( 'Failed to read {0}: {1}'.format( salt.utils.stringutils.to_unicode(filename), exc.strerror ) ) if args[0] != args[1]: if template and __salt__['config.option']('obfuscate_templates'): ret = '<Obfuscated Template>' elif not show_changes: ret = '<show_changes=False>' else: bdiff = _binary_replace(*paths) # pylint: disable=no-value-for-parameter if bdiff: ret = bdiff else: if show_filenames: args.extend(paths) ret = __utils__['stringutils.get_diff'](*args) return ret return '' def manage_file(name, sfn, ret, source, source_sum, user, group, mode, attrs, saltenv, backup, makedirs=False, template=None, # pylint: disable=W0613 show_changes=True, contents=None, dir_mode=None, follow_symlinks=True, skip_verify=False, keep_mode=False, encoding=None, encoding_errors='strict', seuser=None, serole=None, setype=None, serange=None, **kwargs): ''' Checks the destination against what was retrieved with get_managed and makes the appropriate modifications (if necessary). name location to place the file sfn location of cached file on the minion This is the path to the file stored on the minion. This file is placed on the minion using cp.cache_file. If the hash sum of that file matches the source_sum, we do not transfer the file to the minion again. This file is then grabbed and if it has template set, it renders the file to be placed into the correct place on the system using salt.files.utils.copyfile() ret The initial state return data structure. Pass in ``None`` to use the default structure. source file reference on the master source_sum sum hash for source user user owner group group owner backup backup_mode attrs attributes to be set on file: '' means remove all of them .. versionadded:: 2018.3.0 makedirs make directories if they do not exist template format of templating show_changes Include diff in state return contents: contents to be placed in the file dir_mode mode for directories created with makedirs skip_verify : False If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.0 keep_mode : False If ``True``, and the ``source`` is a file from the Salt fileserver (or a local file on the minion), the mode of the destination file will be set to the mode of the source file. .. note:: keep_mode does not work with salt-ssh. As a consequence of how the files are transferred to the minion, and the inability to connect back to the master with salt-ssh, salt is unable to stat the file as it exists on the fileserver and thus cannot mirror the mode on the salt-ssh minion encoding If specified, then the specified encoding will be used. Otherwise, the file will be encoded using the system locale (usually UTF-8). See https://docs.python.org/3/library/codecs.html#standard-encodings for the list of available encodings. .. versionadded:: 2017.7.0 encoding_errors : 'strict' Default is ```'strict'```. See https://docs.python.org/2/library/codecs.html#codec-base-classes for the error handling schemes. .. versionadded:: 2017.7.0 seuser selinux user attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon setype selinux type attribute .. versionadded:: Neon serange selinux range attribute .. versionadded:: Neon CLI Example: .. code-block:: bash salt '*' file.manage_file /etc/httpd/conf.d/httpd.conf '' '{}' salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' '' base '' .. versionchanged:: 2014.7.0 ``follow_symlinks`` option added ''' name = os.path.expanduser(name) if not ret: ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} # Ensure that user-provided hash string is lowercase if source_sum and ('hsum' in source_sum): source_sum['hsum'] = source_sum['hsum'].lower() if source: if not sfn: # File is not present, cache it sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) htype = source_sum.get('hash_type', __opts__['hash_type']) # Recalculate source sum now that file has been cached source_sum = { 'hash_type': htype, 'hsum': get_hash(sfn, form=htype) } if keep_mode: if _urlparse(source).scheme in ('salt', 'file', ''): try: mode = __salt__['cp.stat_file'](source, saltenv=saltenv, octal=True) except Exception as exc: log.warning('Unable to stat %s: %s', sfn, exc) # Check changes if the target file exists if os.path.isfile(name) or os.path.islink(name): if os.path.islink(name) and follow_symlinks: real_name = os.path.realpath(name) else: real_name = name # Only test the checksums on files with managed contents if source and not (not follow_symlinks and os.path.islink(real_name)): name_sum = get_hash(real_name, source_sum.get('hash_type', __opts__['hash_type'])) else: name_sum = None # Check if file needs to be replaced if source and (name_sum is None or source_sum.get('hsum', __opts__['hash_type']) != name_sum): if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server or local # source, and we are not skipping checksum verification, then # verify that it matches the specified checksum. if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3}). If the \'source_hash\' value ' 'refers to a remote file with multiple possible ' 'matches, then it may be necessary to set ' '\'source_hash_name\'.'.format( source_sum['hash_type'], source, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # Print a diff equivalent to diff -u old new if __salt__['config.option']('obfuscate_templates'): ret['changes']['diff'] = '<Obfuscated Template>' elif not show_changes: ret['changes']['diff'] = '<show_changes=False>' else: try: ret['changes']['diff'] = get_diff( real_name, sfn, show_filenames=False) except CommandExecutionError as exc: ret['changes']['diff'] = exc.strerror # Pre requisites are met, and the file needs to be replaced, do it try: salt.utils.files.copyfile(sfn, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) try: differences = get_diff( real_name, tmp, show_filenames=False, show_changes=show_changes, template=True) except CommandExecutionError as exc: ret.setdefault('warnings', []).append( 'Failed to detect changes to file: {0}'.format(exc.strerror) ) differences = '' if differences: ret['changes']['diff'] = differences # Pre requisites are met, the file needs to be replaced, do it try: salt.utils.files.copyfile(tmp, real_name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(tmp) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) __clean_tmp(tmp) # Check for changing symlink to regular file here if os.path.islink(name) and not follow_symlinks: if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret try: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) except IOError as io_error: __clean_tmp(sfn) return _error( ret, 'Failed to commit change: {0}'.format(io_error)) ret['changes']['diff'] = \ 'Replace symbolic link with regular file' if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, follow_symlinks, seuser=seuser, serole=serole, setype=setype, serange=serange) if ret['changes']: ret['comment'] = 'File {0} updated'.format( salt.utils.data.decode(name) ) elif not ret['changes'] and ret['result']: ret['comment'] = 'File {0} is in the correct state'.format( salt.utils.data.decode(name) ) if sfn: __clean_tmp(sfn) return ret else: # target file does not exist contain_dir = os.path.dirname(name) def _set_mode_and_make_dirs(name, dir_mode, mode, user, group): # check for existence of windows drive letter if salt.utils.platform.is_windows(): drive, _ = os.path.splitdrive(name) if drive and not os.path.exists(drive): __clean_tmp(sfn) return _error(ret, '{0} drive not present'.format(drive)) if dir_mode is None and mode is not None: # Add execute bit to each nonzero digit in the mode, if # dir_mode was not specified. Otherwise, any # directories created with makedirs_() below can't be # listed via a shell. mode_list = [x for x in six.text_type(mode)][-3:] for idx in range(len(mode_list)): if mode_list[idx] != '0': mode_list[idx] = six.text_type(int(mode_list[idx]) | 1) dir_mode = ''.join(mode_list) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 makedirs_( path=name, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: makedirs_(name, user=user, group=group, mode=dir_mode) if source: # Apply the new file if not sfn: sfn = __salt__['cp.cache_file'](source, saltenv) if not sfn: return _error( ret, 'Source file \'{0}\' not found'.format(source)) # If the downloaded file came from a non salt server source verify # that it matches the intended sum value if not skip_verify \ and _urlparse(source).scheme != 'salt': dl_sum = get_hash(sfn, source_sum['hash_type']) if dl_sum != source_sum['hsum']: ret['comment'] = ( 'Specified {0} checksum for {1} ({2}) does not match ' 'actual checksum ({3})'.format( source_sum['hash_type'], name, source_sum['hsum'], dl_sum ) ) ret['result'] = False return ret # It is a new file, set the diff accordingly ret['changes']['diff'] = 'New file' if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') else: # source != True if not os.path.isdir(contain_dir): if makedirs: _set_mode_and_make_dirs(name, dir_mode, mode, user, group) else: __clean_tmp(sfn) # No changes actually made ret['changes'].pop('diff', None) return _error(ret, 'Parent directory not present') # Create the file, user rw-only if mode will be set to prevent # a small security race problem before the permissions are set with salt.utils.files.set_umask(0o077 if mode else None): # Create a new file when test is False and source is None if contents is None: if not __opts__['test']: if touch(name): ret['changes']['new'] = 'file {0} created'.format(name) ret['comment'] = 'Empty file' else: return _error( ret, 'Empty file {0} not created'.format(name) ) else: if not __opts__['test']: if touch(name): ret['changes']['diff'] = 'New file' else: return _error( ret, 'File {0} not created'.format(name) ) if contents is not None: # Write the static contents to a temporary file tmp = salt.utils.files.mkstemp(prefix=salt.utils.files.TEMPFILE_PREFIX, text=True) with salt.utils.files.fopen(tmp, 'wb') as tmp_: if encoding: if salt.utils.platform.is_windows(): contents = os.linesep.join( _splitlines_preserving_trailing_newline(contents)) log.debug('File will be encoded with %s', encoding) tmp_.write(contents.encode(encoding=encoding, errors=encoding_errors)) else: tmp_.write(salt.utils.stringutils.to_bytes(contents)) # Copy into place salt.utils.files.copyfile(tmp, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(tmp) # Now copy the file contents if there is a source file elif sfn: salt.utils.files.copyfile(sfn, name, __salt__['config.backup_mode'](backup), __opts__['cachedir']) __clean_tmp(sfn) # This is a new file, if no mode specified, use the umask to figure # out what mode to use for the new file. if mode is None and not salt.utils.platform.is_windows(): # Get current umask mask = salt.utils.files.get_umask() # Calculate the mode value that results from the umask mode = oct((0o777 ^ mask) & 0o666) if salt.utils.platform.is_windows(): # This function resides in win_file.py and will be available # on Windows. The local function will be overridden # pylint: disable=E1120,E1121,E1123 ret = check_perms( path=name, ret=ret, owner=kwargs.get('win_owner'), grant_perms=kwargs.get('win_perms'), deny_perms=kwargs.get('win_deny_perms'), inheritance=kwargs.get('win_inheritance', True), reset=kwargs.get('win_perms_reset', False)) # pylint: enable=E1120,E1121,E1123 else: ret, _ = check_perms(name, ret, user, group, mode, attrs, seuser=seuser, serole=serole, setype=setype, serange=serange) if not ret['comment']: ret['comment'] = 'File ' + name + ' updated' if __opts__['test']: ret['comment'] = 'File ' + name + ' not updated' elif not ret['changes'] and ret['result']: ret['comment'] = 'File ' + name + ' is in the correct state' if sfn: __clean_tmp(sfn) return ret def mkdir(dir_path, user=None, group=None, mode=None): ''' Ensure that a directory is available. CLI Example: .. code-block:: bash salt '*' file.mkdir /opt/jetty/context ''' dir_path = os.path.expanduser(dir_path) directory = os.path.normpath(dir_path) if not os.path.isdir(directory): # If a caller such as managed() is invoked with makedirs=True, make # sure that any created dirs are created with the same user and group # to follow the principal of least surprise method. makedirs_perms(directory, user, group, mode) return True def makedirs_(path, user=None, group=None, mode=None): ''' Ensure that the directory containing this path is available. .. note:: The path must end with a trailing slash otherwise the directory/directories will be created up to the parent directory. For example if path is ``/opt/code``, then it would be treated as ``/opt/`` but if the path ends with a trailing slash like ``/opt/code/``, then it would be treated as ``/opt/code/``. CLI Example: .. code-block:: bash salt '*' file.makedirs /opt/code/ ''' path = os.path.expanduser(path) if mode: mode = salt.utils.files.normalize_mode(mode) # walk up the directory structure until we find the first existing # directory dirname = os.path.normpath(os.path.dirname(path)) if os.path.isdir(dirname): # There's nothing for us to do msg = 'Directory \'{0}\' already exists'.format(dirname) log.debug(msg) return msg if os.path.exists(dirname): msg = 'The path \'{0}\' already exists and is not a directory'.format( dirname ) log.debug(msg) return msg directories_to_create = [] while True: if os.path.isdir(dirname): break directories_to_create.append(dirname) current_dirname = dirname dirname = os.path.dirname(dirname) if current_dirname == dirname: raise SaltInvocationError( 'Recursive creation for path \'{0}\' would result in an ' 'infinite loop. Please use an absolute path.'.format(dirname) ) # create parent directories from the topmost to the most deeply nested one directories_to_create.reverse() for directory_to_create in directories_to_create: # all directories have the user, group and mode set!! log.debug('Creating directory: %s', directory_to_create) mkdir(directory_to_create, user=user, group=group, mode=mode) def makedirs_perms(name, user=None, group=None, mode='0755'): ''' Taken and modified from os.makedirs to set user, group and mode for each directory created. CLI Example: .. code-block:: bash salt '*' file.makedirs_perms /opt/code ''' name = os.path.expanduser(name) path = os.path head, tail = path.split(name) if not tail: head, tail = path.split(head) if head and tail and not path.exists(head): try: makedirs_perms(head, user, group, mode) except OSError as exc: # be happy if someone already created the path if exc.errno != errno.EEXIST: raise if tail == os.curdir: # xxx/newdir/. exists if xxx/newdir exists return os.mkdir(name) check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) def get_devmm(name): ''' Get major/minor info from a device CLI Example: .. code-block:: bash salt '*' file.get_devmm /dev/chr ''' name = os.path.expanduser(name) if is_chrdev(name) or is_blkdev(name): stat_structure = os.stat(name) return ( os.major(stat_structure.st_rdev), os.minor(stat_structure.st_rdev)) else: return (0, 0) def is_chrdev(name): ''' Check if a file exists and is a character device. CLI Example: .. code-block:: bash salt '*' file.is_chrdev /dev/chr ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the character device does not exist in the first place return False else: raise return stat.S_ISCHR(stat_structure.st_mode) def mknod_chrdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a character device. CLI Example: .. code-block:: bash salt '*' file.mknod_chrdev /dev/chr 180 31 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating character device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFCHR, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created character device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_blkdev(name): ''' Check if a file exists and is a block device. CLI Example: .. code-block:: bash salt '*' file.is_blkdev /dev/blk ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the block device does not exist in the first place return False else: raise return stat.S_ISBLK(stat_structure.st_mode) def mknod_blkdev(name, major, minor, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a block device. CLI Example: .. code-block:: bash salt '*' file.mknod_blkdev /dev/blk 8 999 ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating block device name:%s major:%s minor:%s mode:%s', name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = None else: if os.mknod(name, int(six.text_type(mode).lstrip('0Oo'), 8) | stat.S_IFBLK, os.makedev(major, minor)) is None: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there....however, if you are trying to change the # major/minor, you will need to unlink it first as os.mknod will not overwrite if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created block device check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def is_fifo(name): ''' Check if a file exists and is a FIFO. CLI Example: .. code-block:: bash salt '*' file.is_fifo /dev/fifo ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno == errno.ENOENT: # If the fifo does not exist in the first place return False else: raise return stat.S_ISFIFO(stat_structure.st_mode) def mknod_fifo(name, user=None, group=None, mode='0660'): ''' .. versionadded:: 0.17.0 Create a FIFO pipe. CLI Example: .. code-block:: bash salt '*' file.mknod_fifo /dev/fifo ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} log.debug('Creating FIFO name: %s', name) try: if __opts__['test']: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = None else: if os.mkfifo(name, int(six.text_type(mode).lstrip('0Oo'), 8)) is None: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} ret['result'] = True except OSError as exc: # be happy it is already there if exc.errno != errno.EEXIST: raise else: ret['comment'] = 'File {0} exists and cannot be overwritten'.format(name) # quick pass at verifying the permissions of the newly created fifo check_perms(name, None, user, group, int('{0}'.format(mode)) if mode else None) return ret def mknod(name, ntype, major=0, minor=0, user=None, group=None, mode='0600'): ''' .. versionadded:: 0.17.0 Create a block device, character device, or fifo pipe. Identical to the gnu mknod. CLI Examples: .. code-block:: bash salt '*' file.mknod /dev/chr c 180 31 salt '*' file.mknod /dev/blk b 8 999 salt '*' file.nknod /dev/fifo p ''' ret = False makedirs_(name, user, group) if ntype == 'c': ret = mknod_chrdev(name, major, minor, user, group, mode) elif ntype == 'b': ret = mknod_blkdev(name, major, minor, user, group, mode) elif ntype == 'p': ret = mknod_fifo(name, user, group, mode) else: raise SaltInvocationError( 'Node type unavailable: \'{0}\'. Available node types are ' 'character (\'c\'), block (\'b\'), and pipe (\'p\').'.format(ntype) ) return ret def list_backups(path, limit=None): ''' .. versionadded:: 0.17.0 Lists the previous versions of a file backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups /foo/bar/baz.txt ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows src_dir = parent_dir.replace(':', '_') else: src_dir = parent_dir[1:] # Figure out full path of location of backup file in minion cache bkdir = os.path.join(bkroot, src_dir) if not os.path.isdir(bkdir): return {} files = {} for fname in [x for x in os.listdir(bkdir) if os.path.isfile(os.path.join(bkdir, x))]: if salt.utils.platform.is_windows(): # ':' is an illegal filesystem path character on Windows strpfmt = '{0}_%a_%b_%d_%H-%M-%S_%f_%Y'.format(basename) else: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(fname, strpfmt) except ValueError: # File didn't match the strp format string, so it's not a backup # for this file. Move on to the next one. continue if salt.utils.platform.is_windows(): str_format = '%a %b %d %Y %H-%M-%S.%f' else: str_format = '%a %b %d %Y %H:%M:%S.%f' files.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime(str_format) location = os.path.join(bkdir, fname) files[timestamp]['Size'] = os.stat(location).st_size files[timestamp]['Location'] = location return dict(list(zip( list(range(len(files))), [files[x] for x in sorted(files, reverse=True)[:limit]] ))) list_backup = salt.utils.functools.alias_function(list_backups, 'list_backup') def list_backups_dir(path, limit=None): ''' Lists the previous versions of a directory backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The directory on the minion to check for backups limit Limit the number of results to the most recent N backups CLI Example: .. code-block:: bash salt '*' file.list_backups_dir /foo/bar/baz/ ''' path = os.path.expanduser(path) try: limit = int(limit) except TypeError: pass except ValueError: log.error('file.list_backups_dir: \'limit\' value must be numeric') limit = None bkroot = _get_bkroot() parent_dir, basename = os.path.split(path) # Figure out full path of location of backup folder in minion cache bkdir = os.path.join(bkroot, parent_dir[1:]) if not os.path.isdir(bkdir): return {} files = {} f = dict([(i, len(list(n))) for i, n in itertools.groupby([x.split("_")[0] for x in sorted(os.listdir(bkdir))])]) ff = os.listdir(bkdir) for i, n in six.iteritems(f): ssfile = {} for x in sorted(ff): basename = x.split('_')[0] if i == basename: strpfmt = '{0}_%a_%b_%d_%H:%M:%S_%f_%Y'.format(basename) try: timestamp = datetime.datetime.strptime(x, strpfmt) except ValueError: # Folder didn't match the strp format string, so it's not a backup # for this folder. Move on to the next one. continue ssfile.setdefault(timestamp, {})['Backup Time'] = \ timestamp.strftime('%a %b %d %Y %H:%M:%S.%f') location = os.path.join(bkdir, x) ssfile[timestamp]['Size'] = os.stat(location).st_size ssfile[timestamp]['Location'] = location sfiles = dict(list(zip(list(range(n)), [ssfile[x] for x in sorted(ssfile, reverse=True)[:limit]]))) sefiles = {i: sfiles} files.update(sefiles) return files def restore_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Restore a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to restore, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.restore_backup /foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) # Note: This only supports minion backups, so this function will need to be # modified if/when master backups are implemented. ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret salt.utils.files.backup_minion(path, _get_bkroot()) try: shutil.copyfile(backup['Location'], path) except IOError as exc: ret['comment'] = \ 'Unable to restore {0} to {1}: ' \ '{2}'.format(backup['Location'], path, exc) return ret else: ret['result'] = True ret['comment'] = 'Successfully restored {0} to ' \ '{1}'.format(backup['Location'], path) # Try to set proper ownership if not salt.utils.platform.is_windows(): try: fstat = os.stat(path) except (OSError, IOError): ret['comment'] += ', but was unable to set ownership' else: os.chown(path, fstat.st_uid, fstat.st_gid) return ret def delete_backup(path, backup_id): ''' .. versionadded:: 0.17.0 Delete a previous version of a file that was backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups backup_id The numeric id for the backup you wish to delete, as found using :mod:`file.list_backups <salt.modules.file.list_backups>` CLI Example: .. code-block:: bash salt '*' file.delete_backup /var/cache/salt/minion/file_backup/home/foo/bar/baz.txt 0 ''' path = os.path.expanduser(path) ret = {'result': False, 'comment': 'Invalid backup_id \'{0}\''.format(backup_id)} try: if len(six.text_type(backup_id)) == len(six.text_type(int(backup_id))): backup = list_backups(path)[int(backup_id)] else: return ret except ValueError: return ret except KeyError: ret['comment'] = 'backup_id \'{0}\' does not exist for ' \ '{1}'.format(backup_id, path) return ret try: os.remove(backup['Location']) except IOError as exc: ret['comment'] = 'Unable to remove {0}: {1}'.format(backup['Location'], exc) else: ret['result'] = True ret['comment'] = 'Successfully removed {0}'.format(backup['Location']) return ret remove_backup = salt.utils.functools.alias_function(delete_backup, 'remove_backup') def grep(path, pattern, *opts): ''' Grep for a string in the specified file .. note:: This function's return value is slated for refinement in future versions of Salt path Path to the file to be searched .. note:: Globbing is supported (i.e. ``/var/log/foo/*.log``, but if globbing is being used then the path should be quoted to keep the shell from attempting to expand the glob expression. pattern Pattern to match. For example: ``test``, or ``a[0-5]`` opts Additional command-line flags to pass to the grep command. For example: ``-v``, or ``-i -B2`` .. note:: The options should come after a double-dash (as shown in the examples below) to keep Salt's own argument parser from interpreting them. CLI Example: .. code-block:: bash salt '*' file.grep /etc/passwd nobody salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i -B2 salt '*' file.grep "/etc/sysconfig/network-scripts/*" ipaddr -- -i -l ''' path = os.path.expanduser(path) # Backup the path in case the glob returns nothing _path = path path = glob.glob(path) # If the list is empty no files exist # so we revert back to the original path # so the result is an error. if not path: path = _path split_opts = [] for opt in opts: try: split = salt.utils.args.shlex_split(opt) except AttributeError: split = salt.utils.args.shlex_split(six.text_type(opt)) if len(split) > 1: raise SaltInvocationError( 'Passing multiple command line arguments in a single string ' 'is not supported, please pass the following arguments ' 'separately: {0}'.format(opt) ) split_opts.extend(split) if isinstance(path, list): cmd = ['grep'] + split_opts + [pattern] + path else: cmd = ['grep'] + split_opts + [pattern, path] try: ret = __salt__['cmd.run_all'](cmd, python_shell=False) except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) return ret def open_files(by_pid=False): ''' Return a list of all physical open files on the system. CLI Examples: .. code-block:: bash salt '*' file.open_files salt '*' file.open_files by_pid=True ''' # First we collect valid PIDs pids = {} procfs = os.listdir('/proc/') for pfile in procfs: try: pids[int(pfile)] = [] except ValueError: # Not a valid PID, move on pass # Then we look at the open files for each PID files = {} for pid in pids: ppath = '/proc/{0}'.format(pid) try: tids = os.listdir('{0}/task'.format(ppath)) except OSError: continue # Collect the names of all of the file descriptors fd_ = [] #try: # fd_.append(os.path.realpath('{0}/task/{1}exe'.format(ppath, tid))) #except Exception: # pass for fpath in os.listdir('{0}/fd'.format(ppath)): fd_.append('{0}/fd/{1}'.format(ppath, fpath)) for tid in tids: try: fd_.append( os.path.realpath('{0}/task/{1}/exe'.format(ppath, tid)) ) except OSError: continue for tpath in os.listdir('{0}/task/{1}/fd'.format(ppath, tid)): fd_.append('{0}/task/{1}/fd/{2}'.format(ppath, tid, tpath)) fd_ = sorted(set(fd_)) # Loop through file descriptors and return useful data for each file for fdpath in fd_: # Sometimes PIDs and TIDs disappear before we can query them try: name = os.path.realpath(fdpath) # Running stat on the file cuts out all of the sockets and # deleted files from the list os.stat(name) except OSError: continue if name not in files: files[name] = [pid] else: # We still want to know which PIDs are using each file files[name].append(pid) files[name] = sorted(set(files[name])) pids[pid].append(name) pids[pid] = sorted(set(pids[pid])) if by_pid: return pids return files def pardir(): ''' Return the relative parent directory path symbol for underlying OS .. versionadded:: 2014.7.0 This can be useful when constructing Salt Formulas. .. code-block:: jinja {% set pardir = salt['file.pardir']() %} {% set final_path = salt['file.join']('subdir', pardir, 'confdir') %} CLI Example: .. code-block:: bash salt '*' file.pardir ''' return os.path.pardir def normpath(path): ''' Returns Normalize path, eliminating double slashes, etc. .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.normpath'](tpldir + '/../vars.jinja') import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.normpath 'a/b/c/..' ''' return os.path.normpath(path) def basename(path): ''' Returns the final component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- set filename = salt['file.basename'](source_file) %} CLI Example: .. code-block:: bash salt '*' file.basename 'test/test.config' ''' return os.path.basename(path) def dirname(path): ''' Returns the directory component of a pathname .. versionadded:: 2015.5.0 This can be useful at the CLI but is frequently useful when scripting. .. code-block:: jinja {%- from salt['file.dirname'](tpldir) + '/vars.jinja' import parent_vars %} CLI Example: .. code-block:: bash salt '*' file.dirname 'test/path/filename.config' ''' return os.path.dirname(path) def join(*args): ''' Return a normalized file system path for the underlying OS .. versionadded:: 2014.7.0 This can be useful at the CLI but is frequently useful when scripting combining path variables: .. code-block:: jinja {% set www_root = '/var' %} {% set app_dir = 'myapp' %} myapp_config: file: - managed - name: {{ salt['file.join'](www_root, app_dir, 'config.yaml') }} CLI Example: .. code-block:: bash salt '*' file.join '/' 'usr' 'local' 'bin' ''' return os.path.join(*args) def move(src, dst): ''' Move a file or directory CLI Example: .. code-block:: bash salt '*' file.move /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('Source path must be absolute.') if not os.path.isabs(dst): raise SaltInvocationError('Destination path must be absolute.') ret = { 'result': True, 'comment': "'{0}' moved to '{1}'".format(src, dst), } try: shutil.move(src, dst) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move '{0}' to '{1}': {2}".format(src, dst, exc) ) return ret def diskusage(path): ''' Recursively calculate disk usage of path and return it in bytes CLI Example: .. code-block:: bash salt '*' file.diskusage /path/to/check ''' total_size = 0 seen = set() if os.path.isfile(path): stat_structure = os.stat(path) ret = stat_structure.st_size return ret for dirpath, dirnames, filenames in salt.utils.path.os_walk(path): for f in filenames: fp = os.path.join(dirpath, f) try: stat_structure = os.stat(fp) except OSError: continue if stat_structure.st_ino in seen: continue seen.add(stat_structure.st_ino) total_size += stat_structure.st_size ret = total_size return ret