code
stringlengths
114
1.05M
path
stringlengths
3
312
quality_prob
float64
0.5
0.99
learning_prob
float64
0.2
1
filename
stringlengths
3
168
kind
stringclasses
1 value
import logging import salt.utils.napalm from salt.utils.napalm import proxy_napalm_wrap log = logging.getLogger(__file__) # ---------------------------------------------------------------------------------------------------------------------- # module properties # ---------------------------------------------------------------------------------------------------------------------- __virtualname__ = "probes" __proxyenabled__ = ["napalm"] # uses NAPALM-based proxy to interact with network devices # ---------------------------------------------------------------------------------------------------------------------- # 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 # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # callable functions # ---------------------------------------------------------------------------------------------------------------------- @proxy_napalm_wrap def config(**kwargs): # pylint: disable=unused-argument """ Returns the configuration of the RPM probes. :return: A dictionary containing the configuration of the RPM/SLA probes. CLI Example: .. code-block:: bash salt '*' probes.config Output Example: .. code-block:: python { 'probe1':{ 'test1': { 'probe_type' : 'icmp-ping', 'target' : '192.168.0.1', 'source' : '192.168.0.2', 'probe_count' : 13, 'test_interval': 3 }, 'test2': { 'probe_type' : 'http-ping', 'target' : '172.17.17.1', 'source' : '192.17.17.2', 'probe_count' : 5, 'test_interval': 60 } } } """ return salt.utils.napalm.call( napalm_device, "get_probes_config", **{} # pylint: disable=undefined-variable ) @proxy_napalm_wrap def results(**kwargs): # pylint: disable=unused-argument """ Provides the results of the measurements of the RPM/SLA probes. :return a dictionary with the results of the probes. CLI Example: .. code-block:: bash salt '*' probes.results Output example: .. code-block:: python { 'probe1': { 'test1': { 'last_test_min_delay' : 63.120, 'global_test_min_delay' : 62.912, 'current_test_avg_delay': 63.190, 'global_test_max_delay' : 177.349, 'current_test_max_delay': 63.302, 'global_test_avg_delay' : 63.802, 'last_test_avg_delay' : 63.438, 'last_test_max_delay' : 65.356, 'probe_type' : 'icmp-ping', 'rtt' : 63.138, 'last_test_loss' : 0, 'round_trip_jitter' : -59.0, 'target' : '192.168.0.1', 'source' : '192.168.0.2', 'probe_count' : 15, 'current_test_min_delay': 63.138 }, 'test2': { 'last_test_min_delay' : 176.384, 'global_test_min_delay' : 169.226, 'current_test_avg_delay': 177.098, 'global_test_max_delay' : 292.628, 'current_test_max_delay': 180.055, 'global_test_avg_delay' : 177.959, 'last_test_avg_delay' : 177.178, 'last_test_max_delay' : 184.671, 'probe_type' : 'icmp-ping', 'rtt' : 176.449, 'last_test_loss' : 0, 'round_trip_jitter' : -34.0, 'target' : '172.17.17.1', 'source' : '172.17.17.2', 'probe_count' : 15, 'current_test_min_delay': 176.402 } } } """ return salt.utils.napalm.call( napalm_device, "get_probes_results", **{} # pylint: disable=undefined-variable ) @proxy_napalm_wrap def set_probes( probes, test=False, commit=True, **kwargs ): # pylint: disable=unused-argument """ Configures RPM/SLA probes on the device. Calls the configuration template 'set_probes' from the NAPALM library, providing as input a rich formatted dictionary with the configuration details of the probes to be configured. :param probes: Dictionary formatted as the output of the function config() :param test: Dry run? If set as True, will apply the config, discard and return the changes. Default: False :param commit: Commit? (default: True) Sometimes it is not needed to commit the config immediately after loading the changes. E.g.: a state loads a couple of parts (add / remove / update) and would not be optimal to commit after each operation. Also, from the CLI when the user needs to apply the similar changes before committing, can specify commit=False and will not discard the config. :raise MergeConfigException: If there is an error on the configuration sent. :return a dictionary having the following keys: * result (bool): if the config was applied successfully. It is `False` only in case of failure. In case there are no changes to be applied and successfully performs all operations it is still `True` and so will be the `already_configured` flag (example below) * comment (str): a message for the user * already_configured (bool): flag to check if there were no changes applied * diff (str): returns the config changes applied Input example - via state/script: .. code-block:: python probes = { 'new_probe':{ 'new_test1': { 'probe_type' : 'icmp-ping', 'target' : '192.168.0.1', 'source' : '192.168.0.2', 'probe_count' : 13, 'test_interval': 3 }, 'new_test2': { 'probe_type' : 'http-ping', 'target' : '172.17.17.1', 'source' : '192.17.17.2', 'probe_count' : 5, 'test_interval': 60 } } } set_probes(probes) CLI Example - to push changes on the fly (not recommended): .. code-block:: bash salt 'junos_minion' probes.set_probes "{'new_probe':{'new_test1':{'probe_type':'icmp-ping',\ 'target':'192.168.0.1','source':'192.168.0.2','probe_count':13,'test_interval':3}}}" test=True Output example - for the CLI example above: .. code-block:: yaml junos_minion: ---------- already_configured: False comment: Configuration discarded. diff: [edit services rpm] probe transit { ... } + probe new_probe { + test new_test1 { + probe-type icmp-ping; + target address 192.168.0.1; + probe-count 13; + test-interval 3; + source-address 192.168.0.2; + } + } result: True """ # pylint: disable=undefined-variable return __salt__["net.load_template"]( "set_probes", probes=probes, test=test, commit=commit, inherit_napalm_device=napalm_device, ) # pylint: enable=undefined-variable @proxy_napalm_wrap def delete_probes( probes, test=False, commit=True, **kwargs ): # pylint: disable=unused-argument """ Removes RPM/SLA probes from the network device. Calls the configuration template 'delete_probes' from the NAPALM library, providing as input a rich formatted dictionary with the configuration details of the probes to be removed from the configuration of the device. :param probes: Dictionary with a similar format as the output dictionary of the function config(), where the details are not necessary. :param test: Dry run? If set as True, will apply the config, discard and return the changes. Default: False :param commit: Commit? (default: True) Sometimes it is not needed to commit the config immediately after loading the changes. E.g.: a state loads a couple of parts (add / remove / update) and would not be optimal to commit after each operation. Also, from the CLI when the user needs to apply the similar changes before committing, can specify commit=False and will not discard the config. :raise MergeConfigException: If there is an error on the configuration sent. :return: A dictionary having the following keys: - result (bool): if the config was applied successfully. It is `False` only in case of failure. In case there are no changes to be applied and successfully performs all operations it is still `True` and so will be the `already_configured` flag (example below) - comment (str): a message for the user - already_configured (bool): flag to check if there were no changes applied - diff (str): returns the config changes applied Input example: .. code-block:: python probes = { 'existing_probe':{ 'existing_test1': {}, 'existing_test2': {} } } """ # pylint: disable=undefined-variable return __salt__["net.load_template"]( "delete_probes", probes=probes, test=test, commit=commit, inherit_napalm_device=napalm_device, ) # pylint: enable=undefined-variable @proxy_napalm_wrap def schedule_probes( probes, test=False, commit=True, **kwargs ): # pylint: disable=unused-argument """ Will schedule the probes. On Cisco devices, it is not enough to define the probes, it is also necessary to schedule them. This function calls the configuration template ``schedule_probes`` from the NAPALM library, providing as input a rich formatted dictionary with the names of the probes and the tests to be scheduled. :param probes: Dictionary with a similar format as the output dictionary of the function config(), where the details are not necessary. :param test: Dry run? If set as True, will apply the config, discard and return the changes. Default: False :param commit: Commit? (default: True) Sometimes it is not needed to commit the config immediately after loading the changes. E.g.: a state loads a couple of parts (add / remove / update) and would not be optimal to commit after each operation. Also, from the CLI when the user needs to apply the similar changes before committing, can specify commit=False and will not discard the config. :raise MergeConfigException: If there is an error on the configuration sent. :return: a dictionary having the following keys: - result (bool): if the config was applied successfully. It is `False` only in case of failure. In case there are no changes to be applied and successfully performs all operations it is still `True` and so will be the `already_configured` flag (example below) - comment (str): a message for the user - already_configured (bool): flag to check if there were no changes applied - diff (str): returns the config changes applied Input example: .. code-block:: python probes = { 'new_probe':{ 'new_test1': {}, 'new_test2': {} } } """ # pylint: disable=undefined-variable return __salt__["net.load_template"]( "schedule_probes", probes=probes, test=test, commit=commit, inherit_napalm_device=napalm_device, ) # pylint: enable=undefined-variable
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/napalm_probes.py
0.78609
0.179351
napalm_probes.py
pypi
import logging import salt.utils.path from salt.exceptions import CommandExecutionError logger = logging.getLogger(__name__) # Function alias to make sure not to shadow built-in's __func_alias__ = {"list_": "list"} def __virtual__(): """ Only work when cabal-install is installed. """ return (salt.utils.path.which("cabal") is not None) and ( salt.utils.path.which("ghc-pkg") is not None ) def update(user=None, env=None): """ Updates list of known packages. user The user to run cabal update with env Environment variables to set when invoking cabal. Uses the same ``env`` format as the :py:func:`cmd.run <salt.modules.cmdmod.run>` execution function. CLI Example: .. code-block:: bash salt '*' cabal.update """ return __salt__["cmd.run_all"]("cabal update", runas=user, env=env) def install(pkg=None, pkgs=None, user=None, install_global=False, env=None): """ Install a cabal package. pkg A package name in format accepted by cabal-install. See: https://wiki.haskell.org/Cabal-Install pkgs A list of packages names in same format as ``pkg`` user The user to run cabal install with install_global Install package globally instead of locally env Environment variables to set when invoking cabal. Uses the same ``env`` format as the :py:func:`cmd.run <salt.modules.cmdmod.run>` execution function CLI Example: .. code-block:: bash salt '*' cabal.install shellcheck salt '*' cabal.install shellcheck-0.3.5 """ cmd = ["cabal install"] if install_global: cmd.append("--global") if pkg: cmd.append('"{}"'.format(pkg)) elif pkgs: cmd.append('"{}"'.format('" "'.join(pkgs))) result = __salt__["cmd.run_all"](" ".join(cmd), runas=user, env=env) if result["retcode"] != 0: raise CommandExecutionError(result["stderr"]) return result def list_(pkg=None, user=None, installed=False, env=None): """ List packages matching a search string. pkg Search string for matching package names user The user to run cabal list with installed If True, only return installed packages. env Environment variables to set when invoking cabal. Uses the same ``env`` format as the :py:func:`cmd.run <salt.modules.cmdmod.run>` execution function CLI Example: .. code-block:: bash salt '*' cabal.list salt '*' cabal.list ShellCheck """ cmd = ["cabal list --simple-output"] if installed: cmd.append("--installed") if pkg: cmd.append('"{}"'.format(pkg)) result = __salt__["cmd.run_all"](" ".join(cmd), runas=user, env=env) packages = {} for line in result["stdout"].splitlines(): data = line.split() package_name = data[0] package_version = data[1] packages[package_name] = package_version return packages def uninstall(pkg, user=None, env=None): """ Uninstall a cabal package. pkg The package to uninstall user The user to run ghc-pkg unregister with env Environment variables to set when invoking cabal. Uses the same ``env`` format as the :py:func:`cmd.run <salt.modules.cmdmod.run>` execution function CLI Example: .. code-block:: bash salt '*' cabal.uninstall ShellCheck """ cmd = ["ghc-pkg unregister"] cmd.append('"{}"'.format(pkg)) result = __salt__["cmd.run_all"](" ".join(cmd), runas=user, env=env) if result["retcode"] != 0: raise CommandExecutionError(result["stderr"]) return result
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/cabal.py
0.691081
0.187616
cabal.py
pypi
import logging import os import jinja2 import jinja2.exceptions import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net from salt.exceptions import CommandExecutionError # Set up logging log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, "rh_ip") ) ) # Define the module's virtual name __virtualname__ = "ip" # Default values for bonding _BOND_DEFAULTS = { # 803.ad aggregation selection logic # 0 for stable (default) # 1 for bandwidth # 2 for count "ad_select": "0", # Max number of transmit queues (default = 16) "tx_queues": "16", # lacp_rate 0: Slow - every 30 seconds # lacp_rate 1: Fast - every 1 second "lacp_rate": "0", # Max bonds for this driver "max_bonds": "1", # Used with miimon. # On: driver sends mii # Off: ethtool sends mii "use_carrier": "0", # Default. Don't change unless you know what you are doing. "xmit_hash_policy": "layer2", } _RH_NETWORK_SCRIPT_DIR = "/etc/sysconfig/network-scripts" _RH_NETWORK_FILE = "/etc/sysconfig/network" _CONFIG_TRUE = ("yes", "on", "true", "1", True) _CONFIG_FALSE = ("no", "off", "false", "0", False) _IFACE_TYPES = ( "eth", "bond", "team", "alias", "clone", "ipsec", "dialup", "bridge", "slave", "teamport", "vlan", "ipip", "ib", ) def __virtual__(): """ Confine this module to RHEL/Fedora based distros """ if __grains__["os_family"] == "RedHat": if __grains__["os"] == "Amazon": if __grains__["osmajorrelease"] >= 2: return __virtualname__ else: return __virtualname__ return ( False, "The rh_ip execution module cannot be loaded: this module is only available on" " RHEL/Fedora based distributions.", ) def _error_msg_iface(iface, option, expected): """ Build an appropriate error message from a given option and a list of expected values. """ if isinstance(expected, str): expected = (expected,) msg = "Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]" return msg.format(iface, option, "|".join(str(e) for e in expected)) def _error_msg_routes(iface, option, expected): """ Build an appropriate error message from a given option and a list of expected values. """ msg = "Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]" return msg.format(iface, option, expected) def _log_default_iface(iface, opt, value): log.info( "Using default option -- Interface: %s Option: %s Value: %s", iface, opt, value ) def _error_msg_network(option, expected): """ Build an appropriate error message from a given option and a list of expected values. """ if isinstance(expected, str): expected = (expected,) msg = "Invalid network setting -- Setting: {0}, Expected: [{1}]" return msg.format(option, "|".join(str(e) for e in expected)) def _log_default_network(opt, value): log.info("Using existing setting -- Setting: %s Value: %s", opt, value) def _parse_rh_config(path): rh_config = _read_file(path) cv_rh_config = {} if rh_config: for line in rh_config: line = line.strip() if len(line) == 0 or line.startswith("!") or line.startswith("#"): continue pair = [p.rstrip() for p in line.split("=", 1)] if len(pair) != 2: continue name, value = pair cv_rh_config[name.upper()] = value return cv_rh_config def _parse_ethtool_opts(opts, iface): """ Filters given options and outputs valid settings for ETHTOOLS_OPTS If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. """ config = {} if "autoneg" in opts: if opts["autoneg"] in _CONFIG_TRUE: config.update({"autoneg": "on"}) elif opts["autoneg"] in _CONFIG_FALSE: config.update({"autoneg": "off"}) else: _raise_error_iface(iface, "autoneg", _CONFIG_TRUE + _CONFIG_FALSE) if "duplex" in opts: valid = ["full", "half"] if opts["duplex"] in valid: config.update({"duplex": opts["duplex"]}) else: _raise_error_iface(iface, "duplex", valid) if "speed" in opts: valid = ["10", "100", "1000", "10000"] if str(opts["speed"]) in valid: config.update({"speed": opts["speed"]}) else: _raise_error_iface(iface, opts["speed"], valid) if "advertise" in opts: valid = [ "0x001", "0x002", "0x004", "0x008", "0x010", "0x020", "0x20000", "0x8000", "0x1000", "0x40000", "0x80000", "0x200000", "0x400000", "0x800000", "0x1000000", "0x2000000", "0x4000000", ] if str(opts["advertise"]) in valid: config.update({"advertise": opts["advertise"]}) else: _raise_error_iface(iface, "advertise", valid) if "channels" in opts: channels_cmd = "-L {}".format(iface.strip()) channels_params = [] for option in ("rx", "tx", "other", "combined"): if option in opts["channels"]: valid = range(1, __grains__["num_cpus"] + 1) if opts["channels"][option] in valid: channels_params.append( "{} {}".format(option, opts["channels"][option]) ) else: _raise_error_iface(iface, opts["channels"][option], valid) if channels_params: config.update({channels_cmd: " ".join(channels_params)}) valid = _CONFIG_TRUE + _CONFIG_FALSE for option in ("rx", "tx", "sg", "tso", "ufo", "gso", "gro", "lro"): if option in opts: if opts[option] in _CONFIG_TRUE: config.update({option: "on"}) elif opts[option] in _CONFIG_FALSE: config.update({option: "off"}) else: _raise_error_iface(iface, option, valid) return config def _parse_settings_bond(opts, iface): """ Filters given options and outputs valid settings for requested operation. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. """ if opts["mode"] in ("balance-rr", "0"): log.info("Device: %s Bonding Mode: load balancing (round-robin)", iface) return _parse_settings_bond_0(opts, iface) elif opts["mode"] in ("active-backup", "1"): log.info("Device: %s Bonding Mode: fault-tolerance (active-backup)", iface) return _parse_settings_bond_1(opts, iface) elif opts["mode"] in ("balance-xor", "2"): log.info("Device: %s Bonding Mode: load balancing (xor)", iface) return _parse_settings_bond_2(opts, iface) elif opts["mode"] in ("broadcast", "3"): log.info("Device: %s Bonding Mode: fault-tolerance (broadcast)", iface) return _parse_settings_bond_3(opts, iface) elif opts["mode"] in ("802.3ad", "4"): log.info( "Device: %s Bonding Mode: IEEE 802.3ad Dynamic link aggregation", iface ) return _parse_settings_bond_4(opts, iface) elif opts["mode"] in ("balance-tlb", "5"): log.info("Device: %s Bonding Mode: transmit load balancing", iface) return _parse_settings_bond_5(opts, iface) elif opts["mode"] in ("balance-alb", "6"): log.info("Device: %s Bonding Mode: adaptive load balancing", iface) return _parse_settings_bond_6(opts, iface) else: valid = ( "0", "1", "2", "3", "4", "5", "6", "balance-rr", "active-backup", "balance-xor", "broadcast", "802.3ad", "balance-tlb", "balance-alb", ) _raise_error_iface(iface, "mode", valid) def _parse_settings_miimon(opts, iface): """ Add shared settings for miimon support used by balance-rr, balance-xor bonding types. """ ret = {} for binding in ("miimon", "downdelay", "updelay"): if binding in opts: try: int(opts[binding]) ret.update({binding: opts[binding]}) except Exception: # pylint: disable=broad-except _raise_error_iface(iface, binding, "integer") if "miimon" in opts and "downdelay" not in opts: ret["downdelay"] = ret["miimon"] * 2 if "miimon" in opts: if not opts["miimon"]: _raise_error_iface(iface, "miimon", "nonzero integer") for binding in ("downdelay", "updelay"): if binding in ret: if ret[binding] % ret["miimon"]: _raise_error_iface( iface, binding, "0 or a multiple of miimon ({})".format(ret["miimon"]), ) if "use_carrier" in opts: if opts["use_carrier"] in _CONFIG_TRUE: ret.update({"use_carrier": "1"}) elif opts["use_carrier"] in _CONFIG_FALSE: ret.update({"use_carrier": "0"}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, "use_carrier", valid) else: _log_default_iface(iface, "use_carrier", _BOND_DEFAULTS["use_carrier"]) ret.update({"use_carrier": _BOND_DEFAULTS["use_carrier"]}) return ret def _parse_settings_arp(opts, iface): """ Add shared settings for arp used by balance-rr, balance-xor bonding types. """ ret = {} if "arp_interval" in opts: try: int(opts["arp_interval"]) ret.update({"arp_interval": opts["arp_interval"]}) except Exception: # pylint: disable=broad-except _raise_error_iface(iface, "arp_interval", "integer") # ARP targets in n.n.n.n form valid = "list of ips (up to 16)" if "arp_ip_target" in opts: if isinstance(opts["arp_ip_target"], list): if 1 <= len(opts["arp_ip_target"]) <= 16: ret.update({"arp_ip_target": ",".join(opts["arp_ip_target"])}) else: _raise_error_iface(iface, "arp_ip_target", valid) else: _raise_error_iface(iface, "arp_ip_target", valid) else: _raise_error_iface(iface, "arp_ip_target", valid) return ret def _parse_settings_bond_0(opts, iface): """ Filters given options and outputs valid settings for bond0. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. """ bond = {"mode": "0"} bond.update(_parse_settings_miimon(opts, iface)) bond.update(_parse_settings_arp(opts, iface)) if "miimon" not in opts and "arp_interval" not in opts: _raise_error_iface( iface, "miimon or arp_interval", "at least one of these is required" ) return bond def _parse_settings_bond_1(opts, iface): """ Filters given options and outputs valid settings for bond1. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. """ bond = {"mode": "1"} bond.update(_parse_settings_miimon(opts, iface)) if "miimon" not in opts: _raise_error_iface(iface, "miimon", "integer") if "primary" in opts: bond.update({"primary": opts["primary"]}) return bond def _parse_settings_bond_2(opts, iface): """ Filters given options and outputs valid settings for bond2. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. """ bond = {"mode": "2"} bond.update(_parse_settings_miimon(opts, iface)) bond.update(_parse_settings_arp(opts, iface)) if "miimon" not in opts and "arp_interval" not in opts: _raise_error_iface( iface, "miimon or arp_interval", "at least one of these is required" ) if "hashing-algorithm" in opts: valid = ("layer2", "layer2+3", "layer3+4") if opts["hashing-algorithm"] in valid: bond.update({"xmit_hash_policy": opts["hashing-algorithm"]}) else: _raise_error_iface(iface, "hashing-algorithm", valid) return bond def _parse_settings_bond_3(opts, iface): """ Filters given options and outputs valid settings for bond3. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. """ bond = {"mode": "3"} bond.update(_parse_settings_miimon(opts, iface)) if "miimon" not in opts: _raise_error_iface(iface, "miimon", "integer") return bond def _parse_settings_bond_4(opts, iface): """ Filters given options and outputs valid settings for bond4. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. """ bond = {"mode": "4"} bond.update(_parse_settings_miimon(opts, iface)) if "miimon" not in opts: _raise_error_iface(iface, "miimon", "integer") for binding in ("lacp_rate", "ad_select"): if binding in opts: if binding == "lacp_rate": valid = ("fast", "1", "slow", "0") if opts[binding] not in valid: _raise_error_iface(iface, binding, valid) if opts[binding] == "fast": opts.update({binding: "1"}) if opts[binding] == "slow": opts.update({binding: "0"}) else: valid = "integer" try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: # pylint: disable=broad-except _raise_error_iface(iface, binding, valid) else: _log_default_iface(iface, binding, _BOND_DEFAULTS[binding]) bond.update({binding: _BOND_DEFAULTS[binding]}) if "hashing-algorithm" in opts: if __grains__["os_family"] == "RedHat": # allowing for Amazon 2 based of RHEL/Centos 7 if __grains__["osmajorrelease"] < 8: valid = ("layer2", "layer2+3", "layer3+4", "encap2+3", "encap3+4") else: valid = ( "layer2", "layer2+3", "layer3+4", "encap2+3", "encap3+4", "vlan+srcmac", ) if opts["hashing-algorithm"] in valid: bond.update({"xmit_hash_policy": opts["hashing-algorithm"]}) else: _raise_error_iface(iface, "hashing-algorithm", valid) return bond def _parse_settings_bond_5(opts, iface): """ Filters given options and outputs valid settings for bond5. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. """ bond = {"mode": "5"} bond.update(_parse_settings_miimon(opts, iface)) if "miimon" not in opts: _raise_error_iface(iface, "miimon", "integer") if "primary" in opts: bond.update({"primary": opts["primary"]}) return bond def _parse_settings_bond_6(opts, iface): """ Filters given options and outputs valid settings for bond6. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. """ bond = {"mode": "6"} bond.update(_parse_settings_miimon(opts, iface)) if "miimon" not in opts: _raise_error_iface(iface, "miimon", "integer") if "primary" in opts: bond.update({"primary": opts["primary"]}) return bond def _parse_settings_vlan(opts, iface): """ Filters given options and outputs valid settings for a vlan """ vlan = {} if "reorder_hdr" in opts: if opts["reorder_hdr"] in _CONFIG_TRUE + _CONFIG_FALSE: vlan.update({"reorder_hdr": opts["reorder_hdr"]}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, "reorder_hdr", valid) if "vlan_id" in opts: if opts["vlan_id"] > 0: vlan.update({"vlan_id": opts["vlan_id"]}) else: _raise_error_iface(iface, "vlan_id", "Positive integer") if "phys_dev" in opts: if len(opts["phys_dev"]) > 0: vlan.update({"phys_dev": opts["phys_dev"]}) else: _raise_error_iface(iface, "phys_dev", "Non-empty string") return vlan def _parse_settings_eth(opts, iface_type, enabled, iface): """ Filters given options and outputs valid settings for a network interface. """ result = {"name": iface} if "proto" in opts: valid = ["none", "bootp", "dhcp"] if opts["proto"] in valid: result["proto"] = opts["proto"] else: _raise_error_iface(iface, opts["proto"], valid) if "dns" in opts: result["dns"] = opts["dns"] result["peerdns"] = "yes" if "mtu" in opts: try: result["mtu"] = int(opts["mtu"]) except ValueError: _raise_error_iface(iface, "mtu", ["integer"]) if "hwaddr" in opts and "macaddr" in opts: msg = "Cannot pass both hwaddr and macaddr. Must use either hwaddr or macaddr" log.error(msg) raise AttributeError(msg) if iface_type not in ("bridge",): ethtool = _parse_ethtool_opts(opts, iface) if ethtool: result["ethtool"] = " ".join( ["{} {}".format(x, y) for x, y in ethtool.items()] ) if iface_type == "slave": result["proto"] = "none" if iface_type == "team": result["devicetype"] = "Team" if "team_config" in opts: result["team_config"] = salt.utils.json.dumps(opts["team_config"]) if iface_type == "teamport": result["devicetype"] = "TeamPort" result["team_master"] = opts["team_master"] if "team_port_config" in opts: result["team_port_config"] = salt.utils.json.dumps(opts["team_port_config"]) if iface_type == "bond": if "mode" not in opts: msg = "Missing required option 'mode'" log.error("%s for bond interface '%s'", msg, iface) raise AttributeError(msg) bonding = _parse_settings_bond(opts, iface) if bonding: result["bonding"] = " ".join( ["{}={}".format(x, y) for x, y in bonding.items()] ) result["devtype"] = "Bond" if iface_type == "vlan": vlan = _parse_settings_vlan(opts, iface) if vlan: result["devtype"] = "Vlan" for opt in vlan: result[opt] = opts[opt] if iface_type not in ("bond", "team", "vlan", "bridge", "ipip"): auto_addr = False if "hwaddr" in opts: if salt.utils.validate.net.mac(opts["hwaddr"]): result["hwaddr"] = opts["hwaddr"] elif opts["hwaddr"] == "auto": auto_addr = True elif opts["hwaddr"] != "none": _raise_error_iface( iface, opts["hwaddr"], ("AA:BB:CC:DD:EE:FF", "auto", "none") ) else: auto_addr = True if auto_addr: # If interface type is slave for bond, not setting hwaddr if iface_type != "slave": ifaces = __salt__["network.interfaces"]() if iface in ifaces and "hwaddr" in ifaces[iface]: result["hwaddr"] = ifaces[iface]["hwaddr"] if iface_type == "eth": result["devtype"] = "Ethernet" if iface_type == "bridge": result["devtype"] = "Bridge" bypassfirewall = True valid = _CONFIG_TRUE + _CONFIG_FALSE for opt in ("bypassfirewall",): if opt in opts: if opts[opt] in _CONFIG_TRUE: bypassfirewall = True elif opts[opt] in _CONFIG_FALSE: bypassfirewall = False else: _raise_error_iface(iface, opts[opt], valid) bridgectls = [ "net.bridge.bridge-nf-call-ip6tables", "net.bridge.bridge-nf-call-iptables", "net.bridge.bridge-nf-call-arptables", ] if bypassfirewall: sysctl_value = 0 else: sysctl_value = 1 for sysctl in bridgectls: try: __salt__["sysctl.persist"](sysctl, sysctl_value) except CommandExecutionError: log.warning("Failed to set sysctl: %s", sysctl) else: if "bridge" in opts: result["bridge"] = opts["bridge"] if iface_type == "ipip": result["devtype"] = "IPIP" for opt in ("my_inner_ipaddr", "my_outer_ipaddr"): if opt not in opts: _raise_error_iface(iface, opt, "1.2.3.4") else: result[opt] = opts[opt] if iface_type == "ib": result["devtype"] = "InfiniBand" if "prefix" in opts: if "netmask" in opts: msg = "Cannot use prefix and netmask together" log.error(msg) raise AttributeError(msg) result["prefix"] = opts["prefix"] elif "netmask" in opts: result["netmask"] = opts["netmask"] for opt in ( "ipaddr", "master", "srcaddr", "delay", "domain", "gateway", "uuid", "nickname", "zone", ): if opt in opts: result[opt] = opts[opt] for opt in ("ipv6addr", "ipv6gateway"): if opt in opts: result[opt] = opts[opt] if "ipaddrs" in opts: result["ipaddrs"] = [] for opt in opts["ipaddrs"]: if salt.utils.validate.net.ipv4_addr(opt): ip, prefix = (i.strip() for i in opt.split("/")) result["ipaddrs"].append({"ipaddr": ip, "prefix": prefix}) else: msg = "ipv4 CIDR is invalid" log.error(msg) raise AttributeError(msg) if "ipv6addrs" in opts: for opt in opts["ipv6addrs"]: if not salt.utils.validate.net.ipv6_addr(opt): msg = "ipv6 CIDR is invalid" log.error(msg) raise AttributeError(msg) result["ipv6addrs"] = opts["ipv6addrs"] if "enable_ipv6" in opts: result["enable_ipv6"] = opts["enable_ipv6"] valid = _CONFIG_TRUE + _CONFIG_FALSE for opt in ( "onparent", "peerdns", "peerroutes", "slave", "vlan", "defroute", "stp", "ipv6_peerdns", "ipv6_defroute", "ipv6_peerroutes", "ipv6_autoconf", "ipv4_failure_fatal", "dhcpv6c", ): if opt in opts: if opts[opt] in _CONFIG_TRUE: result[opt] = "yes" elif opts[opt] in _CONFIG_FALSE: result[opt] = "no" else: _raise_error_iface(iface, opts[opt], valid) if "onboot" in opts: log.warning( "The 'onboot' option is controlled by the 'enabled' option. " "Interface: %s Enabled: %s", iface, enabled, ) if enabled: result["onboot"] = "yes" else: result["onboot"] = "no" # If the interface is defined then we want to always take # control away from non-root users; unless the administrator # wants to allow non-root users to control the device. if "userctl" in opts: if opts["userctl"] in _CONFIG_TRUE: result["userctl"] = "yes" elif opts["userctl"] in _CONFIG_FALSE: result["userctl"] = "no" else: _raise_error_iface(iface, opts["userctl"], valid) else: result["userctl"] = "no" # This vlan is in opts, and should be only used in range interface # will affect jinja template for interface generating if "vlan" in opts: if opts["vlan"] in _CONFIG_TRUE: result["vlan"] = "yes" elif opts["vlan"] in _CONFIG_FALSE: result["vlan"] = "no" else: _raise_error_iface(iface, opts["vlan"], valid) if "arpcheck" in opts: if opts["arpcheck"] in _CONFIG_FALSE: result["arpcheck"] = "no" if "ipaddr_start" in opts: result["ipaddr_start"] = opts["ipaddr_start"] if "ipaddr_end" in opts: result["ipaddr_end"] = opts["ipaddr_end"] if "clonenum_start" in opts: result["clonenum_start"] = opts["clonenum_start"] if "hwaddr" in opts: result["hwaddr"] = opts["hwaddr"] if "macaddr" in opts: result["macaddr"] = opts["macaddr"] # If NetworkManager is available, we can control whether we use # it or not if "nm_controlled" in opts: if opts["nm_controlled"] in _CONFIG_TRUE: result["nm_controlled"] = "yes" elif opts["nm_controlled"] in _CONFIG_FALSE: result["nm_controlled"] = "no" else: _raise_error_iface(iface, opts["nm_controlled"], valid) else: result["nm_controlled"] = "no" return result def _parse_routes(iface, opts): """ Filters given options and outputs valid settings for the route settings file. """ # Normalize keys opts = {k.lower(): v for (k, v) in opts.items()} result = {} if "routes" not in opts: _raise_error_routes(iface, "routes", "List of routes") for opt in opts: result[opt] = opts[opt] return result def _parse_network_settings(opts, current): """ Filters given options and outputs valid settings for the global network settings file. """ # Normalize keys opts = {k.lower(): v for (k, v) in opts.items()} current = {k.lower(): v for (k, v) in current.items()} # Check for supported parameters retain_settings = opts.get("retain_settings", False) result = current if retain_settings else {} # Default quote type is an empty string, which will not quote values quote_type = "" valid = _CONFIG_TRUE + _CONFIG_FALSE if "enabled" not in opts: try: opts["networking"] = current["networking"] # If networking option is quoted, use its quote type quote_type = salt.utils.stringutils.is_quoted(opts["networking"]) _log_default_network("networking", current["networking"]) except ValueError: _raise_error_network("networking", valid) else: opts["networking"] = opts["enabled"] true_val = "{0}yes{0}".format(quote_type) false_val = "{0}no{0}".format(quote_type) networking = salt.utils.stringutils.dequote(opts["networking"]) if networking in valid: if networking in _CONFIG_TRUE: result["networking"] = true_val elif networking in _CONFIG_FALSE: result["networking"] = false_val else: _raise_error_network("networking", valid) if "hostname" not in opts: try: opts["hostname"] = current["hostname"] _log_default_network("hostname", current["hostname"]) except Exception: # pylint: disable=broad-except _raise_error_network("hostname", ["server1.example.com"]) if opts["hostname"]: result["hostname"] = "{1}{0}{1}".format( salt.utils.stringutils.dequote(opts["hostname"]), quote_type ) else: _raise_error_network("hostname", ["server1.example.com"]) if "nozeroconf" in opts: nozeroconf = salt.utils.stringutils.dequote(opts["nozeroconf"]) if nozeroconf in valid: if nozeroconf in _CONFIG_TRUE: result["nozeroconf"] = true_val elif nozeroconf in _CONFIG_FALSE: result["nozeroconf"] = false_val else: _raise_error_network("nozeroconf", valid) for opt in opts: if opt not in ("networking", "hostname", "nozeroconf"): result[opt] = "{1}{0}{1}".format( salt.utils.stringutils.dequote(opts[opt]), quote_type ) return result def _raise_error_iface(iface, option, expected): """ Log and raise an error with a logical formatted message. """ msg = _error_msg_iface(iface, option, expected) log.error(msg) raise AttributeError(msg) def _raise_error_network(option, expected): """ Log and raise an error with a logical formatted message. """ msg = _error_msg_network(option, expected) log.error(msg) raise AttributeError(msg) def _raise_error_routes(iface, option, expected): """ Log and raise an error with a logical formatted message. """ msg = _error_msg_routes(iface, option, expected) log.error(msg) raise AttributeError(msg) def _read_file(path): """ Reads and returns the contents of a file """ try: with salt.utils.files.fopen(path, "rb") as rfh: lines = salt.utils.stringutils.to_unicode(rfh.read()).splitlines() try: lines.remove("") except ValueError: pass return lines except Exception: # pylint: disable=broad-except return [] # Return empty list for type consistency def _write_file_iface(iface, data, folder, pattern): """ Writes a file to disk """ filename = os.path.join(folder, pattern.format(iface)) if not os.path.exists(folder): msg = "{0} cannot be written. {1} does not exist" msg = msg.format(filename, folder) log.error(msg) raise AttributeError(msg) with salt.utils.files.fopen(filename, "w") as fp_: fp_.write(salt.utils.stringutils.to_str(data)) def _write_file_network(data, filename): """ Writes a file to disk """ with salt.utils.files.fopen(filename, "w") as fp_: fp_.write(salt.utils.stringutils.to_str(data)) def _read_temp(data): lines = data.splitlines() try: # Discard newlines if they exist lines.remove("") except ValueError: pass return lines def build_interface(iface, iface_type, enabled, **settings): """ Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> """ if __grains__["os"] == "Fedora": if __grains__["osmajorrelease"] >= 28: rh_major = "8" else: rh_major = "7" elif __grains__["os"] == "Amazon": rh_major = "7" else: rh_major = __grains__["osrelease"][:1] iface_type = iface_type.lower() if iface_type not in _IFACE_TYPES: _raise_error_iface(iface, iface_type, _IFACE_TYPES) if iface_type == "slave": settings["slave"] = "yes" if "master" not in settings: msg = "master is a required setting for slave interfaces" log.error(msg) raise AttributeError(msg) if iface_type == "bond": if "mode" not in settings: msg = "mode is required for bond interfaces" log.error(msg) raise AttributeError(msg) settings["mode"] = str(settings["mode"]) if iface_type == "teamport": # Validate that either a master or team_master is defined if "master" not in settings and "team_master" not in settings: msg = "master or team_master is a required setting for teamport interfaces" log.error(msg) raise AttributeError(msg) elif "master" in settings and "team_master" in settings: log.warning( "Both team_master (%s) and master (%s) were configured " "for teamport interface %s. Ignoring master in favor of " "team_master.", settings["team_master"], settings["master"], iface, ) del settings["master"] elif "master" in settings: settings["team_master"] = settings.pop("master") if iface_type == "vlan": settings["vlan"] = "yes" if iface_type == "bridge" and not __salt__["pkg.version"]("bridge-utils"): __salt__["pkg.install"]("bridge-utils") if iface_type == "team" and not __salt__["pkg.version"]("teamd"): __salt__["pkg.install"]("teamd") if iface_type in ( "eth", "bond", "team", "teamport", "bridge", "slave", "vlan", "ipip", "ib", "alias", ): opts = _parse_settings_eth(settings, iface_type, enabled, iface) try: template = JINJA.get_template("rh{}_eth.jinja".format(rh_major)) except jinja2.exceptions.TemplateNotFound: log.error("Could not load template rh%s_eth.jinja", rh_major) return "" ifcfg = template.render(opts) if settings.get("test"): return _read_temp(ifcfg) _write_file_iface(iface, ifcfg, _RH_NETWORK_SCRIPT_DIR, "ifcfg-{0}") path = os.path.join(_RH_NETWORK_SCRIPT_DIR, "ifcfg-{}".format(iface)) return _read_file(path) def build_routes(iface, **settings): """ Build a route script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_routes eth0 <settings> """ template = "rh6_route_eth.jinja" try: if int(__grains__["osrelease"][0]) < 6: template = "route_eth.jinja" except ValueError: pass log.debug("Template name: %s", template) opts = _parse_routes(iface, settings) log.debug("Opts: \n %s", opts) try: template = JINJA.get_template(template) except jinja2.exceptions.TemplateNotFound: log.error("Could not load template %s", template) return "" opts6 = [] opts4 = [] for route in opts["routes"]: ipaddr = route["ipaddr"] if salt.utils.validate.net.ipv6_addr(ipaddr): opts6.append(route) else: opts4.append(route) log.debug("IPv4 routes:\n%s", opts4) log.debug("IPv6 routes:\n%s", opts6) routecfg = template.render(routes=opts4, iface=iface) routecfg6 = template.render(routes=opts6, iface=iface) if settings["test"]: routes = _read_temp(routecfg) routes.extend(_read_temp(routecfg6)) return routes _write_file_iface(iface, routecfg, _RH_NETWORK_SCRIPT_DIR, "route-{0}") _write_file_iface(iface, routecfg6, _RH_NETWORK_SCRIPT_DIR, "route6-{0}") path = os.path.join(_RH_NETWORK_SCRIPT_DIR, "route-{}".format(iface)) path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, "route6-{}".format(iface)) routes = _read_file(path) routes.extend(_read_file(path6)) return routes def down(iface, iface_type): """ Shutdown a network interface CLI Example: .. code-block:: bash salt '*' ip.down eth0 """ # Slave devices are controlled by the master. if iface_type.lower() not in ("slave", "teamport"): return __salt__["cmd.run"]("ifdown {}".format(iface)) return None def get_interface(iface): """ Return the contents of an interface script CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 """ path = os.path.join(_RH_NETWORK_SCRIPT_DIR, "ifcfg-{}".format(iface)) return _read_file(path) def up(iface, iface_type): # pylint: disable=C0103 """ Start up a network interface CLI Example: .. code-block:: bash salt '*' ip.up eth0 """ # Slave devices are controlled by the master. if iface_type.lower() not in ("slave", "teamport"): return __salt__["cmd.run"]("ifup {}".format(iface)) return None def get_routes(iface): """ Return the contents of the interface routes script. CLI Example: .. code-block:: bash salt '*' ip.get_routes eth0 """ path = os.path.join(_RH_NETWORK_SCRIPT_DIR, "route-{}".format(iface)) path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, "route6-{}".format(iface)) routes = _read_file(path) routes.extend(_read_file(path6)) return routes def get_network_settings(): """ Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings """ return _read_file(_RH_NETWORK_FILE) def apply_network_settings(**settings): """ Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings """ if "require_reboot" not in settings: settings["require_reboot"] = False if "apply_hostname" not in settings: settings["apply_hostname"] = False hostname_res = True if settings["apply_hostname"] in _CONFIG_TRUE: if "hostname" in settings: hostname_res = __salt__["network.mod_hostname"](settings["hostname"]) else: log.warning( "The network state sls is trying to apply hostname " "changes but no hostname is defined." ) hostname_res = False res = True if settings["require_reboot"] in _CONFIG_TRUE: log.warning( "The network state sls is requiring a reboot of the system to " "properly apply network configuration." ) res = True else: if __grains__["osmajorrelease"] >= 8: res = __salt__["service.restart"]("NetworkManager") else: res = __salt__["service.restart"]("network") return hostname_res and res def build_network_settings(**settings): """ Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> """ # Read current configuration and store default values current_network_settings = _parse_rh_config(_RH_NETWORK_FILE) # Build settings opts = _parse_network_settings(settings, current_network_settings) try: template = JINJA.get_template("network.jinja") except jinja2.exceptions.TemplateNotFound: log.error("Could not load template network.jinja") return "" network = template.render(opts) if settings["test"]: return _read_temp(network) # Write settings _write_file_network(network, _RH_NETWORK_FILE) return _read_file(_RH_NETWORK_FILE)
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/rh_ip.py
0.448426
0.238545
rh_ip.py
pypi
import logging import salt.utils.platform from salt.exceptions import CommandExecutionError from salt.utils.args import clean_kwargs try: from netmiko import ConnectHandler from netmiko import BaseConnection HAS_NETMIKO = True except ImportError: HAS_NETMIKO = False # ----------------------------------------------------------------------------- # execution module properties # ----------------------------------------------------------------------------- __proxyenabled__ = ["*"] # Any Proxy Minion should be able to execute these (not only netmiko) __virtualname__ = "netmiko" # The Execution Module will be identified as ``netmiko`` # ----------------------------------------------------------------------------- # globals # ----------------------------------------------------------------------------- log = logging.getLogger(__name__) # ----------------------------------------------------------------------------- # propery functions # ----------------------------------------------------------------------------- def __virtual__(): """ Execution module available only if Netmiko is installed. """ if not HAS_NETMIKO: return ( False, "The netmiko execution module requires netmiko library to be installed.", ) if ( salt.utils.platform.is_proxy() and __opts__["proxy"]["proxytype"] == "deltaproxy" ): return ( False, "Unsupported proxy minion type.", ) return __virtualname__ # ----------------------------------------------------------------------------- # helper functions # ----------------------------------------------------------------------------- def _prepare_connection(**kwargs): """ Prepare the connection with the remote network device, and clean up the key value pairs, removing the args used for the connection init. """ init_args = {} fun_kwargs = {} netmiko_kwargs = __salt__["config.get"]("netmiko", {}) netmiko_kwargs.update(kwargs) # merge the CLI args with the opts/pillar netmiko_init_args, _, _, netmiko_defaults = __utils__["args.get_function_argspec"]( BaseConnection.__init__ ) check_self = netmiko_init_args.pop(0) for karg, warg in netmiko_kwargs.items(): if karg not in netmiko_init_args: if warg is not None: fun_kwargs[karg] = warg continue if warg is not None: init_args[karg] = warg conn = ConnectHandler(**init_args) return conn, fun_kwargs # ----------------------------------------------------------------------------- # callable functions # ----------------------------------------------------------------------------- def get_connection(**kwargs): """ Return the Netmiko connection object. .. warning:: This function returns an unserializable object, hence it is not meant to be used on the CLI. This should mainly be used when invoked from other modules for the low level connection with the network device. kwargs Key-value dictionary with the authentication details. USAGE Example: .. code-block:: python conn = __salt__['netmiko.get_connection'](host='router1.example.com', username='example', password='example') show_if = conn.send_command('show interfaces') conn.disconnect() """ kwargs = clean_kwargs(**kwargs) if "netmiko.conn" in __proxy__: return __proxy__["netmiko.conn"]() conn, kwargs = _prepare_connection(**kwargs) return conn def call(method, *args, **kwargs): """ Invoke an arbitrary Netmiko method. method The name of the Netmiko method to invoke. args A list of arguments to send to the method invoked. kwargs Key-value dictionary to send to the method invoked. """ kwargs = clean_kwargs(**kwargs) if "netmiko.call" in __proxy__: return __proxy__["netmiko.call"](method, *args, **kwargs) conn, kwargs = _prepare_connection(**kwargs) ret = getattr(conn, method)(*args, **kwargs) conn.disconnect() return ret def multi_call(*methods, **kwargs): """ Invoke multiple Netmiko methods at once, and return their output, as list. methods A list of dictionaries with the following keys: - ``name``: the name of the Netmiko method to be executed. - ``args``: list of arguments to be sent to the Netmiko method. - ``kwargs``: dictionary of arguments to be sent to the Netmiko method. kwargs Key-value dictionary with the connection details (when not running under a Proxy Minion). """ kwargs = clean_kwargs(**kwargs) if "netmiko.conn" in __proxy__: conn = __proxy__["netmiko.conn"]() else: conn, kwargs = _prepare_connection(**kwargs) ret = [] for method in methods: # Explicit unpacking method_name = method["name"] method_args = method.get("args", []) method_kwargs = method.get("kwargs", []) ret.append(getattr(conn, method_name)(*method_args, **method_kwargs)) if "netmiko.conn" not in __proxy__: conn.disconnect() return ret def send_command(command_string, **kwargs): """ Execute command_string on the SSH channel using a pattern-based mechanism. Generally used for show commands. By default this method will keep waiting to receive data until the network device prompt is detected. The current network device prompt will be determined automatically. command_string The command to be executed on the remote device. expect_string Regular expression pattern to use for determining end of output. If left blank will default to being based on router prompt. delay_factor: ``1`` Multiplying factor used to adjust delays (default: ``1``). max_loops: ``500`` Controls wait time in conjunction with delay_factor. Will default to be based upon self.timeout. auto_find_prompt: ``True`` Whether it should try to auto-detect the prompt (default: ``True``). strip_prompt: ``True`` Remove the trailing router prompt from the output (default: ``True``). strip_command: ``True`` Remove the echo of the command from the output (default: ``True``). normalize: ``True`` Ensure the proper enter is sent at end of command (default: ``True``). use_textfsm: ``False`` Process command output through TextFSM template (default: ``False``). CLI Example: .. code-block:: bash salt '*' netmiko.send_command 'show version' salt '*' netmiko.send_command 'show_version' host='router1.example.com' username='example' device_type='cisco_ios' """ return call("send_command", command_string, **kwargs) def send_command_timing(command_string, **kwargs): """ Execute command_string on the SSH channel using a delay-based mechanism. Generally used for show commands. command_string The command to be executed on the remote device. delay_factor: ``1`` Multiplying factor used to adjust delays (default: ``1``). max_loops: ``500`` Controls wait time in conjunction with delay_factor. Will default to be based upon self.timeout. strip_prompt: ``True`` Remove the trailing router prompt from the output (default: ``True``). strip_command: ``True`` Remove the echo of the command from the output (default: ``True``). normalize: ``True`` Ensure the proper enter is sent at end of command (default: ``True``). use_textfsm: ``False`` Process command output through TextFSM template (default: ``False``). CLI Example: .. code-block:: bash salt '*' netmiko.send_command_timing 'show version' salt '*' netmiko.send_command_timing 'show version' host='router1.example.com' username='example' device_type='arista_eos' """ return call("send_command_timing", command_string, **kwargs) def enter_config_mode(**kwargs): """ Enter into config mode. config_command Configuration command to send to the device. pattern Pattern to terminate reading of channel. CLI Example: .. code-block:: bash salt '*' netmiko.enter_config_mode salt '*' netmiko.enter_config_mode device_type='juniper_junos' ip='192.168.0.1' username='example' """ return call("config_mode", **kwargs) def exit_config_mode(**kwargs): """ Exit from configuration mode. exit_config Command to exit configuration mode. pattern Pattern to terminate reading of channel. CLI Example: .. code-block:: bash salt '*' netmiko.exit_config_mode salt '*' netmiko.exit_config_mode device_type='juniper' ip='192.168.0.1' username='example' """ return call("exit_config_mode", **kwargs) def send_config( config_file=None, config_commands=None, template_engine="jinja", commit=False, context=None, defaults=None, saltenv="base", **kwargs ): """ Send configuration commands down the SSH channel. Return the configuration lines sent to the device. The function is flexible to send the configuration from a local or remote file, or simply the commands as list. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` config_commands Multiple configuration commands to be sent to the device. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. commit: ``False`` Commit the configuration changes before exiting the config mode. This option is by default disabled, as many platforms don't have this capability natively. context Variables to add to the template context. defaults Default values of the context_dict. exit_config_mode: ``True`` Determines whether or not to exit config mode after complete. delay_factor: ``1`` Factor to adjust delays. max_loops: ``150`` Controls wait time in conjunction with delay_factor (default: ``150``). strip_prompt: ``False`` Determines whether or not to strip the prompt (default: ``False``). strip_command: ``False`` Determines whether or not to strip the command (default: ``False``). config_mode_command The command to enter into config mode. CLI Example: .. code-block:: bash salt '*' netmiko.send_config config_commands="['interface GigabitEthernet3', 'no ip address']" salt '*' netmiko.send_config config_commands="['snmp-server location {{ grains.location }}']" salt '*' netmiko.send_config config_file=salt://config.txt salt '*' netmiko.send_config config_file=https://bit.ly/2sgljCB device_type='cisco_ios' ip='1.2.3.4' username='example' """ if config_file: file_str = __salt__["cp.get_file_str"](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError("Source file {} not found".format(config_file)) elif config_commands: if isinstance(config_commands, ((str,), str)): config_commands = [config_commands] file_str = "\n".join(config_commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__["file.apply_template_on_contents"]( file_str, template_engine, context, defaults, saltenv ) # whatever the source of the commands would be, split them line by line config_commands = [line for line in file_str.splitlines() if line.strip()] kwargs = clean_kwargs(**kwargs) if "netmiko.conn" in __proxy__: conn = __proxy__["netmiko.conn"]() if not conn or not conn.is_alive(): conn, _ = _prepare_connection(**__proxy__["netmiko.args"]()) else: conn, kwargs = _prepare_connection(**kwargs) if commit: kwargs["exit_config_mode"] = False # don't exit config mode after # loading the commands, wait for explicit commit ret = conn.send_config_set(config_commands=config_commands, **kwargs) if commit: ret += conn.commit() return ret def commit(**kwargs): """ Commit the configuration changes. .. warning:: This function is supported only on the platforms that support the ``commit`` operation. CLI Example: .. code-block:: bash salt '*' netmiko.commit """ return call("commit", **kwargs)
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/netmiko_mod.py
0.772273
0.179243
netmiko_mod.py
pypi
import logging import os import re import time import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) def __virtual__(): """ Only work on POSIX-like systems """ return not salt.utils.platform.is_windows() and __grains__.get("kernel") == "Linux" def _verify_run(out, cmd=None): """ Crash to the log if command execution was not successful. """ if out.get("retcode", 0) and out["stderr"]: if cmd: log.debug('Command: "%s"', cmd) log.debug("Return code: %s", out.get("retcode")) log.debug("Error output:\n%s", out.get("stderr", "N/A")) raise CommandExecutionError(out["stderr"]) def _xfs_info_get_kv(serialized): """ Parse one line of the XFS info output. """ # No need to know sub-elements here if serialized.startswith("="): serialized = serialized[1:].strip() serialized = serialized.replace(" = ", "=*** ").replace(" =", "=") # Keywords has no spaces, values do opt = [] for tkn in serialized.split(" "): if not opt or "=" in tkn: opt.append(tkn) else: opt[len(opt) - 1] = opt[len(opt) - 1] + " " + tkn # Preserve ordering return [tuple(items.split("=")) for items in opt] def _parse_xfs_info(data): """ Parse output from "xfs_info" or "xfs_growfs -n". """ ret = {} spr = re.compile(r"\s+") entry = None for line in [spr.sub(" ", l).strip().replace(", ", " ") for l in data.split("\n")]: if not line: continue nfo = _xfs_info_get_kv(line) if not line.startswith("="): entry = nfo.pop(0) ret[entry[0]] = {"section": entry[(entry[1] != "***" and 1 or 0)]} ret[entry[0]].update(dict(nfo)) return ret def info(device): """ Get filesystem geometry information. CLI Example: .. code-block:: bash salt '*' xfs.info /dev/sda1 """ out = __salt__["cmd.run_all"]("xfs_info {}".format(device)) if out.get("stderr"): raise CommandExecutionError(out["stderr"].replace("xfs_info:", "").strip()) return _parse_xfs_info(out["stdout"]) def _xfsdump_output(data): """ Parse CLI output of the xfsdump utility. """ out = {} summary = [] summary_block = False for line in [l.strip() for l in data.split("\n") if l.strip()]: line = re.sub("^xfsdump: ", "", line) if line.startswith("session id:"): out["Session ID"] = line.split(" ")[-1] elif line.startswith("session label:"): out["Session label"] = re.sub("^session label: ", "", line) elif line.startswith("media file size"): out["Media size"] = re.sub(r"^media file size\s+", "", line) elif line.startswith("dump complete:"): out["Dump complete"] = re.sub(r"^dump complete:\s+", "", line) elif line.startswith("Dump Status:"): out["Status"] = re.sub(r"^Dump Status:\s+", "", line) elif line.startswith("Dump Summary:"): summary_block = True continue if line.startswith(" ") and summary_block: summary.append(line.strip()) elif not line.startswith(" ") and summary_block: summary_block = False if summary: out["Summary"] = " ".join(summary) return out def dump(device, destination, level=0, label=None, noerase=None): """ Dump filesystem device to the media (file, tape etc). Required parameters: * **device**: XFS device, content of which to be dumped. * **destination**: Specifies a dump destination. Valid options are: * **label**: Label of the dump. Otherwise automatically generated label is used. * **level**: Specifies a dump level of 0 to 9. * **noerase**: Pre-erase media. Other options are not used in order to let ``xfsdump`` use its default values, as they are most optimal. See the ``xfsdump(8)`` manpage for a more complete description of these options. CLI Example: .. code-block:: bash salt '*' xfs.dump /dev/sda1 /detination/on/the/client salt '*' xfs.dump /dev/sda1 /detination/on/the/client label='Company accountancy' salt '*' xfs.dump /dev/sda1 /detination/on/the/client noerase=True """ if not salt.utils.path.which("xfsdump"): raise CommandExecutionError('Utility "xfsdump" has to be installed or missing.') label = ( label and label or time.strftime( 'XFS dump for "{}" of %Y.%m.%d, %H:%M'.format(device), time.localtime() ).replace("'", '"') ) cmd = ["xfsdump"] cmd.append("-F") # Force if not noerase: cmd.append("-E") # pre-erase cmd.append("-L '{}'".format(label)) # Label cmd.append("-l {}".format(level)) # Dump level cmd.append("-f {}".format(destination)) # Media destination cmd.append(device) # Device cmd = " ".join(cmd) out = __salt__["cmd.run_all"](cmd) _verify_run(out, cmd=cmd) return _xfsdump_output(out["stdout"]) def _xr_to_keyset(line): """ Parse xfsrestore output keyset elements. """ tkns = [elm for elm in line.strip().split(":", 1) if elm] if len(tkns) == 1: return "'{}': ".format(tkns[0]) else: key, val = tkns return "'{}': '{}',".format(key.strip(), val.strip()) def _xfs_inventory_output(out): """ Transform xfsrestore inventory data output to a Python dict source and evaluate it. """ data = [] out = [line for line in out.split("\n") if line.strip()] # No inventory yet if len(out) == 1 and "restore status" in out[0].lower(): return {"restore_status": out[0]} ident = 0 data.append("{") for line in out[:-1]: if len([elm for elm in line.strip().split(":") if elm]) == 1: n_ident = len(re.sub("[^\t]", "", line)) if ident > n_ident: for step in range(ident): data.append("},") ident = n_ident data.append(_xr_to_keyset(line)) data.append("{") else: data.append(_xr_to_keyset(line)) for step in range(ident + 1): data.append("},") data.append("},") # We are evaling into a python dict, a json load # would be safer data = eval("\n".join(data))[0] # pylint: disable=W0123 data["restore_status"] = out[-1] return data def inventory(): """ Display XFS dump inventory without restoration. CLI Example: .. code-block:: bash salt '*' xfs.inventory """ out = __salt__["cmd.run_all"]("xfsrestore -I") _verify_run(out) return _xfs_inventory_output(out["stdout"]) def _xfs_prune_output(out, uuid): """ Parse prune output. """ data = {} cnt = [] cutpoint = False for line in [l.strip() for l in out.split("\n") if l]: if line.startswith("-"): if cutpoint: break else: cutpoint = True continue if cutpoint: cnt.append(line) for kset in [e for e in cnt[1:] if ":" in e]: key, val = (t.strip() for t in kset.split(":", 1)) data[key.lower().replace(" ", "_")] = val return data.get("uuid") == uuid and data or {} def prune_dump(sessionid): """ Prunes the dump session identified by the given session id. CLI Example: .. code-block:: bash salt '*' xfs.prune_dump b74a3586-e52e-4a4a-8775-c3334fa8ea2c """ out = __salt__["cmd.run_all"]("xfsinvutil -s {} -F".format(sessionid)) _verify_run(out) data = _xfs_prune_output(out["stdout"], sessionid) if data: return data raise CommandExecutionError('Session UUID "{}" was not found.'.format(sessionid)) def _blkid_output(out): """ Parse blkid output. """ flt = lambda data: [el for el in data if el.strip()] data = {} for dev_meta in flt(out.split("\n\n")): dev = {} for items in flt(dev_meta.strip().split("\n")): key, val = items.split("=", 1) dev[key.lower()] = val if dev.pop("type", None) == "xfs": dev["label"] = dev.get("label") data[dev.pop("devname")] = dev mounts = _get_mounts() for device in mounts: if data.get(device): data[device].update(mounts[device]) return data def devices(): """ Get known XFS formatted devices on the system. CLI Example: .. code-block:: bash salt '*' xfs.devices """ out = __salt__["cmd.run_all"]("blkid -o export") _verify_run(out) return _blkid_output(out["stdout"]) def _xfs_estimate_output(out): """ Parse xfs_estimate output. """ spc = re.compile(r"\s+") data = {} for line in [l for l in out.split("\n") if l.strip()][1:]: directory, bsize, blocks, megabytes, logsize = spc.sub(" ", line).split(" ") data[directory] = { "block _size": bsize, "blocks": blocks, "megabytes": megabytes, "logsize": logsize, } return data def estimate(path): """ Estimate the space that an XFS filesystem will take. For each directory estimate the space that directory would take if it were copied to an XFS filesystem. Estimation does not cross mount points. CLI Example: .. code-block:: bash salt '*' xfs.estimate /path/to/file salt '*' xfs.estimate /path/to/dir/* """ if not os.path.exists(path): raise CommandExecutionError('Path "{}" was not found.'.format(path)) out = __salt__["cmd.run_all"]("xfs_estimate -v {}".format(path)) _verify_run(out) return _xfs_estimate_output(out["stdout"]) def mkfs( device, label=None, ssize=None, noforce=None, bso=None, gmo=None, ino=None, lso=None, rso=None, nmo=None, dso=None, ): """ Create a file system on the specified device. By default wipes out with force. General options: * **label**: Specify volume label. * **ssize**: Specify the fundamental sector size of the filesystem. * **noforce**: Do not force create filesystem, if disk is already formatted. Filesystem geometry options: * **bso**: Block size options. * **gmo**: Global metadata options. * **dso**: Data section options. These options specify the location, size, and other parameters of the data section of the filesystem. * **ino**: Inode options to specify the inode size of the filesystem, and other inode allocation parameters. * **lso**: Log section options. * **nmo**: Naming options. * **rso**: Realtime section options. See the ``mkfs.xfs(8)`` manpage for a more complete description of corresponding options description. CLI Example: .. code-block:: bash salt '*' xfs.mkfs /dev/sda1 salt '*' xfs.mkfs /dev/sda1 dso='su=32k,sw=6' noforce=True salt '*' xfs.mkfs /dev/sda1 dso='su=32k,sw=6' lso='logdev=/dev/sda2,size=10000b' """ getopts = lambda args: dict( (args and ("=" in args) and args or None) and [kw.split("=") for kw in args.split(",")] or [] ) cmd = ["mkfs.xfs"] if label: cmd.append("-L") cmd.append("'{}'".format(label)) if ssize: cmd.append("-s") cmd.append(ssize) for switch, opts in [ ("-b", bso), ("-m", gmo), ("-n", nmo), ("-i", ino), ("-d", dso), ("-l", lso), ("-r", rso), ]: try: if getopts(opts): cmd.append(switch) cmd.append(opts) except Exception: # pylint: disable=broad-except raise CommandExecutionError( 'Wrong parameters "{}" for option "{}"'.format(opts, switch) ) if not noforce: cmd.append("-f") cmd.append(device) cmd = " ".join(cmd) out = __salt__["cmd.run_all"](cmd) _verify_run(out, cmd=cmd) return _parse_xfs_info(out["stdout"]) def modify(device, label=None, lazy_counting=None, uuid=None): """ Modify parameters of an XFS filesystem. CLI Example: .. code-block:: bash salt '*' xfs.modify /dev/sda1 label='My backup' lazy_counting=False salt '*' xfs.modify /dev/sda1 uuid=False salt '*' xfs.modify /dev/sda1 uuid=True """ if not label and lazy_counting is None and uuid is None: raise CommandExecutionError( 'Nothing specified for modification for "{}" device'.format(device) ) cmd = ["xfs_admin"] if label: cmd.append("-L") cmd.append("'{}'".format(label)) if lazy_counting is False: cmd.append("-c") cmd.append("0") elif lazy_counting: cmd.append("-c") cmd.append("1") if uuid is False: cmd.append("-U") cmd.append("nil") elif uuid: cmd.append("-U") cmd.append("generate") cmd.append(device) cmd = " ".join(cmd) _verify_run(__salt__["cmd.run_all"](cmd), cmd=cmd) out = __salt__["cmd.run_all"]("blkid -o export {}".format(device)) _verify_run(out) return _blkid_output(out["stdout"]) def _get_mounts(): """ List mounted filesystems. """ mounts = {} with salt.utils.files.fopen("/proc/mounts") as fhr: for line in salt.utils.data.decode(fhr.readlines()): device, mntpnt, fstype, options, fs_freq, fs_passno = line.strip().split( " " ) if fstype != "xfs": continue mounts[device] = { "mount_point": mntpnt, "options": options.split(","), } return mounts def defragment(device): """ Defragment mounted XFS filesystem. In order to mount a filesystem, device should be properly mounted and writable. CLI Example: .. code-block:: bash salt '*' xfs.defragment /dev/sda1 """ if device == "/": raise CommandExecutionError("Root is not a device.") if not _get_mounts().get(device): raise CommandExecutionError('Device "{}" is not mounted'.format(device)) out = __salt__["cmd.run_all"]("xfs_fsr {}".format(device)) _verify_run(out) return {"log": out["stdout"]}
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/xfs.py
0.529263
0.154217
xfs.py
pypi
import logging import os import socket import urllib.error import salt.utils.data import salt.utils.files import salt.utils.http import salt.utils.json from salt.exceptions import SaltException from salt.utils.versions import LooseVersion as _LooseVersion log = logging.getLogger(__name__) INTERFACE_DEFAULT_PORTS = [10050, 161, 623, 12345] ZABBIX_TOP_LEVEL_OBJECTS = ( "hostgroup", "template", "host", "maintenance", "action", "drule", "service", "proxy", "screen", "usergroup", "mediatype", "script", "valuemap", ) # Zabbix object and its ID name mapping ZABBIX_ID_MAPPER = { "action": "actionid", "alert": "alertid", "application": "applicationid", "dhost": "dhostid", "dservice": "dserviceid", "dcheck": "dcheckid", "drule": "druleid", "event": "eventid", "graph": "graphid", "graphitem": "gitemid", "graphprototype": "graphid", "history": "itemid", "host": "hostid", "hostgroup": "groupid", "hostinterface": "interfaceid", "hostprototype": "hostid", "iconmap": "iconmapid", "image": "imageid", "item": "itemid", "itemprototype": "itemid", "service": "serviceid", "discoveryrule": "itemid", "maintenance": "maintenanceid", "map": "sysmapid", "usermedia": "mediaid", "mediatype": "mediatypeid", "proxy": "proxyid", "screen": "screenid", "screenitem": "screenitemid", "script": "scriptid", "template": "templateid", "templatescreen": "screenid", "templatescreenitem": "screenitemid", "trend": "itemid", "trigger": "triggerid", "triggerprototype": "triggerid", "user": "userid", "usergroup": "usrgrpid", "usermacro": "globalmacroid", "valuemap": "valuemapid", "httptest": "httptestid", } # Define the module's virtual name __virtualname__ = "zabbix" def __virtual__(): """ Only load the module if all modules are imported correctly. """ return __virtualname__ def _frontend_url(): """ Tries to guess the url of zabbix frontend. .. versionadded:: 2016.3.0 """ hostname = socket.gethostname() frontend_url = "http://" + hostname + "/zabbix/api_jsonrpc.php" try: try: response = salt.utils.http.query(frontend_url) error = response["error"] except urllib.error.HTTPError as http_e: error = str(http_e) if error.find("412: Precondition Failed"): return frontend_url else: raise KeyError except (ValueError, KeyError): return False def _query(method, params, url, auth=None): """ JSON request to Zabbix API. .. versionadded:: 2016.3.0 :param method: actual operation to perform via the API :param params: parameters required for specific method :param url: url of zabbix api :param auth: auth token for zabbix api (only for methods with required authentication) :return: Response from API with desired data in JSON format. In case of error returns more specific description. .. versionchanged:: 2017.7 """ unauthenticated_methods = [ "user.login", "apiinfo.version", ] header_dict = {"Content-type": "application/json"} data = {"jsonrpc": "2.0", "id": 0, "method": method, "params": params} if method not in unauthenticated_methods: data["auth"] = auth data = salt.utils.json.dumps(data) log.info("_QUERY input:\nurl: %s\ndata: %s", str(url), str(data)) try: result = salt.utils.http.query( url, method="POST", data=data, header_dict=header_dict, decode_type="json", decode=True, status=True, headers=True, ) log.info("_QUERY result: %s", str(result)) if "error" in result: raise SaltException( "Zabbix API: Status: {} ({})".format(result["status"], result["error"]) ) ret = result.get("dict", {}) if "error" in ret: raise SaltException( "Zabbix API: {} ({})".format( ret["error"]["message"], ret["error"]["data"] ) ) return ret except ValueError as err: raise SaltException( "URL or HTTP headers are probably not correct! ({})".format(err) ) except OSError as err: raise SaltException("Check hostname in URL! ({})".format(err)) def _login(**kwargs): """ Log in to the API and generate the authentication token. .. versionadded:: 2016.3.0 :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: On success connargs dictionary with auth token and frontend url, False on failure. """ connargs = dict() def _connarg(name, key=None): """ Add key to connargs, only if name exists in our kwargs or, as zabbix.<name> in __opts__ or __pillar__ Evaluate in said order - kwargs, opts, then pillar. To avoid collision with other functions, kwargs-based connection arguments are prefixed with 'connection_' (i.e. '_connection_user', etc.). Inspired by mysql salt module. """ if key is None: key = name if name in kwargs: connargs[key] = kwargs[name] else: prefix = "_connection_" if name.startswith(prefix): try: name = name[len(prefix) :] except IndexError: return val = __salt__["config.get"]("zabbix.{}".format(name), None) or __salt__[ "config.get" ]("zabbix:{}".format(name), None) if val is not None: connargs[key] = val _connarg("_connection_user", "user") _connarg("_connection_password", "password") _connarg("_connection_url", "url") if "url" not in connargs: connargs["url"] = _frontend_url() try: if connargs["user"] and connargs["password"] and connargs["url"]: params = {"user": connargs["user"], "password": connargs["password"]} method = "user.login" ret = _query(method, params, connargs["url"]) auth = ret["result"] connargs["auth"] = auth connargs.pop("user", None) connargs.pop("password", None) return connargs else: raise KeyError except KeyError as err: raise SaltException("URL is probably not correct! ({})".format(err)) def _params_extend(params, _ignore_name=False, **kwargs): """ Extends the params dictionary by values from keyword arguments. .. versionadded:: 2016.3.0 :param params: Dictionary with parameters for zabbix API. :param _ignore_name: Salt State module is passing first line as 'name' parameter. If API uses optional parameter 'name' (for ex. host_create, user_create method), please use 'visible_name' or 'firstname' instead of 'name' to not mess these values. :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: Extended params dictionary with parameters. """ # extend params value by optional zabbix API parameters for key in kwargs: if not key.startswith("_"): params.setdefault(key, kwargs[key]) # ignore name parameter passed from Salt state module, use firstname or visible_name instead if _ignore_name: params.pop("name", None) if "firstname" in params: params["name"] = params.pop("firstname") elif "visible_name" in params: params["name"] = params.pop("visible_name") return params def _map_to_list_of_dicts(source, key): """ Maps list of values to list of dicts of values, eg: [usrgrpid1, usrgrpid2, ...] => [{"usrgrpid": usrgrpid1}, {"usrgrpid": usrgrpid2}, ...] :param source: list of values :param key: name of dict key :return: List of dicts in format: [{key: elem}, ...] """ output = [] for elem in source: output.append({key: elem}) return output def get_zabbix_id_mapper(): """ .. versionadded:: 2017.7 Make ZABBIX_ID_MAPPER constant available to state modules. :return: ZABBIX_ID_MAPPER CLI Example: .. code-block:: bash salt '*' zabbix.get_zabbix_id_mapper """ return ZABBIX_ID_MAPPER def substitute_params(input_object, extend_params=None, filter_key="name", **kwargs): """ .. versionadded:: 2017.7 Go through Zabbix object params specification and if needed get given object ID from Zabbix API and put it back as a value. Definition of the object is done via dict with keys "query_object" and "query_name". :param input_object: Zabbix object type specified in state file :param extend_params: Specify query with params :param filter_key: Custom filtering key (default: name) :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: Params structure with values converted to string for further comparison purposes CLI Example: .. code-block:: bash salt '*' zabbix.substitute_params '{"query_object": "object_name", "query_name": "specific_object_name"}' """ if extend_params is None: extend_params = {} if isinstance(input_object, list): return [ substitute_params(oitem, extend_params, filter_key, **kwargs) for oitem in input_object ] elif isinstance(input_object, dict): if "query_object" in input_object: query_params = {} if input_object["query_object"] not in ZABBIX_TOP_LEVEL_OBJECTS: query_params.update(extend_params) try: query_params.update( {"filter": {filter_key: input_object["query_name"]}} ) return get_object_id_by_params( input_object["query_object"], query_params, **kwargs ) except KeyError: raise SaltException( "Qyerying object ID requested " "but object name not provided: {}".format(input_object) ) else: return { key: substitute_params(val, extend_params, filter_key, **kwargs) for key, val in input_object.items() } else: # Zabbix response is always str, return everything in str as well return str(input_object) # pylint: disable=too-many-return-statements,too-many-nested-blocks def compare_params(defined, existing, return_old_value=False): """ .. versionadded:: 2017.7 Compares Zabbix object definition against existing Zabbix object. :param defined: Zabbix object definition taken from sls file. :param existing: Existing Zabbix object taken from result of an API call. :param return_old_value: Default False. If True, returns dict("old"=old_val, "new"=new_val) for rollback purpose. :return: Params that are different from existing object. Result extended by object ID can be passed directly to Zabbix API update method. CLI Example: .. code-block:: bash salt '*' zabbix.compare_params new_zabbix_object_dict existing_zabbix_onject_dict """ # Comparison of data types if not isinstance(defined, type(existing)): raise SaltException( "Zabbix object comparison failed (data type mismatch). Expecting {}, got" ' {}. Existing value: "{}", defined value: "{}").'.format( type(existing), type(defined), existing, defined ) ) # Comparison of values if not salt.utils.data.is_iter(defined): if str(defined) != str(existing) and return_old_value: return {"new": str(defined), "old": str(existing)} elif str(defined) != str(existing) and not return_old_value: return str(defined) # Comparison of lists of values or lists of dicts if isinstance(defined, list): if len(defined) != len(existing): log.info("Different list length!") return {"new": defined, "old": existing} if return_old_value else defined else: difflist = [] for ditem in defined: d_in_e = [] for eitem in existing: comp = compare_params(ditem, eitem, return_old_value) if return_old_value: d_in_e.append(comp["new"]) else: d_in_e.append(comp) if all(d_in_e): difflist.append(ditem) # If there is any difference in a list then whole defined list must be returned and provided for update if any(difflist) and return_old_value: return {"new": defined, "old": existing} elif any(difflist) and not return_old_value: return defined # Comparison of dicts if isinstance(defined, dict): try: # defined must be a subset of existing to be compared if set(defined) <= set(existing): intersection = set(defined) & set(existing) diffdict = {"new": {}, "old": {}} if return_old_value else {} for i in intersection: comp = compare_params(defined[i], existing[i], return_old_value) if return_old_value: if comp or (not comp and isinstance(comp, list)): diffdict["new"].update({i: defined[i]}) diffdict["old"].update({i: existing[i]}) else: if comp or (not comp and isinstance(comp, list)): diffdict.update({i: defined[i]}) return diffdict return {"new": defined, "old": existing} if return_old_value else defined except TypeError: raise SaltException( "Zabbix object comparison failed (data type mismatch). Expecting {}," ' got {}. Existing value: "{}", defined value: "{}").'.format( type(existing), type(defined), existing, defined ) ) def get_object_id_by_params(obj, params=None, **connection_args): """ .. versionadded:: 2017.7 Get ID of single Zabbix object specified by its name. :param obj: Zabbix object type :param params: Parameters by which object is uniquely identified :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: object ID CLI Example: .. code-block:: bash salt '*' zabbix.get_object_id_by_params object_type params=zabbix_api_query_parameters_dict """ if params is None: params = {} res = run_query(obj + ".get", params, **connection_args) if res and len(res) == 1: return str(res[0][ZABBIX_ID_MAPPER[obj]]) else: raise SaltException( "Zabbix API: Object does not exist or bad Zabbix user permissions or other" " unexpected result. Called method {} with params {}. Result: {}".format( obj + ".get", params, res ) ) def apiinfo_version(**connection_args): """ Retrieve the version of the Zabbix API. .. versionadded:: 2016.3.0 :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: On success string with Zabbix API version, False on failure. CLI Example: .. code-block:: bash salt '*' zabbix.apiinfo_version """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "apiinfo.version" params = {} ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"] else: raise KeyError except KeyError: return False def user_create(alias, passwd, usrgrps, **connection_args): """ .. versionadded:: 2016.3.0 Create new zabbix user .. note:: This function accepts all standard user properties: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user :param alias: user alias :param passwd: user's password :param usrgrps: user groups to add the user to :param _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring) :param firstname: string with firstname of the user, use 'firstname' instead of 'name' parameter to not mess with value supplied from Salt sls file. :return: On success string with id of the created user. CLI Example: .. code-block:: bash salt '*' zabbix.user_create james password007 '[7, 12]' firstname='James Bond' """ conn_args = _login(**connection_args) zabbix_version = apiinfo_version(**connection_args) ret = False username_field = "alias" # Zabbix 5.4 changed object fields if _LooseVersion(zabbix_version) > _LooseVersion("5.2"): username_field = "username" try: if conn_args: method = "user.create" params = {username_field: alias, "passwd": passwd, "usrgrps": []} # User groups if not isinstance(usrgrps, list): usrgrps = [usrgrps] params["usrgrps"] = _map_to_list_of_dicts(usrgrps, "usrgrpid") params = _params_extend(params, _ignore_name=True, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["userids"] else: raise KeyError except KeyError: return ret def user_delete(users, **connection_args): """ Delete zabbix users. .. versionadded:: 2016.3.0 :param users: array of users (userids) to delete :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: On success array with userids of deleted users. CLI Example: .. code-block:: bash salt '*' zabbix.user_delete 15 """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "user.delete" if not isinstance(users, list): params = [users] else: params = users ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["userids"] else: raise KeyError except KeyError: return ret def user_exists(alias, **connection_args): """ Checks if user with given alias exists. .. versionadded:: 2016.3.0 :param alias: user alias :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: True if user exists, else False. CLI Example: .. code-block:: bash salt '*' zabbix.user_exists james """ conn_args = _login(**connection_args) zabbix_version = apiinfo_version(**connection_args) ret = False username_field = "alias" # Zabbix 5.4 changed object fields if _LooseVersion(zabbix_version) > _LooseVersion("5.2"): username_field = "username" try: if conn_args: method = "user.get" # Zabbix 5.4 changed object fields params = {"output": "extend", "filter": {username_field: alias}} ret = _query(method, params, conn_args["url"], conn_args["auth"]) return True if len(ret["result"]) > 0 else False else: raise KeyError except KeyError: return ret def user_get(alias=None, userids=None, **connection_args): """ Retrieve users according to the given parameters. .. versionadded:: 2016.3.0 :param alias: user alias :param userids: return only users with the given IDs :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: Array with details of convenient users, False on failure of if no user found. CLI Example: .. code-block:: bash salt '*' zabbix.user_get james """ conn_args = _login(**connection_args) zabbix_version = apiinfo_version(**connection_args) ret = False username_field = "alias" # Zabbix 5.4 changed object fields if _LooseVersion(zabbix_version) > _LooseVersion("5.2"): username_field = "username" try: if conn_args: method = "user.get" params = { "output": "extend", "selectUsrgrps": "extend", "selectMedias": "extend", "selectMediatypes": "extend", "filter": {}, } if not userids and not alias: return { "result": False, "comment": ( "Please submit alias or userids parameter to retrieve users." ), } if alias: params["filter"].setdefault(username_field, alias) if userids: params.setdefault("userids", userids) params = _params_extend(params, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"] if len(ret["result"]) > 0 else False else: raise KeyError except KeyError: return ret def user_update(userid, **connection_args): """ .. versionadded:: 2016.3.0 Update existing users .. note:: This function accepts all standard user properties: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/user/definitions#user :param userid: id of the user to update :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: Id of the updated user on success. CLI Example: .. code-block:: bash salt '*' zabbix.user_update 16 visible_name='James Brown' """ conn_args = _login(**connection_args) zabbix_version = apiinfo_version(**connection_args) ret = False medias = connection_args.pop("medias", None) if medias is None: medias = connection_args.pop("user_medias", None) else: medias.extend(connection_args.pop("user_medias", [])) try: if conn_args: method = "user.update" params = { "userid": userid, } if ( _LooseVersion(zabbix_version) < _LooseVersion("3.4") and medias is not None ): ret = { "result": False, "comment": "Setting medias available in Zabbix 3.4+", } return ret elif ( _LooseVersion(zabbix_version) > _LooseVersion("5.0") and medias is not None ): params["medias"] = medias elif medias is not None: params["user_medias"] = medias if "usrgrps" in connection_args: params["usrgrps"] = _map_to_list_of_dicts( connection_args.pop("usrgrps"), "usrgrpid" ) params = _params_extend(params, _ignore_name=True, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["userids"] else: raise KeyError except KeyError: return ret def user_getmedia(userids=None, **connection_args): """ .. versionadded:: 2016.3.0 Retrieve media according to the given parameters .. note:: This function accepts all standard usermedia.get properties: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/3.2/manual/api/reference/usermedia/get :param userids: return only media that are used by the given users :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: List of retrieved media, False on failure. CLI Example: .. code-block:: bash salt '*' zabbix.user_getmedia """ conn_args = _login(**connection_args) zabbix_version = apiinfo_version(**connection_args) ret = False if _LooseVersion(zabbix_version) > _LooseVersion("3.4"): users = user_get(userids=userids, **connection_args) medias = [] for user in users: medias.extend(user.get("medias", [])) return medias try: if conn_args: method = "usermedia.get" params = {} if userids: params["userids"] = userids params = _params_extend(params, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"] else: raise KeyError except KeyError: return ret def user_addmedia( userids, active, mediatypeid, period, sendto, severity, **connection_args ): """ Add new media to multiple users. Available only for Zabbix version 3.4 or older. .. versionadded:: 2016.3.0 :param userids: ID of the user that uses the media :param active: Whether the media is enabled (0 enabled, 1 disabled) :param mediatypeid: ID of the media type used by the media :param period: Time when the notifications can be sent as a time period :param sendto: Address, user name or other identifier of the recipient :param severity: Trigger severities to send notifications about :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: IDs of the created media. CLI Example: .. code-block:: bash salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com' severity=63 """ conn_args = _login(**connection_args) zabbix_version = apiinfo_version(**connection_args) ret = False method = "user.addmedia" if _LooseVersion(zabbix_version) > _LooseVersion("3.4"): ret = { "result": False, "comment": "Method '{}' removed in Zabbix 4.0+ use 'user.update'".format( method ), } return ret try: if conn_args: method = "user.addmedia" params = {"users": []} # Users if not isinstance(userids, list): userids = [userids] for user in userids: params["users"].append({"userid": user}) # Medias params["medias"] = [ { "active": active, "mediatypeid": mediatypeid, "period": period, "sendto": sendto, "severity": severity, }, ] ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["mediaids"] else: raise KeyError except KeyError: return ret def user_deletemedia(mediaids, **connection_args): """ Delete media by id. Available only for Zabbix version 3.4 or older. .. versionadded:: 2016.3.0 :param mediaids: IDs of the media to delete :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: IDs of the deleted media, False on failure. CLI Example: .. code-block:: bash salt '*' zabbix.user_deletemedia 27 """ conn_args = _login(**connection_args) zabbix_version = apiinfo_version(**connection_args) ret = False method = "user.deletemedia" if _LooseVersion(zabbix_version) > _LooseVersion("3.4"): ret = { "result": False, "comment": "Method '{}' removed in Zabbix 4.0+ use 'user.update'".format( method ), } return ret try: if conn_args: if not isinstance(mediaids, list): mediaids = [mediaids] params = mediaids ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["mediaids"] else: raise KeyError except KeyError: return ret def user_list(**connection_args): """ Retrieve all of the configured users. .. versionadded:: 2016.3.0 :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: Array with user details. CLI Example: .. code-block:: bash salt '*' zabbix.user_list """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "user.get" params = {"output": "extend"} ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"] else: raise KeyError except KeyError: return ret def usergroup_create(name, **connection_args): """ .. versionadded:: 2016.3.0 Create new user group .. note:: This function accepts all standard user group properties: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group :param name: name of the user group :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: IDs of the created user groups. CLI Example: .. code-block:: bash salt '*' zabbix.usergroup_create GroupName """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "usergroup.create" params = {"name": name} params = _params_extend(params, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["usrgrpids"] else: raise KeyError except KeyError: return ret def usergroup_delete(usergroupids, **connection_args): """ .. versionadded:: 2016.3.0 :param usergroupids: IDs of the user groups to delete :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: IDs of the deleted user groups. CLI Example: .. code-block:: bash salt '*' zabbix.usergroup_delete 28 """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "usergroup.delete" if not isinstance(usergroupids, list): usergroupids = [usergroupids] params = usergroupids ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["usrgrpids"] else: raise KeyError except KeyError: return ret def usergroup_exists(name=None, node=None, nodeids=None, **connection_args): """ Checks if at least one user group that matches the given filter criteria exists .. versionadded:: 2016.3.0 :param name: names of the user groups :param node: name of the node the user groups must belong to (This will override the nodeids parameter.) :param nodeids: IDs of the nodes the user groups must belong to :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: True if at least one user group that matches the given filter criteria exists, else False. CLI Example: .. code-block:: bash salt '*' zabbix.usergroup_exists Guests """ conn_args = _login(**connection_args) zabbix_version = apiinfo_version(**connection_args) ret = False try: if conn_args: # usergroup.exists deprecated if _LooseVersion(zabbix_version) > _LooseVersion("2.5"): if not name: name = "" ret = usergroup_get(name, None, **connection_args) return bool(ret) # zabbix 2.4 and earlier else: method = "usergroup.exists" params = {} if not name and not node and not nodeids: return { "result": False, "comment": ( "Please submit name, node or nodeids parameter to check if " "at least one user group exists." ), } if name: params["name"] = name # deprecated in 2.4 if _LooseVersion(zabbix_version) < _LooseVersion("2.4"): if node: params["node"] = node if nodeids: params["nodeids"] = nodeids ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"] else: raise KeyError except KeyError: return ret def usergroup_get(name=None, usrgrpids=None, userids=None, **connection_args): """ .. versionadded:: 2016.3.0 Retrieve user groups according to the given parameters .. note:: This function accepts all usergroup_get properties: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/get :param name: names of the user groups :param usrgrpids: return only user groups with the given IDs :param userids: return only user groups that contain the given users :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: Array with convenient user groups details, False if no user group found or on failure. CLI Example: .. code-block:: bash salt '*' zabbix.usergroup_get Guests """ conn_args = _login(**connection_args) zabbix_version = apiinfo_version(**connection_args) ret = False try: if conn_args: method = "usergroup.get" # Versions above 2.4 allow retrieving user group permissions if _LooseVersion(zabbix_version) > _LooseVersion("2.5"): params = {"selectRights": "extend", "output": "extend", "filter": {}} else: params = {"output": "extend", "filter": {}} if not name and not usrgrpids and not userids: return False if name: params["filter"].setdefault("name", name) if usrgrpids: params.setdefault("usrgrpids", usrgrpids) if userids: params.setdefault("userids", userids) params = _params_extend(params, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return False if len(ret["result"]) < 1 else ret["result"] else: raise KeyError except KeyError: return ret def usergroup_update(usrgrpid, **connection_args): """ .. versionadded:: 2016.3.0 Update existing user group .. note:: This function accepts all standard user group properties: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#user_group :param usrgrpid: ID of the user group to update. :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: IDs of the updated user group, False on failure. CLI Example: .. code-block:: bash salt '*' zabbix.usergroup_update 8 name=guestsRenamed """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "usergroup.update" params = {"usrgrpid": usrgrpid} params = _params_extend(params, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["usrgrpids"] else: raise KeyError except KeyError: return ret def usergroup_list(**connection_args): """ Retrieve all enabled user groups. .. versionadded:: 2016.3.0 :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: Array with enabled user groups details, False on failure. CLI Example: .. code-block:: bash salt '*' zabbix.usergroup_list """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "usergroup.get" params = { "output": "extend", } ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"] else: raise KeyError except KeyError: return ret def host_create(host, groups, interfaces, **connection_args): """ .. versionadded:: 2016.3.0 Create new host .. note:: This function accepts all standard host properties: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host :param host: technical name of the host :param groups: groupids of host groups to add the host to :param interfaces: interfaces to be created for the host :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :param visible_name: string with visible name of the host, use 'visible_name' instead of 'name' parameter to not mess with value supplied from Salt sls file. return: ID of the created host. CLI Example: .. code-block:: bash salt '*' zabbix.host_create technicalname 4 interfaces='{type: 1, main: 1, useip: 1, ip: "192.168.3.1", dns: "", port: 10050}' visible_name='Host Visible Name' inventory_mode=0 inventory='{"alias": "something"}' """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "host.create" params = {"host": host} # Groups if not isinstance(groups, list): groups = [groups] params["groups"] = _map_to_list_of_dicts(groups, "groupid") # Interfaces if not isinstance(interfaces, list): interfaces = [interfaces] params["interfaces"] = interfaces params = _params_extend(params, _ignore_name=True, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["hostids"] else: raise KeyError except KeyError: return ret def host_delete(hostids, **connection_args): """ Delete hosts. .. versionadded:: 2016.3.0 :param hostids: Hosts (hostids) to delete. :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: IDs of the deleted hosts. CLI Example: .. code-block:: bash salt '*' zabbix.host_delete 10106 """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "host.delete" if not isinstance(hostids, list): params = [hostids] else: params = hostids ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["hostids"] else: raise KeyError except KeyError: return ret def host_exists( host=None, hostid=None, name=None, node=None, nodeids=None, **connection_args ): """ Checks if at least one host that matches the given filter criteria exists. .. versionadded:: 2016.3.0 :param host: technical name of the host :param hostids: Hosts (hostids) to delete. :param name: visible name of the host :param node: name of the node the hosts must belong to (zabbix API < 2.4) :param nodeids: IDs of the node the hosts must belong to (zabbix API < 2.4) :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: IDs of the deleted hosts, False on failure. CLI Example: .. code-block:: bash salt '*' zabbix.host_exists 'Zabbix server' """ conn_args = _login(**connection_args) zabbix_version = apiinfo_version(**connection_args) ret = False try: if conn_args: # hostgroup.exists deprecated if _LooseVersion(zabbix_version) > _LooseVersion("2.5"): if not host: host = None if not name: name = None if not hostid: hostid = None ret = host_get(host, name, hostid, **connection_args) return bool(ret) # zabbix 2.4 nad earlier else: method = "host.exists" params = {} if hostid: params["hostid"] = hostid if host: params["host"] = host if name: params["name"] = name # deprecated in 2.4 if _LooseVersion(zabbix_version) < _LooseVersion("2.4"): if node: params["node"] = node if nodeids: params["nodeids"] = nodeids if not hostid and not host and not name and not node and not nodeids: return { "result": False, "comment": ( "Please submit hostid, host, name, node or nodeids" " parameter tocheck if at least one host that matches the" " given filter criteria exists." ), } ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"] else: raise KeyError except KeyError: return ret def host_get(host=None, name=None, hostids=None, **connection_args): """ .. versionadded:: 2016.3.0 Retrieve hosts according to the given parameters .. note:: This function accepts all optional host.get parameters: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get :param host: technical name of the host :param name: visible name of the host :param hostids: ids of the hosts :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: Array with convenient hosts details, False if no host found or on failure. CLI Example: .. code-block:: bash salt '*' zabbix.host_get 'Zabbix server' """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "host.get" params = {"output": "extend", "filter": {}} if not name and not hostids and not host: return False if name: params["filter"].setdefault("name", name) if hostids: params.setdefault("hostids", hostids) if host: params["filter"].setdefault("host", host) params = _params_extend(params, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"] if len(ret["result"]) > 0 else False else: raise KeyError except KeyError: return ret def host_update(hostid, **connection_args): """ .. versionadded:: 2016.3.0 Update existing hosts .. note:: This function accepts all standard host and host.update properties: keyword argument names differ depending on your zabbix version, see the documentation for `host objects`_ and the documentation for `updating hosts`_. .. _`host objects`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host .. _`updating hosts`: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/update :param hostid: ID of the host to update :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :param visible_name: string with visible name of the host, use 'visible_name' instead of 'name' parameter to not mess with value supplied from Salt sls file. :return: ID of the updated host. CLI Example: .. code-block:: bash salt '*' zabbix.host_update 10084 name='Zabbix server2' """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "host.update" params = {"hostid": hostid} if "groups" in connection_args: params["groups"] = _map_to_list_of_dicts( connection_args.pop("groups"), "groupid" ) params = _params_extend(params, _ignore_name=True, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["hostids"] else: raise KeyError except KeyError: return ret def host_inventory_get(hostids, **connection_args): """ Retrieve host inventory according to the given parameters. See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory .. versionadded:: 2019.2.0 :param hostids: ID of the host to query :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: Array with host inventory fields, populated or not, False if host inventory is disabled or on failure. CLI Example: .. code-block:: bash salt '*' zabbix.host_inventory_get 101054 """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "host.get" params = {"selectInventory": "extend"} if hostids: params.setdefault("hostids", hostids) params = _params_extend(params, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ( ret["result"][0]["inventory"] if ret["result"] and ret["result"][0]["inventory"] else False ) else: raise KeyError except KeyError: return ret def host_inventory_set(hostid, **connection_args): """ Update host inventory items NOTE: This function accepts all standard host: keyword argument names for inventory see: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory .. versionadded:: 2019.2.0 :param hostid: ID of the host to update :param clear_old: Set to True in order to remove all existing inventory items before setting the specified items :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: ID of the updated host, False on failure. CLI Example: .. code-block:: bash salt '*' zabbix.host_inventory_set 101054 asset_tag=jml3322 type=vm clear_old=True """ conn_args = _login(**connection_args) ret = False try: if conn_args: params = {} clear_old = False method = "host.update" if connection_args.get("clear_old"): clear_old = True connection_args.pop("clear_old", None) inventory_mode = connection_args.pop("inventory_mode", "0") inventory_params = dict(_params_extend(params, **connection_args)) for key in inventory_params: params.pop(key, None) if hostid: params.setdefault("hostid", hostid) if clear_old: # Set inventory to disabled in order to clear existing data params["inventory_mode"] = "-1" ret = _query(method, params, conn_args["url"], conn_args["auth"]) # Set inventory mode to manual in order to submit inventory data params["inventory_mode"] = inventory_mode params["inventory"] = inventory_params ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"] else: raise KeyError except KeyError: return ret def host_list(**connection_args): """ Retrieve all hosts. .. versionadded:: 2016.3.0 :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: Array with details about hosts, False on failure. CLI Example: .. code-block:: bash salt '*' zabbix.host_list """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "host.get" params = { "output": "extend", } ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"] else: raise KeyError except KeyError: return ret def hostgroup_create(name, **connection_args): """ .. versionadded:: 2016.3.0 Create a host group .. note:: This function accepts all standard host group properties: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group :param name: name of the host group :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: ID of the created host group. CLI Example: .. code-block:: bash salt '*' zabbix.hostgroup_create MyNewGroup """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "hostgroup.create" params = {"name": name} params = _params_extend(params, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["groupids"] else: raise KeyError except KeyError: return ret def hostgroup_delete(hostgroupids, **connection_args): """ Delete the host group. .. versionadded:: 2016.3.0 :param hostgroupids: IDs of the host groups to delete :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: ID of the deleted host groups, False on failure. CLI Example: .. code-block:: bash salt '*' zabbix.hostgroup_delete 23 """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "hostgroup.delete" if not isinstance(hostgroupids, list): params = [hostgroupids] else: params = hostgroupids ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["groupids"] else: raise KeyError except KeyError: return ret def hostgroup_exists( name=None, groupid=None, node=None, nodeids=None, **connection_args ): """ Checks if at least one host group that matches the given filter criteria exists. .. versionadded:: 2016.3.0 :param name: names of the host groups :param groupid: host group IDs :param node: name of the node the host groups must belong to (zabbix API < 2.4) :param nodeids: IDs of the nodes the host groups must belong to (zabbix API < 2.4) :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: True if at least one host group exists, False if not or on failure. CLI Example: .. code-block:: bash salt '*' zabbix.hostgroup_exists MyNewGroup """ conn_args = _login(**connection_args) zabbix_version = apiinfo_version(**connection_args) ret = False try: if conn_args: # hostgroup.exists deprecated if _LooseVersion(zabbix_version) > _LooseVersion("2.5"): if not groupid: groupid = None if not name: name = None ret = hostgroup_get(name, groupid, **connection_args) return bool(ret) # zabbix 2.4 nad earlier else: params = {} method = "hostgroup.exists" if groupid: params["groupid"] = groupid if name: params["name"] = name # deprecated in 2.4 if _LooseVersion(zabbix_version) < _LooseVersion("2.4"): if node: params["node"] = node if nodeids: params["nodeids"] = nodeids if not groupid and not name and not node and not nodeids: return { "result": False, "comment": ( "Please submit groupid, name, node or nodeids parameter" " tocheck if at least one host group that matches the given" " filter criteria exists." ), } ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"] else: raise KeyError except KeyError: return ret def hostgroup_get(name=None, groupids=None, hostids=None, **connection_args): """ .. versionadded:: 2016.3.0 Retrieve host groups according to the given parameters .. note:: This function accepts all standard hostgroup.get properities: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get :param name: names of the host groups :param groupid: host group IDs :param node: name of the node the host groups must belong to :param nodeids: IDs of the nodes the host groups must belong to :param hostids: return only host groups that contain the given hosts :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: Array with host groups details, False if no convenient host group found or on failure. CLI Example: .. code-block:: bash salt '*' zabbix.hostgroup_get MyNewGroup """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "hostgroup.get" params = {"output": "extend"} if not groupids and not name and not hostids: return False if name: name_dict = {"name": name} params.setdefault("filter", name_dict) if groupids: params.setdefault("groupids", groupids) if hostids: params.setdefault("hostids", hostids) params = _params_extend(params, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"] if len(ret["result"]) > 0 else False else: raise KeyError except KeyError: return ret def hostgroup_update(groupid, name=None, **connection_args): """ .. versionadded:: 2016.3.0 Update existing hosts group .. note:: This function accepts all standard host group properties: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostgroup/object#host_group :param groupid: ID of the host group to update :param name: name of the host group :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: IDs of updated host groups. CLI Example: .. code-block:: bash salt '*' zabbix.hostgroup_update 24 name='Renamed Name' """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "hostgroup.update" params = {"groupid": groupid} if name: params["name"] = name params = _params_extend(params, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["groupids"] else: raise KeyError except KeyError: return ret def hostgroup_list(**connection_args): """ Retrieve all host groups. .. versionadded:: 2016.3.0 :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: Array with details about host groups, False on failure. CLI Example: .. code-block:: bash salt '*' zabbix.hostgroup_list """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "hostgroup.get" params = { "output": "extend", } ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"] else: raise KeyError except KeyError: return ret def hostinterface_get(hostids, **connection_args): """ .. versionadded:: 2016.3.0 Retrieve host groups according to the given parameters .. note:: This function accepts all standard hostinterface.get properities: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/get :param hostids: Return only host interfaces used by the given hosts. :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: Array with host interfaces details, False if no convenient host interfaces found or on failure. CLI Example: .. code-block:: bash salt '*' zabbix.hostinterface_get 101054 """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "hostinterface.get" params = {"output": "extend"} if hostids: params.setdefault("hostids", hostids) params = _params_extend(params, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"] if len(ret["result"]) > 0 else False else: raise KeyError except KeyError: return ret def hostinterface_create( hostid, ip_, dns="", main=1, if_type=1, useip=1, port=None, **connection_args ): """ .. versionadded:: 2016.3.0 Create new host interface .. note:: This function accepts all standard host group interface: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/hostinterface/object :param hostid: ID of the host the interface belongs to :param ip_: IP address used by the interface :param dns: DNS name used by the interface :param main: whether the interface is used as default on the host (0 - not default, 1 - default) :param port: port number used by the interface :param type: Interface type (1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX) :param useip: Whether the connection should be made via IP (0 - connect using host DNS name; 1 - connect using host IP address for this host interface) :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: ID of the created host interface, False on failure. CLI Example: .. code-block:: bash salt '*' zabbix.hostinterface_create 10105 192.193.194.197 """ conn_args = _login(**connection_args) ret = False if not port: port = INTERFACE_DEFAULT_PORTS[if_type] try: if conn_args: method = "hostinterface.create" params = { "hostid": hostid, "ip": ip_, "dns": dns, "main": main, "port": port, "type": if_type, "useip": useip, } params = _params_extend(params, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["interfaceids"] else: raise KeyError except KeyError: return ret def hostinterface_delete(interfaceids, **connection_args): """ Delete host interface .. versionadded:: 2016.3.0 :param interfaceids: IDs of the host interfaces to delete :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: ID of deleted host interfaces, False on failure. CLI Example: .. code-block:: bash salt '*' zabbix.hostinterface_delete 50 """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "hostinterface.delete" if isinstance(interfaceids, list): params = interfaceids else: params = [interfaceids] ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["interfaceids"] else: raise KeyError except KeyError: return ret def hostinterface_update(interfaceid, **connection_args): """ .. versionadded:: 2016.3.0 Update host interface .. note:: This function accepts all standard hostinterface: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_interface :param interfaceid: ID of the hostinterface to update :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: ID of the updated host interface, False on failure. CLI Example: .. code-block:: bash salt '*' zabbix.hostinterface_update 6 ip_=0.0.0.2 """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "hostinterface.update" params = {"interfaceid": interfaceid} params = _params_extend(params, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["interfaceids"] else: raise KeyError except KeyError: return ret def usermacro_get( macro=None, hostids=None, templateids=None, hostmacroids=None, globalmacroids=None, globalmacro=False, **connection_args ): """ Retrieve user macros according to the given parameters. Args: macro: name of the usermacro hostids: Return macros for the given hostids templateids: Return macros for the given templateids hostmacroids: Return macros with the given hostmacroids globalmacroids: Return macros with the given globalmacroids (implies globalmacro=True) globalmacro: if True, returns only global macros optional connection_args: _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring) _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring) _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring) Returns: Array with usermacro details, False if no usermacro found or on failure. CLI Example: .. code-block:: bash salt '*' zabbix.usermacro_get macro='{$SNMP_COMMUNITY}' """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "usermacro.get" params = {"output": "extend", "filter": {}} if macro: # Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict if isinstance(macro, dict): macro = "{" + str(next(iter(macro))) + "}" if not macro.startswith("{") and not macro.endswith("}"): macro = "{" + macro + "}" params["filter"].setdefault("macro", macro) if hostids: params.setdefault("hostids", hostids) elif templateids: params.setdefault("templateids", hostids) if hostmacroids: params.setdefault("hostmacroids", hostmacroids) elif globalmacroids: globalmacro = True params.setdefault("globalmacroids", globalmacroids) if globalmacro: params = _params_extend(params, globalmacro=True) params = _params_extend(params, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"] if len(ret["result"]) > 0 else False else: raise KeyError except KeyError: return ret def usermacro_create(macro, value, hostid, **connection_args): """ Create new host usermacro. :param macro: name of the host usermacro :param value: value of the host usermacro :param hostid: hostid or templateid :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) return: ID of the created host usermacro. CLI Example: .. code-block:: bash salt '*' zabbix.usermacro_create '{$SNMP_COMMUNITY}' 'public' 1 """ conn_args = _login(**connection_args) ret = False try: if conn_args: params = {} method = "usermacro.create" if macro: # Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict if isinstance(macro, dict): macro = "{" + str(next(iter(macro))) + "}" if not macro.startswith("{") and not macro.endswith("}"): macro = "{" + macro + "}" params["macro"] = macro params["value"] = value params["hostid"] = hostid params = _params_extend(params, _ignore_name=True, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["hostmacroids"][0] else: raise KeyError except KeyError: return ret def usermacro_createglobal(macro, value, **connection_args): """ Create new global usermacro. :param macro: name of the global usermacro :param value: value of the global usermacro :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) return: ID of the created global usermacro. CLI Example: .. code-block:: bash salt '*' zabbix.usermacro_createglobal '{$SNMP_COMMUNITY}' 'public' """ conn_args = _login(**connection_args) ret = False try: if conn_args: params = {} method = "usermacro.createglobal" if macro: # Python mistakenly interprets macro names starting and ending with '{' and '}' as a dict if isinstance(macro, dict): macro = "{" + str(next(iter(macro))) + "}" if not macro.startswith("{") and not macro.endswith("}"): macro = "{" + macro + "}" params["macro"] = macro params["value"] = value params = _params_extend(params, _ignore_name=True, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["globalmacroids"][0] else: raise KeyError except KeyError: return ret def usermacro_delete(macroids, **connection_args): """ Delete host usermacros. :param macroids: macroids of the host usermacros :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) return: IDs of the deleted host usermacro. CLI Example: .. code-block:: bash salt '*' zabbix.usermacro_delete 21 """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "usermacro.delete" if isinstance(macroids, list): params = macroids else: params = [macroids] ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["hostmacroids"] else: raise KeyError except KeyError: return ret def usermacro_deleteglobal(macroids, **connection_args): """ Delete global usermacros. :param macroids: macroids of the global usermacros :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) return: IDs of the deleted global usermacro. CLI Example: .. code-block:: bash salt '*' zabbix.usermacro_deleteglobal 21 """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "usermacro.deleteglobal" if isinstance(macroids, list): params = macroids else: params = [macroids] ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["globalmacroids"] else: raise KeyError except KeyError: return ret def usermacro_update(hostmacroid, value, **connection_args): """ Update existing host usermacro. :param hostmacroid: id of the host usermacro :param value: new value of the host usermacro :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) return: ID of the update host usermacro. CLI Example: .. code-block:: bash salt '*' zabbix.usermacro_update 1 'public' """ conn_args = _login(**connection_args) ret = False try: if conn_args: params = {} method = "usermacro.update" params["hostmacroid"] = hostmacroid params["value"] = value params = _params_extend(params, _ignore_name=True, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["hostmacroids"][0] else: raise KeyError except KeyError: return ret def usermacro_updateglobal(globalmacroid, value, **connection_args): """ Update existing global usermacro. :param globalmacroid: id of the host usermacro :param value: new value of the host usermacro :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) return: ID of the update global usermacro. CLI Example: .. code-block:: bash salt '*' zabbix.usermacro_updateglobal 1 'public' """ conn_args = _login(**connection_args) ret = False try: if conn_args: params = {} method = "usermacro.updateglobal" params["globalmacroid"] = globalmacroid params["value"] = value params = _params_extend(params, _ignore_name=True, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["globalmacroids"][0] else: raise KeyError except KeyError: return ret def mediatype_get(name=None, mediatypeids=None, **connection_args): """ Retrieve mediatypes according to the given parameters. Args: name: Name or description of the mediatype mediatypeids: ids of the mediatypes optional connection_args: _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring) _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring) _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring) all optional mediatype.get parameters: keyword argument names depends on your zabbix version, see: https://www.zabbix.com/documentation/2.2/manual/api/reference/mediatype/get Returns: Array with mediatype details, False if no mediatype found or on failure. CLI Example: .. code-block:: bash salt '*' zabbix.mediatype_get name='Email' salt '*' zabbix.mediatype_get mediatypeids="['1', '2', '3']" """ conn_args = _login(**connection_args) zabbix_version = apiinfo_version(**connection_args) ret = False try: if conn_args: method = "mediatype.get" params = {"output": "extend", "filter": {}} if name: # since zabbix API 4.4, mediatype has new attribute: name if _LooseVersion(zabbix_version) >= _LooseVersion("4.4"): params["filter"].setdefault("name", name) else: params["filter"].setdefault("description", name) if mediatypeids: params.setdefault("mediatypeids", mediatypeids) params = _params_extend(params, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"] if len(ret["result"]) > 0 else False else: raise KeyError except KeyError: return ret def mediatype_create(name, mediatype, **connection_args): """ Create new mediatype .. note:: This function accepts all standard mediatype properties: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object :param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting :param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs :param gsm_modem: exec path - Required for sms type, see Zabbix API docs :param smtp_email: email address from which notifications will be sent, required for email type :param smtp_helo: SMTP HELO, required for email type :param smtp_server: SMTP server, required for email type :param status: whether the media type is enabled - 0: enabled, 1: disabled :param username: authentication user, required for Jabber and Ez Texting types :param passwd: authentication password, required for Jabber and Ez Texting types :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) return: ID of the created mediatype. CLI Example: .. code-block:: bash salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com' smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com' """ conn_args = _login(**connection_args) zabbix_version = apiinfo_version(**connection_args) ret = False try: if conn_args: method = "mediatype.create" # since zabbix 4.4 api, mediatype has new attribute: name if _LooseVersion(zabbix_version) >= _LooseVersion("4.4"): params = {"name": name} _ignore_name = False else: params = {"description": name} _ignore_name = True params["type"] = mediatype params = _params_extend(params, _ignore_name, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["mediatypeid"] else: raise KeyError except KeyError: return ret def mediatype_delete(mediatypeids, **connection_args): """ Delete mediatype :param interfaceids: IDs of the mediatypes to delete :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: ID of deleted mediatype, False on failure. CLI Example: .. code-block:: bash salt '*' zabbix.mediatype_delete 3 """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "mediatype.delete" if isinstance(mediatypeids, list): params = mediatypeids else: params = [mediatypeids] ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["mediatypeids"] else: raise KeyError except KeyError: return ret def mediatype_update(mediatypeid, name=False, mediatype=False, **connection_args): """ Update existing mediatype .. note:: This function accepts all standard mediatype properties: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object :param mediatypeid: ID of the mediatype to update :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) :return: IDs of the updated mediatypes, False on failure. CLI Example: .. code-block:: bash salt '*' zabbix.usergroup_update 8 name="Email update" """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "mediatype.update" params = {"mediatypeid": mediatypeid} if name: params["description"] = name if mediatype: params["type"] = mediatype params = _params_extend(params, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"]["mediatypeids"] else: raise KeyError except KeyError: return ret def template_get(name=None, host=None, templateids=None, **connection_args): """ Retrieve templates according to the given parameters. Args: host: technical name of the template name: visible name of the template hostids: ids of the templates optional connection_args: _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring) _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring) _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring) all optional template.get parameters: keyword argument names depends on your zabbix version, see: https://www.zabbix.com/documentation/2.4/manual/api/reference/template/get Returns: Array with convenient template details, False if no template found or on failure. CLI Example: .. code-block:: bash salt '*' zabbix.template_get name='Template OS Linux' salt '*' zabbix.template_get templateids="['10050', '10001']" """ conn_args = _login(**connection_args) ret = False try: if conn_args: method = "template.get" params = {"output": "extend", "filter": {}} if name: params["filter"].setdefault("name", name) if host: params["filter"].setdefault("host", host) if templateids: params.setdefault("templateids", templateids) params = _params_extend(params, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) return ret["result"] if len(ret["result"]) > 0 else False else: raise KeyError except KeyError: return ret def run_query(method, params, **connection_args): """ Send Zabbix API call Args: method: actual operation to perform via the API params: parameters required for specific method optional connection_args: _connection_user: zabbix user (can also be set in opts or pillar, see module's docstring) _connection_password: zabbix password (can also be set in opts or pillar, see module's docstring) _connection_url: url of zabbix frontend (can also be set in opts or pillar, see module's docstring) all optional template.get parameters: keyword argument names depends on your zabbix version, see: https://www.zabbix.com/documentation/2.4/manual/api/reference/ Returns: Response from Zabbix API CLI Example: .. code-block:: bash salt '*' zabbix.run_query proxy.create '{"host": "zabbixproxy.domain.com", "status": "5"}' """ conn_args = _login(**connection_args) ret = False try: if conn_args: params = _params_extend(params, **connection_args) ret = _query(method, params, conn_args["url"], conn_args["auth"]) if isinstance(ret["result"], bool): return ret["result"] if ret["result"] is True or len(ret["result"]) > 0: return ret["result"] else: return False else: raise KeyError except KeyError: return ret def configuration_import(config_file, rules=None, file_format="xml", **connection_args): """ .. versionadded:: 2017.7 Imports Zabbix configuration specified in file to Zabbix server. :param config_file: File with Zabbix config (local or remote) :param rules: Optional - Rules that have to be different from default (defaults are the same as in Zabbix web UI.) :param file_format: Config file format (default: xml) :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring) CLI Example: .. code-block:: bash salt '*' zabbix.configuration_import salt://zabbix/config/zabbix_templates.xml \ "{'screens': {'createMissing': True, 'updateExisting': True}}" """ zabbix_version = apiinfo_version(**connection_args) if rules is None: rules = {} default_rules = { "discoveryRules": { "createMissing": True, "updateExisting": True, "deleteMissing": False, }, "graphs": { "createMissing": True, "updateExisting": True, "deleteMissing": False, }, "groups": {"createMissing": True}, "hosts": {"createMissing": False, "updateExisting": False}, "images": {"createMissing": False, "updateExisting": False}, "items": { "createMissing": True, "updateExisting": True, "deleteMissing": False, }, "maps": {"createMissing": False, "updateExisting": False}, "screens": {"createMissing": False, "updateExisting": False}, "templateLinkage": {"createMissing": True}, "templates": {"createMissing": True, "updateExisting": True}, "templateScreens": { "createMissing": True, "updateExisting": True, "deleteMissing": False, }, "triggers": { "createMissing": True, "updateExisting": True, "deleteMissing": False, }, "valueMaps": {"createMissing": True, "updateExisting": False}, } if _LooseVersion(zabbix_version) >= _LooseVersion("3.2"): # rules/httptests added default_rules["httptests"] = { "createMissing": True, "updateExisting": True, "deleteMissing": False, } if _LooseVersion(zabbix_version) >= _LooseVersion("3.4"): # rules/applications/upateExisting deprecated default_rules["applications"] = {"createMissing": True, "deleteMissing": False} else: default_rules["applications"] = { "createMissing": True, "updateExisting": True, "deleteMissing": False, } new_rules = dict(default_rules) if rules: for rule in rules: if rule in new_rules: new_rules[rule].update(rules[rule]) else: new_rules[rule] = rules[rule] if "salt://" in config_file: tmpfile = salt.utils.files.mkstemp() cfile = __salt__["cp.get_file"](config_file, tmpfile) if not cfile or os.path.getsize(cfile) == 0: return { "name": config_file, "result": False, "message": "Failed to fetch config file.", } else: cfile = config_file if not os.path.isfile(cfile): return { "name": config_file, "result": False, "message": "Invalid file path.", } with salt.utils.files.fopen(cfile, mode="r") as fp_: xml = fp_.read() if "salt://" in config_file: salt.utils.files.safe_rm(cfile) params = {"format": file_format, "rules": new_rules, "source": xml} log.info("CONFIGURATION IMPORT: rules: %s", str(params["rules"])) try: run_query("configuration.import", params, **connection_args) return { "name": config_file, "result": True, "message": 'Zabbix API "configuration.import" method called successfully.', } except SaltException as exc: return {"name": config_file, "result": False, "message": str(exc)}
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/zabbix.py
0.427277
0.154504
zabbix.py
pypi
import salt.exceptions import salt.utils.path def __virtual__(): """ Only work on Gentoo systems with layman installed """ if __grains__["os"] == "Gentoo" and salt.utils.path.which("layman"): return "layman" return ( False, "layman execution module cannot be loaded: only available on Gentoo with layman" " installed.", ) def _get_makeconf(): """ Find the correct make.conf. Gentoo recently moved the make.conf but still supports the old location, using the old location first """ old_conf = "/etc/make.conf" new_conf = "/etc/portage/make.conf" if __salt__["file.file_exists"](old_conf): return old_conf elif __salt__["file.file_exists"](new_conf): return new_conf def add(overlay): """ Add the given overlay from the cached remote list to your locally installed overlays. Specify 'ALL' to add all overlays from the remote list. Return a list of the new overlay(s) added: CLI Example: .. code-block:: bash salt '*' layman.add <overlay name> """ ret = list() old_overlays = list_local() cmd = "layman --quietness=0 --add {}".format(overlay) add_attempt = __salt__["cmd.run_all"](cmd, python_shell=False, stdin="y") if add_attempt["retcode"] != 0: raise salt.exceptions.CommandExecutionError(add_attempt["stdout"]) new_overlays = list_local() # If we did not have any overlays before and we successfully added # a new one. We need to ensure the make.conf is sourcing layman's # make.conf so emerge can see the overlays if not old_overlays and new_overlays: srcline = "source /var/lib/layman/make.conf" makeconf = _get_makeconf() if not __salt__["file.contains"](makeconf, "layman"): __salt__["file.append"](makeconf, srcline) ret = [overlay for overlay in new_overlays if overlay not in old_overlays] return ret def delete(overlay): """ Remove the given overlay from the your locally installed overlays. Specify 'ALL' to remove all overlays. Return a list of the overlays(s) that were removed: CLI Example: .. code-block:: bash salt '*' layman.delete <overlay name> """ ret = list() old_overlays = list_local() cmd = "layman --quietness=0 --delete {}".format(overlay) delete_attempt = __salt__["cmd.run_all"](cmd, python_shell=False) if delete_attempt["retcode"] != 0: raise salt.exceptions.CommandExecutionError(delete_attempt["stdout"]) new_overlays = list_local() # If we now have no overlays added, We need to ensure that the make.conf # does not source layman's make.conf, as it will break emerge if not new_overlays: srcline = "source /var/lib/layman/make.conf" makeconf = _get_makeconf() if __salt__["file.contains"](makeconf, "layman"): __salt__["file.sed"](makeconf, srcline, "") ret = [overlay for overlay in old_overlays if overlay not in new_overlays] return ret def sync(overlay="ALL"): """ Update the specified overlay. Use 'ALL' to synchronize all overlays. This is the default if no overlay is specified. overlay Name of the overlay to sync. (Defaults to 'ALL') CLI Example: .. code-block:: bash salt '*' layman.sync """ cmd = "layman --quietness=0 --sync {}".format(overlay) return __salt__["cmd.retcode"](cmd, python_shell=False) == 0 def list_local(): """ List the locally installed overlays. Return a list of installed overlays: CLI Example: .. code-block:: bash salt '*' layman.list_local """ cmd = "layman --quietness=1 --list-local --nocolor" out = __salt__["cmd.run"](cmd, python_shell=False).split("\n") ret = [line.split()[1] for line in out if len(line.split()) > 2] return ret def list_all(): """ List all overlays, including remote ones. Return a list of available overlays: CLI Example: .. code-block:: bash salt '*' layman.list_all """ cmd = "layman --quietness=1 --list --nocolor" out = __salt__["cmd.run"](cmd, python_shell=False).split("\n") ret = [line.split()[1] for line in out if len(line.split()) > 2] return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/layman.py
0.669421
0.238434
layman.py
pypi
import logging import salt.utils.data import salt.utils.path from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) def __virtual__(): """ Only load if hg is installed """ if salt.utils.path.which("hg") is None: return (False, "The hg execution module cannot be loaded: hg unavailable.") else: return True def _ssh_flag(identity_path): return ["--ssh", "ssh -i {}".format(identity_path)] def revision(cwd, rev="tip", short=False, user=None): """ Returns the long hash of a given identifier (hash, branch, tag, HEAD, etc) cwd The path to the Mercurial repository rev: tip The revision short: False Return an abbreviated commit hash user : None Run hg as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' hg.revision /path/to/repo mybranch """ cmd = ["hg", "id", "-i", "--debug" if not short else "", "-r", "{}".format(rev)] result = __salt__["cmd.run_all"](cmd, cwd=cwd, runas=user, python_shell=False) if result["retcode"] == 0: return result["stdout"] else: return "" def describe(cwd, rev="tip", user=None): """ Mimic git describe and return an identifier for the given revision cwd The path to the Mercurial repository rev: tip The path to the archive tarball user : None Run hg as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' hg.describe /path/to/repo """ cmd = [ "hg", "log", "-r", "{}".format(rev), "--template", "'{{latesttag}}-{{latesttagdistance}}-{{node|short}}'", ] desc = __salt__["cmd.run_stdout"](cmd, cwd=cwd, runas=user, python_shell=False) return desc or revision(cwd, rev, short=True) def archive(cwd, output, rev="tip", fmt=None, prefix=None, user=None): """ Export a tarball from the repository cwd The path to the Mercurial repository output The path to the archive tarball rev: tip The revision to create an archive from fmt: None Format of the resulting archive. Mercurial supports: tar, tbz2, tgz, zip, uzip, and files formats. prefix : None Prepend <prefix>/ to every filename in the archive user : None Run hg as a user other than what the minion runs as If ``prefix`` is not specified it defaults to the basename of the repo directory. CLI Example: .. code-block:: bash salt '*' hg.archive /path/to/repo output=/tmp/archive.tgz fmt=tgz """ cmd = [ "hg", "archive", "{}".format(output), "--rev", "{}".format(rev), ] if fmt: cmd.append("--type") cmd.append("{}".format(fmt)) if prefix: cmd.append("--prefix") cmd.append('"{}"'.format(prefix)) return __salt__["cmd.run"](cmd, cwd=cwd, runas=user, python_shell=False) def pull(cwd, opts=None, user=None, identity=None, repository=None): """ Perform a pull on the given repository cwd The path to the Mercurial repository repository : None Perform pull from the repository different from .hg/hgrc:[paths]:default opts : None Any additional options to add to the command line user : None Run hg as a user other than what the minion runs as identity : None Private SSH key on the minion server for authentication (ssh://) .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' hg.pull /path/to/repo opts=-u """ cmd = ["hg", "pull"] if identity: cmd.extend(_ssh_flag(identity)) if opts: for opt in opts.split(): cmd.append(opt) if repository is not None: cmd.append(repository) ret = __salt__["cmd.run_all"](cmd, cwd=cwd, runas=user, python_shell=False) if ret["retcode"] != 0: raise CommandExecutionError( "Hg command failed: {}".format(ret.get("stderr", ret["stdout"])) ) return ret["stdout"] def update(cwd, rev, force=False, user=None): """ Update to a given revision cwd The path to the Mercurial repository rev The revision to update to force : False Force an update user : None Run hg as a user other than what the minion runs as CLI Example: .. code-block:: bash salt devserver1 hg.update /path/to/repo somebranch """ cmd = ["hg", "update", "{}".format(rev)] if force: cmd.append("-C") ret = __salt__["cmd.run_all"](cmd, cwd=cwd, runas=user, python_shell=False) if ret["retcode"] != 0: raise CommandExecutionError( "Hg command failed: {}".format(ret.get("stderr", ret["stdout"])) ) return ret["stdout"] def clone(cwd, repository, opts=None, user=None, identity=None): """ Clone a new repository cwd The path to the Mercurial repository repository The hg URI of the repository opts : None Any additional options to add to the command line user : None Run hg as a user other than what the minion runs as identity : None Private SSH key on the minion server for authentication (ssh://) .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' hg.clone /path/to/repo https://bitbucket.org/birkenfeld/sphinx """ cmd = ["hg", "clone", "{}".format(repository), "{}".format(cwd)] if opts: for opt in opts.split(): cmd.append("{}".format(opt)) if identity: cmd.extend(_ssh_flag(identity)) ret = __salt__["cmd.run_all"](cmd, runas=user, python_shell=False) if ret["retcode"] != 0: raise CommandExecutionError( "Hg command failed: {}".format(ret.get("stderr", ret["stdout"])) ) return ret["stdout"] def status(cwd, opts=None, user=None): """ Show changed files of the given repository cwd The path to the Mercurial repository opts : None Any additional options to add to the command line user : None Run hg as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' hg.status /path/to/repo """ def _status(cwd): cmd = ["hg", "status"] if opts: for opt in opts.split(): cmd.append("{}".format(opt)) out = __salt__["cmd.run_stdout"](cmd, cwd=cwd, runas=user, python_shell=False) types = { "M": "modified", "A": "added", "R": "removed", "C": "clean", "!": "missing", "?": "not tracked", "I": "ignored", " ": "origin of the previous file", } ret = {} for line in out.splitlines(): t, f = types[line[0]], line[2:] if t not in ret: ret[t] = [] ret[t].append(f) return ret if salt.utils.data.is_iter(cwd): return {cwd: _status(cwd) for cwd in cwd} else: return _status(cwd)
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/hg.py
0.644784
0.23965
hg.py
pypi
HAS_SHADE = False try: import shade HAS_SHADE = True except ImportError: pass __virtualname__ = "glanceng" def __virtual__(): """ Only load this module if shade python module is installed """ if HAS_SHADE: return __virtualname__ return ( False, "The glanceng execution module failed to load: shade python module is not" " available", ) def compare_changes(obj, **kwargs): """ Compare two dicts returning only keys that exist in the first dict and are different in the second one """ changes = {} for k, v in obj.items(): if k in kwargs: if v != kwargs[k]: changes[k] = kwargs[k] return changes def _clean_kwargs(keep_name=False, **kwargs): """ Sanatize the arguments for use with shade """ if "name" in kwargs and not keep_name: kwargs["name_or_id"] = kwargs.pop("name") return __utils__["args.clean_kwargs"](**kwargs) def setup_clouds(auth=None): """ Call functions to create Shade cloud objects in __context__ to take advantage of Shade's in-memory caching across several states """ get_operator_cloud(auth) get_openstack_cloud(auth) def get_operator_cloud(auth=None): """ Return an operator_cloud """ if auth is None: auth = __salt__["config.option"]("glance", {}) if "shade_opcloud" in __context__: if __context__["shade_opcloud"].auth == auth: return __context__["shade_opcloud"] __context__["shade_opcloud"] = shade.operator_cloud(**auth) return __context__["shade_opcloud"] def get_openstack_cloud(auth=None): """ Return an openstack_cloud """ if auth is None: auth = __salt__["config.option"]("glance", {}) if "shade_oscloud" in __context__: if __context__["shade_oscloud"].auth == auth: return __context__["shade_oscloud"] __context__["shade_oscloud"] = shade.openstack_cloud(**auth) return __context__["shade_oscloud"] def image_create(auth=None, **kwargs): """ Create an image CLI Example: .. code-block:: bash salt '*' glanceng.image_create name=cirros file=cirros.raw disk_format=raw salt '*' glanceng.image_create name=cirros file=cirros.raw disk_format=raw hw_scsi_model=virtio-scsi hw_disk_bus=scsi """ cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(keep_name=True, **kwargs) return cloud.create_image(**kwargs) def image_delete(auth=None, **kwargs): """ Delete an image CLI Example: .. code-block:: bash salt '*' glanceng.image_delete name=image1 salt '*' glanceng.image_delete name=0e4febc2a5ab4f2c8f374b054162506d """ cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.delete_image(**kwargs) def image_list(auth=None, **kwargs): """ List images CLI Example: .. code-block:: bash salt '*' glanceng.image_list salt '*' glanceng.image_list """ cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.list_images(**kwargs) def image_search(auth=None, **kwargs): """ Search for images CLI Example: .. code-block:: bash salt '*' glanceng.image_search name=image1 salt '*' glanceng.image_search """ cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.search_images(**kwargs) def image_get(auth=None, **kwargs): """ Get a single image CLI Example: .. code-block:: bash salt '*' glanceng.image_get name=image1 salt '*' glanceng.image_get name=0e4febc2a5ab4f2c8f374b054162506d """ cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.get_image(**kwargs) def update_image_properties(auth=None, **kwargs): """ Update properties for an image CLI Example: .. code-block:: bash salt '*' glanceng.update_image_properties name=image1 hw_scsi_model=virtio-scsi hw_disk_bus=scsi salt '*' glanceng.update_image_properties name=0e4febc2a5ab4f2c8f374b054162506d min_ram=1024 """ cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.update_image_properties(**kwargs)
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/glanceng.py
0.692642
0.184143
glanceng.py
pypi
import logging import salt.utils.json import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) # Function aliases __func_alias__ = { "list_installed": "list", "update_installed": "update", "import_image": "import", } # Define the module's virtual name __virtualname__ = "imgadm" def __virtual__(): """ Provides imgadm only on SmartOS """ if salt.utils.platform.is_smartos_globalzone() and salt.utils.path.which("imgadm"): return __virtualname__ return ( False, "{} module can only be loaded on SmartOS compute nodes".format(__virtualname__), ) def _exit_status(retcode, stderr=None): """ Translate exit status of imgadm """ ret = { 0: "Successful completion.", 1: "An error occurred." if not stderr else stderr, 2: "Usage error.", 3: "Image not installed.", }[retcode] return ret def _parse_image_meta(image=None, detail=False): ret = None if image and "Error" in image: ret = image elif image and "manifest" in image and "name" in image["manifest"]: name = image["manifest"]["name"] version = image["manifest"]["version"] os = image["manifest"]["os"] description = image["manifest"]["description"] published = image["manifest"]["published_at"] source = image["source"] if image["manifest"]["name"] == "docker-layer": # NOTE: skip docker-layer unless it has a docker:repo and docker:tag name = None docker_repo = None docker_tag = None for tag in image["manifest"]["tags"]: if tag.startswith("docker:tag:") and image["manifest"]["tags"][tag]: docker_tag = tag.split(":")[-1] elif tag == "docker:repo": docker_repo = image["manifest"]["tags"][tag] if docker_repo and docker_tag: name = "{}:{}".format(docker_repo, docker_tag) description = ( "Docker image imported from {repo}:{tag} on {date}.".format( repo=docker_repo, tag=docker_tag, date=published, ) ) if name and detail: ret = { "name": name, "version": version, "os": os, "description": description, "published": published, "source": source, } elif name: ret = "{name}@{version} [{published}]".format( name=name, version=version, published=published, ) else: log.debug("smartos_image - encountered invalid image payload: %s", image) ret = {"Error": "This looks like an orphaned image, image payload was invalid."} return ret def _split_docker_uuid(uuid): """ Split a smartos docker uuid into repo and tag """ if uuid: uuid = uuid.split(":") if len(uuid) == 2: tag = uuid[1] repo = uuid[0] return repo, tag return None, None def _is_uuid(uuid): """ Check if uuid is a valid smartos uuid Example: e69a0918-055d-11e5-8912-e3ceb6df4cf8 """ if uuid and list(len(x) for x in uuid.split("-")) == [8, 4, 4, 4, 12]: return True return False def _is_docker_uuid(uuid): """ Check if uuid is a valid smartos docker uuid Example plexinc/pms-docker:plexpass """ repo, tag = _split_docker_uuid(uuid) return not (not repo and not tag) def version(): """ Return imgadm version CLI Example: .. code-block:: bash salt '*' imgadm.version """ ret = {} cmd = "imgadm --version" res = __salt__["cmd.run"](cmd).splitlines() ret = res[0].split() return ret[-1] def docker_to_uuid(uuid): """ Get the image uuid from an imported docker image .. versionadded:: 2019.2.0 """ if _is_uuid(uuid): return uuid if _is_docker_uuid(uuid): images = list_installed(verbose=True) for image_uuid in images: if "name" not in images[image_uuid]: continue if images[image_uuid]["name"] == uuid: return image_uuid return None def update_installed(uuid=""): """ Gather info on unknown image(s) (locally installed) uuid : string optional uuid of image CLI Example: .. code-block:: bash salt '*' imgadm.update [uuid] """ cmd = "imgadm update {}".format(uuid).rstrip() __salt__["cmd.run"](cmd) return {} def avail(search=None, verbose=False): """ Return a list of available images search : string search keyword verbose : boolean (False) toggle verbose output CLI Example: .. code-block:: bash salt '*' imgadm.avail [percona] salt '*' imgadm.avail verbose=True """ ret = {} cmd = "imgadm avail -j" res = __salt__["cmd.run_all"](cmd) retcode = res["retcode"] if retcode != 0: ret["Error"] = _exit_status(retcode) return ret for image in salt.utils.json.loads(res["stdout"]): if image["manifest"]["disabled"] or not image["manifest"]["public"]: continue if search and search not in image["manifest"]["name"]: # we skip if we are searching but don't have a match continue uuid = image["manifest"]["uuid"] data = _parse_image_meta(image, verbose) if data: ret[uuid] = data return ret def list_installed(verbose=False): """ Return a list of installed images verbose : boolean (False) toggle verbose output .. versionchanged:: 2019.2.0 Docker images are now also listed CLI Example: .. code-block:: bash salt '*' imgadm.list salt '*' imgadm.list docker=True salt '*' imgadm.list verbose=True """ ret = {} cmd = "imgadm list -j" res = __salt__["cmd.run_all"](cmd) retcode = res["retcode"] if retcode != 0: ret["Error"] = _exit_status(retcode) return ret for image in salt.utils.json.loads(res["stdout"]): uuid = image["manifest"]["uuid"] data = _parse_image_meta(image, verbose) if data: ret[uuid] = data return ret def show(uuid): """ Show manifest of a given image uuid : string uuid of image CLI Example: .. code-block:: bash salt '*' imgadm.show e42f8c84-bbea-11e2-b920-078fab2aab1f salt '*' imgadm.show plexinc/pms-docker:plexpass """ ret = {} if _is_uuid(uuid) or _is_docker_uuid(uuid): cmd = "imgadm show {}".format(uuid) res = __salt__["cmd.run_all"](cmd, python_shell=False) retcode = res["retcode"] if retcode != 0: ret["Error"] = _exit_status(retcode, res["stderr"]) else: ret = salt.utils.json.loads(res["stdout"]) else: ret["Error"] = "{} is not a valid uuid.".format(uuid) return ret def get(uuid): """ Return info on an installed image uuid : string uuid of image CLI Example: .. code-block:: bash salt '*' imgadm.get e42f8c84-bbea-11e2-b920-078fab2aab1f salt '*' imgadm.get plexinc/pms-docker:plexpass """ ret = {} if _is_docker_uuid(uuid): uuid = docker_to_uuid(uuid) if _is_uuid(uuid): cmd = "imgadm get {}".format(uuid) res = __salt__["cmd.run_all"](cmd, python_shell=False) retcode = res["retcode"] if retcode != 0: ret["Error"] = _exit_status(retcode, res["stderr"]) else: ret = salt.utils.json.loads(res["stdout"]) else: ret["Error"] = "{} is not a valid uuid.".format(uuid) return ret def import_image(uuid, verbose=False): """ Import an image from the repository uuid : string uuid to import verbose : boolean (False) toggle verbose output CLI Example: .. code-block:: bash salt '*' imgadm.import e42f8c84-bbea-11e2-b920-078fab2aab1f [verbose=True] """ ret = {} cmd = "imgadm import {}".format(uuid) res = __salt__["cmd.run_all"](cmd, python_shell=False) retcode = res["retcode"] if retcode != 0: ret["Error"] = _exit_status(retcode) return ret uuid = docker_to_uuid(uuid) data = _parse_image_meta(get(uuid), verbose) return {uuid: data} def delete(uuid): """ Remove an installed image uuid : string Specifies uuid to import CLI Example: .. code-block:: bash salt '*' imgadm.delete e42f8c84-bbea-11e2-b920-078fab2aab1f """ ret = {} cmd = "imgadm delete {}".format(uuid) res = __salt__["cmd.run_all"](cmd, python_shell=False) retcode = res["retcode"] if retcode != 0: ret["Error"] = _exit_status(retcode) return ret # output: Deleted image d5b3865c-0804-11e5-be21-dbc4ce844ddc result = [] for image in res["stdout"].splitlines(): image = [var for var in image.split(" ") if var] result.append(image[2]) return result def vacuum(verbose=False): """ Remove unused images verbose : boolean (False) toggle verbose output CLI Example: .. code-block:: bash salt '*' imgadm.vacuum [verbose=True] """ ret = {} cmd = "imgadm vacuum -f" res = __salt__["cmd.run_all"](cmd) retcode = res["retcode"] if retcode != 0: ret["Error"] = _exit_status(retcode) return ret # output: Deleted image d5b3865c-0804-11e5-be21-dbc4ce844ddc (lx-centos-6@20150601) result = {} for image in res["stdout"].splitlines(): image = [var for var in image.split(" ") if var] result[image[2]] = { "name": image[3][1 : image[3].index("@")], "version": image[3][image[3].index("@") + 1 : -1], } if verbose: return result else: return list(result.keys()) def sources(verbose=False): """ Return a list of available sources verbose : boolean (False) toggle verbose output .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' imgadm.sources """ ret = {} cmd = "imgadm sources -j" res = __salt__["cmd.run_all"](cmd) retcode = res["retcode"] if retcode != 0: ret["Error"] = _exit_status(retcode) return ret for src in salt.utils.json.loads(res["stdout"]): ret[src["url"]] = src del src["url"] if not verbose: ret = list(ret) return ret def source_delete(source): """ Delete a source source : string source url to delete .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' imgadm.source_delete https://updates.joyent.com """ ret = {} cmd = "imgadm sources -d {}".format(source) res = __salt__["cmd.run_all"](cmd) retcode = res["retcode"] if retcode != 0: ret["Error"] = _exit_status(retcode, res["stderr"]) return ret return sources(False) def source_add(source, source_type="imgapi"): """ Add a new source source : string source url to add source_trype : string (imgapi) source type, either imgapi or docker .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' imgadm.source_add https://updates.joyent.com salt '*' imgadm.source_add https://docker.io docker """ ret = {} # NOTE: there are some undocumented deprecated source types # so we just warn instead of error on those if source_type not in ["imgapi", "docker"]: log.warning("Possible unsupported imgage source type specified!") cmd = "imgadm sources -a {} -t {}".format(source, source_type) res = __salt__["cmd.run_all"](cmd) retcode = res["retcode"] if retcode != 0: ret["Error"] = _exit_status(retcode, res["stderr"]) return ret return sources(False) # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/smartos_imgadm.py
0.508788
0.164148
smartos_imgadm.py
pypi
import salt.utils.path import salt.utils.platform # Define the module's virtual name __virtualname__ = "system" def __virtual__(): """ Only supported on Solaris-like systems """ if not salt.utils.platform.is_sunos() or not salt.utils.path.which("shutdown"): return ( False, "The system execution module failed to load: only available on " "Solaris-like ystems with shutdown command.", ) return __virtualname__ def halt(): """ Halt a running system CLI Example: .. code-block:: bash salt '*' system.halt """ return shutdown() def init(state): """ Change the system runlevel on sysV compatible systems CLI Example: state : string Init state .. code-block:: bash salt '*' system.init 3 .. note: state 0 Stop the operating system. state 1 State 1 is referred to as the administrative state. In state 1 file systems required for multi-user operations are mounted, and logins requiring access to multi-user file systems can be used. When the system comes up from firmware mode into state 1, only the console is active and other multi-user (state 2) services are unavailable. Note that not all user processes are stopped when transitioning from multi-user state to state 1. state s, S State s (or S) is referred to as the single-user state. All user processes are stopped on transitions to this state. In the single-user state, file systems required for multi-user logins are unmounted and the system can only be accessed through the console. Logins requiring access to multi-user file systems cannot be used. state 5 Shut the machine down so that it is safe to remove the power. Have the machine remove power, if possible. The rc0 procedure is called to perform this task. state 6 Stop the operating system and reboot to the state defined by the initdefault entry in /etc/inittab. The rc6 procedure is called to perform this task. """ cmd = ["shutdown", "-i", state, "-g", "0", "-y"] ret = __salt__["cmd.run"](cmd, python_shell=False) return ret def poweroff(): """ Poweroff a running system CLI Example: .. code-block:: bash salt '*' system.poweroff """ return shutdown() def reboot(delay=0, message=None): """ Reboot the system delay : int Optional wait time in seconds before the system will be rebooted. message : string Optional message to broadcast before rebooting. CLI Example: .. code-block:: bash salt '*' system.reboot salt '*' system.reboot 60 "=== system upgraded ===" """ cmd = ["shutdown", "-i", "6", "-g", delay, "-y"] if message: cmd.append(message) ret = __salt__["cmd.run"](cmd, python_shell=False) return ret def shutdown(delay=0, message=None): """ Shutdown a running system delay : int Optional wait time in seconds before the system will be shutdown. message : string Optional message to broadcast before rebooting. CLI Example: .. code-block:: bash salt '*' system.shutdown salt '*' system.shutdown 60 "=== disk replacement ===" """ cmd = ["shutdown", "-i", "5", "-g", delay, "-y"] if message: cmd.append(message) ret = __salt__["cmd.run"](cmd, python_shell=False) return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/solaris_system.py
0.534612
0.408513
solaris_system.py
pypi
import logging import salt.utils.versions import salt.version log = logging.getLogger(__name__) __virtualname__ = "salt_version" def __virtual__(): """ Only work on POSIX-like systems """ return __virtualname__ def get_release_number(name): """ Returns the release number of a given release code name in a ``MAJOR.PATCH`` format. If the release name has not been given an assigned release number, the function returns a string. If the release cannot be found, it returns ``None``. name The release code name for which to find a release number. CLI Example: .. code-block:: bash salt '*' salt_version.get_release_number 'Oxygen' """ name = name.lower() version_map = salt.version.SaltStackVersion.LNAMES version = version_map.get(name) if version is None: log.info("Version %s not found.", name) return None try: if version[1] == 0: log.info( "Version %s found, but no release number has been assigned yet.", name ) return "No version assigned." except IndexError: # The new versioning scheme does not include minor version pass return ".".join(str(item) for item in version) def equal(name): """ Returns a boolean (True) if the minion's current version code name matches the named version. name The release code name to check the version against. CLI Example: .. code-block:: bash salt '*' salt_version.equal 'Oxygen' """ if _check_release_cmp(name) == 0: log.info("The minion's version code name matches '%s'.", name) return True return False def greater_than(name): """ Returns a boolean (True) if the minion's current version code name is greater than the named version. name The release code name to check the version against. CLI Example: .. code-block:: bash salt '*' salt_version.greater_than 'Oxygen' """ if _check_release_cmp(name) == 1: log.info("The minion's version code name is greater than '%s'.", name) return True return False def less_than(name): """ Returns a boolean (True) if the minion's current version code name is less than the named version. name The release code name to check the version against. CLI Example: .. code-block:: bash salt '*' salt_version.less_than 'Oxygen' """ if _check_release_cmp(name) == -1: log.info("The minion's version code name is less than '%s'.", name) return True return False def _check_release_cmp(name): """ Helper function to compare the minion's current Salt version to release code name versions. If release code name isn't found, the function returns None. Otherwise, it returns the results of the version comparison as documented by the ``versions_cmp`` function in ``salt.utils.versions.py``. """ map_version = get_release_number(name) if map_version is None: log.info("Release code name %s was not found.", name) return None current_version = str(salt.version.SaltStackVersion(*salt.version.__version_info__)) current_version = current_version.rsplit(".", 1)[0] version_cmp = salt.utils.versions.version_cmp(current_version, map_version) return version_cmp
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/salt_version.py
0.823612
0.184859
salt_version.py
pypi
import shlex import salt.exceptions import salt.utils.decorators.path try: import pipes HAS_DEPS = True except ImportError: HAS_DEPS = False if hasattr(shlex, "quote"): _quote = shlex.quote elif HAS_DEPS and hasattr(pipes, "quote"): _quote = pipes.quote else: _quote = None # Don't shadow built-in's. __func_alias__ = {"set_": "set"} def __virtual__(): if _quote is None and not HAS_DEPS: return (False, "Missing dependencies") return True def _fallback(*args, **kw): return ( 'The "openstack-config" command needs to be installed for this function to' ' work. Typically this is included in the "openstack-utils" package.' ) @salt.utils.decorators.path.which("openstack-config") def set_(filename, section, parameter, value): """ Set a value in an OpenStack configuration file. filename The full path to the configuration file section The section in which the parameter will be set parameter The parameter to change value The value to set CLI Example: .. code-block:: bash salt-call openstack_config.set /etc/keystone/keystone.conf sql connection foo """ filename = _quote(filename) section = _quote(section) parameter = _quote(parameter) value = _quote(str(value)) result = __salt__["cmd.run_all"]( "openstack-config --set {} {} {} {}".format( filename, section, parameter, value ), python_shell=False, ) if result["retcode"] == 0: return result["stdout"] else: raise salt.exceptions.CommandExecutionError(result["stderr"]) @salt.utils.decorators.path.which("openstack-config") def get(filename, section, parameter): """ Get a value from an OpenStack configuration file. filename The full path to the configuration file section The section from which to search for the parameter parameter The parameter to return CLI Example: .. code-block:: bash salt-call openstack_config.get /etc/keystone/keystone.conf sql connection """ filename = _quote(filename) section = _quote(section) parameter = _quote(parameter) result = __salt__["cmd.run_all"]( "openstack-config --get {} {} {}".format(filename, section, parameter), python_shell=False, ) if result["retcode"] == 0: return result["stdout"] else: raise salt.exceptions.CommandExecutionError(result["stderr"]) @salt.utils.decorators.path.which("openstack-config") def delete(filename, section, parameter): """ Delete a value from an OpenStack configuration file. filename The full path to the configuration file section The section from which to delete the parameter parameter The parameter to delete CLI Example: .. code-block:: bash salt-call openstack_config.delete /etc/keystone/keystone.conf sql connection """ filename = _quote(filename) section = _quote(section) parameter = _quote(parameter) result = __salt__["cmd.run_all"]( "openstack-config --del {} {} {}".format(filename, section, parameter), python_shell=False, ) if result["retcode"] == 0: return result["stdout"] else: raise salt.exceptions.CommandExecutionError(result["stderr"])
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/openstack_config.py
0.534127
0.193547
openstack_config.py
pypi
import logging import os import jinja2 import jinja2.exceptions import salt.utils.files import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net from salt.exceptions import CommandExecutionError # Set up logging log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, "suse_ip") ) ) # Define the module's virtual name __virtualname__ = "ip" # Default values for bonding _BOND_DEFAULTS = { # 803.ad aggregation selection logic # 0 for stable (default) # 1 for bandwidth # 2 for count "ad_select": "0", # Max number of transmit queues (default = 16) "tx_queues": "16", # lacp_rate 0: Slow - every 30 seconds # lacp_rate 1: Fast - every 1 second "lacp_rate": "0", # Max bonds for this driver "max_bonds": "1", # Used with miimon. # On: driver sends mii # Off: ethtool sends mii "use_carrier": "0", # Default. Don't change unless you know what you are doing. "xmit_hash_policy": "layer2", } _SUSE_NETWORK_SCRIPT_DIR = "/etc/sysconfig/network" _SUSE_NETWORK_FILE = "/etc/sysconfig/network/config" _SUSE_NETWORK_ROUTES_FILE = "/etc/sysconfig/network/routes" _CONFIG_TRUE = ("yes", "on", "true", "1", True) _CONFIG_FALSE = ("no", "off", "false", "0", False) _IFACE_TYPES = ( "eth", "bond", "alias", "clone", "ipsec", "dialup", "bridge", "slave", "vlan", "ipip", "ib", ) def __virtual__(): """ Confine this module to SUSE based distros """ if __grains__["os_family"] == "Suse": return __virtualname__ return ( False, "The suse_ip execution module cannot be loaded: " "this module is only available on SUSE based distributions.", ) def _error_msg_iface(iface, option, expected): """ Build an appropriate error message from a given option and a list of expected values. """ if isinstance(expected, str): expected = (expected,) msg = "Invalid option -- Interface: {}, Option: {}, Expected: [{}]" return msg.format(iface, option, "|".join(str(e) for e in expected)) def _error_msg_routes(iface, option, expected): """ Build an appropriate error message from a given option and a list of expected values. """ msg = "Invalid option -- Route interface: {}, Option: {}, Expected: [{}]" return msg.format(iface, option, expected) def _log_default_iface(iface, opt, value): log.info( "Using default option -- Interface: %s Option: %s Value: %s", iface, opt, value ) def _error_msg_network(option, expected): """ Build an appropriate error message from a given option and a list of expected values. """ if isinstance(expected, str): expected = (expected,) msg = "Invalid network setting -- Setting: {}, Expected: [{}]" return msg.format(option, "|".join(str(e) for e in expected)) def _log_default_network(opt, value): log.info("Using existing setting -- Setting: %s Value: %s", opt, value) def _parse_suse_config(path): suse_config = _read_file(path) cv_suse_config = {} if suse_config: for line in suse_config: line = line.strip() if not line or line.startswith("!") or line.startswith("#"): continue pair = [p.rstrip() for p in line.split("=", 1)] if len(pair) != 2: continue name, value = pair cv_suse_config[name.upper()] = salt.utils.stringutils.dequote(value) return cv_suse_config def _parse_ethtool_opts(opts, iface): """ Parses valid options for ETHTOOL_OPTIONS of the interface Logs the error and raises AttributeError in case of getting invalid options """ config = {} if "autoneg" in opts: if opts["autoneg"] in _CONFIG_TRUE: config.update({"autoneg": "on"}) elif opts["autoneg"] in _CONFIG_FALSE: config.update({"autoneg": "off"}) else: _raise_error_iface(iface, "autoneg", _CONFIG_TRUE + _CONFIG_FALSE) if "duplex" in opts: valid = ["full", "half"] if opts["duplex"] in valid: config.update({"duplex": opts["duplex"]}) else: _raise_error_iface(iface, "duplex", valid) if "speed" in opts: valid = ["10", "100", "1000", "10000"] if str(opts["speed"]) in valid: config.update({"speed": opts["speed"]}) else: _raise_error_iface(iface, opts["speed"], valid) if "advertise" in opts: valid = [ "0x001", "0x002", "0x004", "0x008", "0x010", "0x020", "0x20000", "0x8000", "0x1000", "0x40000", "0x80000", "0x200000", "0x400000", "0x800000", "0x1000000", "0x2000000", "0x4000000", ] if str(opts["advertise"]) in valid: config.update({"advertise": opts["advertise"]}) else: _raise_error_iface(iface, "advertise", valid) if "channels" in opts: channels_cmd = "-L {}".format(iface.strip()) channels_params = [] for option in ("rx", "tx", "other", "combined"): if option in opts["channels"]: valid = range(1, __grains__["num_cpus"] + 1) if opts["channels"][option] in valid: channels_params.append( "{} {}".format(option, opts["channels"][option]) ) else: _raise_error_iface(iface, opts["channels"][option], valid) if channels_params: config.update({channels_cmd: " ".join(channels_params)}) valid = _CONFIG_TRUE + _CONFIG_FALSE for option in ("rx", "tx", "sg", "tso", "ufo", "gso", "gro", "lro"): if option in opts: if opts[option] in _CONFIG_TRUE: config.update({option: "on"}) elif opts[option] in _CONFIG_FALSE: config.update({option: "off"}) else: _raise_error_iface(iface, option, valid) return config def _parse_settings_bond(opts, iface): """ Parses valid options for bonding interface Logs the error and raises AttributeError in case of getting invalid options """ if opts["mode"] in ("balance-rr", "0"): log.info("Device: %s Bonding Mode: load balancing (round-robin)", iface) return _parse_settings_bond_0(opts, iface) elif opts["mode"] in ("active-backup", "1"): log.info("Device: %s Bonding Mode: fault-tolerance (active-backup)", iface) return _parse_settings_bond_1(opts, iface) elif opts["mode"] in ("balance-xor", "2"): log.info("Device: %s Bonding Mode: load balancing (xor)", iface) return _parse_settings_bond_2(opts, iface) elif opts["mode"] in ("broadcast", "3"): log.info("Device: %s Bonding Mode: fault-tolerance (broadcast)", iface) return _parse_settings_bond_3(opts, iface) elif opts["mode"] in ("802.3ad", "4"): log.info( "Device: %s Bonding Mode: IEEE 802.3ad Dynamic link aggregation", iface ) return _parse_settings_bond_4(opts, iface) elif opts["mode"] in ("balance-tlb", "5"): log.info("Device: %s Bonding Mode: transmit load balancing", iface) return _parse_settings_bond_5(opts, iface) elif opts["mode"] in ("balance-alb", "6"): log.info("Device: %s Bonding Mode: adaptive load balancing", iface) return _parse_settings_bond_6(opts, iface) else: valid = ( "0", "1", "2", "3", "4", "5", "6", "balance-rr", "active-backup", "balance-xor", "broadcast", "802.3ad", "balance-tlb", "balance-alb", ) _raise_error_iface(iface, "mode", valid) def _parse_settings_miimon(opts, iface): """ Add shared settings for miimon support used by balance-rr, balance-xor bonding types. """ ret = {} for binding in ("miimon", "downdelay", "updelay"): if binding in opts: try: int(opts[binding]) ret.update({binding: opts[binding]}) except ValueError: _raise_error_iface(iface, binding, "integer") if "miimon" in opts and "downdelay" not in opts: ret["downdelay"] = ret["miimon"] * 2 if "miimon" in opts: if not opts["miimon"]: _raise_error_iface(iface, "miimon", "nonzero integer") for binding in ("downdelay", "updelay"): if binding in ret: if ret[binding] % ret["miimon"]: _raise_error_iface( iface, binding, "0 or a multiple of miimon ({})".format(ret["miimon"]), ) if "use_carrier" in opts: if opts["use_carrier"] in _CONFIG_TRUE: ret.update({"use_carrier": "1"}) elif opts["use_carrier"] in _CONFIG_FALSE: ret.update({"use_carrier": "0"}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, "use_carrier", valid) else: _log_default_iface(iface, "use_carrier", _BOND_DEFAULTS["use_carrier"]) ret.update({"use_carrier": _BOND_DEFAULTS["use_carrier"]}) return ret def _parse_settings_arp(opts, iface): """ Add shared settings for arp used by balance-rr, balance-xor bonding types. """ ret = {} if "arp_interval" in opts: try: int(opts["arp_interval"]) ret.update({"arp_interval": opts["arp_interval"]}) except ValueError: _raise_error_iface(iface, "arp_interval", "integer") # ARP targets in n.n.n.n form valid = "list of ips (up to 16)" if "arp_ip_target" in opts: if isinstance(opts["arp_ip_target"], list): if 1 <= len(opts["arp_ip_target"]) <= 16: ret.update({"arp_ip_target": ",".join(opts["arp_ip_target"])}) else: _raise_error_iface(iface, "arp_ip_target", valid) else: _raise_error_iface(iface, "arp_ip_target", valid) else: _raise_error_iface(iface, "arp_ip_target", valid) return ret def _parse_settings_bond_0(opts, iface): """ Parses valid options for balance-rr (type 0) bonding interface Logs the error and raises AttributeError in case of getting invalid options """ bond = {"mode": "0"} bond.update(_parse_settings_miimon(opts, iface)) bond.update(_parse_settings_arp(opts, iface)) if "miimon" not in opts and "arp_interval" not in opts: _raise_error_iface( iface, "miimon or arp_interval", "at least one of these is required" ) return bond def _parse_settings_bond_1(opts, iface): """ Parses valid options for active-backup (type 1) bonding interface Logs the error and raises AttributeError in case of getting invalid options """ bond = {"mode": "1"} bond.update(_parse_settings_miimon(opts, iface)) if "miimon" not in opts: _raise_error_iface(iface, "miimon", "integer") if "primary" in opts: bond.update({"primary": opts["primary"]}) return bond def _parse_settings_bond_2(opts, iface): """ Parses valid options for balance-xor (type 2) bonding interface Logs the error and raises AttributeError in case of getting invalid options """ bond = {"mode": "2"} bond.update(_parse_settings_miimon(opts, iface)) bond.update(_parse_settings_arp(opts, iface)) if "miimon" not in opts and "arp_interval" not in opts: _raise_error_iface( iface, "miimon or arp_interval", "at least one of these is required" ) if "hashing-algorithm" in opts: valid = ("layer2", "layer2+3", "layer3+4") if opts["hashing-algorithm"] in valid: bond.update({"xmit_hash_policy": opts["hashing-algorithm"]}) else: _raise_error_iface(iface, "hashing-algorithm", valid) return bond def _parse_settings_bond_3(opts, iface): """ Parses valid options for broadcast (type 3) bonding interface Logs the error and raises AttributeError in case of getting invalid options """ bond = {"mode": "3"} bond.update(_parse_settings_miimon(opts, iface)) if "miimon" not in opts: _raise_error_iface(iface, "miimon", "integer") return bond def _parse_settings_bond_4(opts, iface): """ Parses valid options for 802.3ad (type 4) bonding interface Logs the error and raises AttributeError in case of getting invalid options """ bond = {"mode": "4"} bond.update(_parse_settings_miimon(opts, iface)) if "miimon" not in opts: _raise_error_iface(iface, "miimon", "integer") for binding in ("lacp_rate", "ad_select"): if binding in opts: if binding == "lacp_rate": valid = ("fast", "1", "slow", "0") if opts[binding] not in valid: _raise_error_iface(iface, binding, valid) if opts[binding] == "fast": opts.update({binding: "1"}) if opts[binding] == "slow": opts.update({binding: "0"}) else: valid = "integer" try: int(opts[binding]) bond.update({binding: opts[binding]}) except ValueError: _raise_error_iface(iface, binding, valid) else: _log_default_iface(iface, binding, _BOND_DEFAULTS[binding]) bond.update({binding: _BOND_DEFAULTS[binding]}) if "hashing-algorithm" in opts: valid = ("layer2", "layer2+3", "layer3+4") if opts["hashing-algorithm"] in valid: bond.update({"xmit_hash_policy": opts["hashing-algorithm"]}) else: _raise_error_iface(iface, "hashing-algorithm", valid) return bond def _parse_settings_bond_5(opts, iface): """ Parses valid options for balance-tlb (type 5) bonding interface Logs the error and raises AttributeError in case of getting invalid options """ bond = {"mode": "5"} bond.update(_parse_settings_miimon(opts, iface)) if "miimon" not in opts: _raise_error_iface(iface, "miimon", "integer") if "primary" in opts: bond.update({"primary": opts["primary"]}) return bond def _parse_settings_bond_6(opts, iface): """ Parses valid options for balance-alb (type 6) bonding interface Logs the error and raises AttributeError in case of getting invalid options """ bond = {"mode": "6"} bond.update(_parse_settings_miimon(opts, iface)) if "miimon" not in opts: _raise_error_iface(iface, "miimon", "integer") if "primary" in opts: bond.update({"primary": opts["primary"]}) return bond def _parse_settings_vlan(opts, iface): """ Filters given options and outputs valid settings for a vlan """ vlan = {} if "reorder_hdr" in opts: if opts["reorder_hdr"] in _CONFIG_TRUE + _CONFIG_FALSE: vlan.update({"reorder_hdr": opts["reorder_hdr"]}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, "reorder_hdr", valid) if "vlan_id" in opts: if opts["vlan_id"] > 0: vlan.update({"vlan_id": opts["vlan_id"]}) else: _raise_error_iface(iface, "vlan_id", "Positive integer") if "phys_dev" in opts: if len(opts["phys_dev"]) > 0: vlan.update({"phys_dev": opts["phys_dev"]}) else: _raise_error_iface(iface, "phys_dev", "Non-empty string") return vlan def _parse_settings_eth(opts, iface_type, enabled, iface): """ Filters given options and outputs valid settings for a network interface. """ result = {"name": iface} if "proto" in opts: valid = [ "static", "dhcp", "dhcp4", "dhcp6", "autoip", "dhcp+autoip", "auto6", "6to4", "none", ] if opts["proto"] in valid: result["proto"] = opts["proto"] else: _raise_error_iface(iface, opts["proto"], valid) if "mtu" in opts: try: result["mtu"] = int(opts["mtu"]) except ValueError: _raise_error_iface(iface, "mtu", ["integer"]) if "hwaddr" in opts and "macaddr" in opts: msg = "Cannot pass both hwaddr and macaddr. Must use either hwaddr or macaddr" log.error(msg) raise AttributeError(msg) if iface_type not in ("bridge",): ethtool = _parse_ethtool_opts(opts, iface) if ethtool: result["ethtool"] = " ".join( ["{} {}".format(x, y) for x, y in ethtool.items()] ) if iface_type == "slave": result["proto"] = "none" if iface_type == "bond": if "mode" not in opts: msg = "Missing required option 'mode'" log.error("%s for bond interface '%s'", msg, iface) raise AttributeError(msg) bonding = _parse_settings_bond(opts, iface) if bonding: result["bonding"] = " ".join( ["{}={}".format(x, y) for x, y in bonding.items()] ) result["devtype"] = "Bond" if "slaves" in opts: if isinstance(opts["slaves"], list): result["slaves"] = opts["slaves"] else: result["slaves"] = opts["slaves"].split() if iface_type == "vlan": vlan = _parse_settings_vlan(opts, iface) if vlan: result["devtype"] = "Vlan" for opt in vlan: result[opt] = opts[opt] if iface_type == "eth": result["devtype"] = "Ethernet" if iface_type == "bridge": result["devtype"] = "Bridge" bypassfirewall = True valid = _CONFIG_TRUE + _CONFIG_FALSE for opt in ("bypassfirewall",): if opt in opts: if opts[opt] in _CONFIG_TRUE: bypassfirewall = True elif opts[opt] in _CONFIG_FALSE: bypassfirewall = False else: _raise_error_iface(iface, opts[opt], valid) bridgectls = [ "net.bridge.bridge-nf-call-ip6tables", "net.bridge.bridge-nf-call-iptables", "net.bridge.bridge-nf-call-arptables", ] if bypassfirewall: sysctl_value = 0 else: sysctl_value = 1 for sysctl in bridgectls: try: __salt__["sysctl.persist"](sysctl, sysctl_value) except CommandExecutionError: log.warning("Failed to set sysctl: %s", sysctl) else: if "bridge" in opts: result["bridge"] = opts["bridge"] if iface_type == "ipip": result["devtype"] = "IPIP" for opt in ("my_inner_ipaddr", "my_outer_ipaddr"): if opt not in opts: _raise_error_iface(iface, opt, "1.2.3.4") else: result[opt] = opts[opt] if iface_type == "ib": result["devtype"] = "InfiniBand" if "prefix" in opts: if "netmask" in opts: msg = "Cannot use prefix and netmask together" log.error(msg) raise AttributeError(msg) result["prefix"] = opts["prefix"] elif "netmask" in opts: result["netmask"] = opts["netmask"] for opt in ( "ipaddr", "master", "srcaddr", "delay", "domain", "gateway", "uuid", "nickname", "zone", ): if opt in opts: result[opt] = opts[opt] if "ipaddrs" in opts or "ipv6addr" in opts or "ipv6addrs" in opts: result["ipaddrs"] = [] if "ipaddrs" in opts: for opt in opts["ipaddrs"]: if salt.utils.validate.net.ipv4_addr( opt ) or salt.utils.validate.net.ipv6_addr(opt): result["ipaddrs"].append(opt) else: msg = "{} is invalid ipv4 or ipv6 CIDR".format(opt) log.error(msg) raise AttributeError(msg) if "ipv6addr" in opts: if salt.utils.validate.net.ipv6_addr(opts["ipv6addr"]): result["ipaddrs"].append(opts["ipv6addr"]) else: msg = "{} is invalid ipv6 CIDR".format(opt) log.error(msg) raise AttributeError(msg) if "ipv6addrs" in opts: for opt in opts["ipv6addrs"]: if salt.utils.validate.net.ipv6_addr(opt): result["ipaddrs"].append(opt) else: msg = "{} is invalid ipv6 CIDR".format(opt) log.error(msg) raise AttributeError(msg) if "enable_ipv6" in opts: result["enable_ipv6"] = opts["enable_ipv6"] valid = _CONFIG_TRUE + _CONFIG_FALSE for opt in ( "onparent", "peerdns", "peerroutes", "slave", "vlan", "defroute", "stp", "ipv6_peerdns", "ipv6_defroute", "ipv6_peerroutes", "ipv6_autoconf", "ipv4_failure_fatal", "dhcpv6c", ): if opt in opts: if opts[opt] in _CONFIG_TRUE: result[opt] = "yes" elif opts[opt] in _CONFIG_FALSE: result[opt] = "no" else: _raise_error_iface(iface, opts[opt], valid) if "onboot" in opts: log.warning( "The 'onboot' option is controlled by the 'enabled' option. " "Interface: %s Enabled: %s", iface, enabled, ) if "startmode" in opts: valid = ("manual", "auto", "nfsroot", "hotplug", "off") if opts["startmode"] in valid: result["startmode"] = opts["startmode"] else: _raise_error_iface(iface, opts["startmode"], valid) else: if enabled: result["startmode"] = "auto" else: result["startmode"] = "off" # This vlan is in opts, and should be only used in range interface # will affect jinja template for interface generating if "vlan" in opts: if opts["vlan"] in _CONFIG_TRUE: result["vlan"] = "yes" elif opts["vlan"] in _CONFIG_FALSE: result["vlan"] = "no" else: _raise_error_iface(iface, opts["vlan"], valid) if "arpcheck" in opts: if opts["arpcheck"] in _CONFIG_FALSE: result["arpcheck"] = "no" if "ipaddr_start" in opts: result["ipaddr_start"] = opts["ipaddr_start"] if "ipaddr_end" in opts: result["ipaddr_end"] = opts["ipaddr_end"] if "clonenum_start" in opts: result["clonenum_start"] = opts["clonenum_start"] if "hwaddr" in opts: result["hwaddr"] = opts["hwaddr"] if "macaddr" in opts: result["macaddr"] = opts["macaddr"] # If NetworkManager is available, we can control whether we use # it or not if "nm_controlled" in opts: if opts["nm_controlled"] in _CONFIG_TRUE: result["nm_controlled"] = "yes" elif opts["nm_controlled"] in _CONFIG_FALSE: result["nm_controlled"] = "no" else: _raise_error_iface(iface, opts["nm_controlled"], valid) else: result["nm_controlled"] = "no" return result def _parse_routes(iface, opts): """ Filters given options and outputs valid settings for the route settings file. """ # Normalize keys opts = {k.lower(): v for (k, v) in opts.items()} result = {} if "routes" not in opts: _raise_error_routes(iface, "routes", "List of routes") for opt in opts: result[opt] = opts[opt] return result def _parse_network_settings(opts, current): """ Filters given options and outputs valid settings for the global network settings file. """ # Normalize keys opts = {k.lower(): v for (k, v) in opts.items()} current = {k.lower(): v for (k, v) in current.items()} # Check for supported parameters retain_settings = opts.get("retain_settings", False) result = {} if retain_settings: for opt in current: nopt = opt if opt == "netconfig_dns_static_servers": nopt = "dns" result[nopt] = current[opt].split() elif opt == "netconfig_dns_static_searchlist": nopt = "dns_search" result[nopt] = current[opt].split() elif opt.startswith("netconfig_") and opt not in ( "netconfig_modules_order", "netconfig_verbose", "netconfig_force_replace", ): nopt = opt[10:] result[nopt] = current[opt] else: result[nopt] = current[opt] _log_default_network(nopt, current[opt]) for opt in opts: if opt in ("dns", "dns_search") and not isinstance(opts[opt], list): result[opt] = opts[opt].split() else: result[opt] = opts[opt] return result def _raise_error_iface(iface, option, expected): """ Log and raise an error with a logical formatted message. """ msg = _error_msg_iface(iface, option, expected) log.error(msg) raise AttributeError(msg) def _raise_error_network(option, expected): """ Log and raise an error with a logical formatted message. """ msg = _error_msg_network(option, expected) log.error(msg) raise AttributeError(msg) def _raise_error_routes(iface, option, expected): """ Log and raise an error with a logical formatted message. """ msg = _error_msg_routes(iface, option, expected) log.error(msg) raise AttributeError(msg) def _read_file(path): """ Reads and returns the contents of a file """ try: with salt.utils.files.fopen(path, "rb") as rfh: return _get_non_blank_lines(salt.utils.stringutils.to_unicode(rfh.read())) except OSError: return [] # Return empty list for type consistency def _write_file_iface(iface, data, folder, pattern): """ Writes a file to disk """ filename = os.path.join(folder, pattern.format(iface)) if not os.path.exists(folder): msg = "{} cannot be written. {} does not exist".format(filename, folder) log.error(msg) raise AttributeError(msg) with salt.utils.files.fopen(filename, "w") as fp_: fp_.write(salt.utils.stringutils.to_str(data)) def _write_file_network(data, filename): """ Writes a file to disk """ with salt.utils.files.fopen(filename, "w") as fp_: fp_.write(salt.utils.stringutils.to_str(data)) def _get_non_blank_lines(data): lines = data.splitlines() try: # Discard newlines if they exist lines.remove("") except ValueError: pass return lines def build_interface(iface, iface_type, enabled, **settings): """ Build an interface script for a network interface. Args: :param iface: The name of the interface to build the configuration for :param iface_type: The type of the interface. The following types are possible: - eth - bond - alias - clone - ipsec - dialup - bridge - slave - vlan - ipip - ib :param enabled: Build the interface enabled or disabled :param settings: The settings for the interface Returns: dict: A dictionary of file/content CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> """ iface_type = iface_type.lower() if iface_type not in _IFACE_TYPES: _raise_error_iface(iface, iface_type, _IFACE_TYPES) if iface_type == "slave": settings["slave"] = "yes" if "master" not in settings: msg = "master is a required setting for slave interfaces" log.error(msg) raise AttributeError(msg) if iface_type == "bond": if "mode" not in settings: msg = "mode is required for bond interfaces" log.error(msg) raise AttributeError(msg) settings["mode"] = str(settings["mode"]) if iface_type == "vlan": settings["vlan"] = "yes" if iface_type == "bridge" and not __salt__["pkg.version"]("bridge-utils"): __salt__["pkg.install"]("bridge-utils") if iface_type in ( "eth", "bond", "bridge", "slave", "vlan", "ipip", "ib", "alias", ): opts = _parse_settings_eth(settings, iface_type, enabled, iface) try: template = JINJA.get_template("ifcfg.jinja") except jinja2.exceptions.TemplateNotFound: log.error("Could not load template ifcfg.jinja") return "" log.debug("Interface opts:\n%s", opts) ifcfg = template.render(opts) if settings.get("test"): return _get_non_blank_lines(ifcfg) _write_file_iface(iface, ifcfg, _SUSE_NETWORK_SCRIPT_DIR, "ifcfg-{}") path = os.path.join(_SUSE_NETWORK_SCRIPT_DIR, "ifcfg-{}".format(iface)) return _read_file(path) def build_routes(iface, **settings): """ Build a route script for a network interface. Args: :param iface: The name of the interface to build the routes for :param settings: The settings for the routes Returns: dict: A dictionary of file/content CLI Example: .. code-block:: bash salt '*' ip.build_routes eth0 <settings> """ template = "ifroute.jinja" log.debug("Template name: %s", template) opts = _parse_routes(iface, settings) log.debug("Opts:\n%s", opts) try: template = JINJA.get_template(template) except jinja2.exceptions.TemplateNotFound: log.error("Could not load template %s", template) return "" log.debug("IP routes:\n%s", opts["routes"]) if iface == "routes": routecfg = template.render(routes=opts["routes"]) else: routecfg = template.render(routes=opts["routes"], iface=iface) if settings["test"]: return _get_non_blank_lines(routecfg) if iface == "routes": path = _SUSE_NETWORK_ROUTES_FILE else: path = os.path.join(_SUSE_NETWORK_SCRIPT_DIR, "ifroute-{}".format(iface)) _write_file_network(routecfg, path) return _read_file(path) def down(iface, iface_type=None): """ Shutdown a network interface Args: :param iface: The name of the interface to shutdown :param iface_type: The type of the interface If ``slave`` is specified, no any action is performing Default is ``None`` Returns: str: The result of ``ifdown`` command or ``None`` if ``slave`` iface_type was specified CLI Example: .. code-block:: bash salt '*' ip.down eth0 """ # Slave devices are controlled by the master. if not iface_type or iface_type.lower() != "slave": return __salt__["cmd.run"]("ifdown {}".format(iface)) return None def get_interface(iface): """ Return the contents of an interface script Args: :param iface: The name of the interface to get settings for Returns: dict: A dictionary of file/content CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 """ path = os.path.join(_SUSE_NETWORK_SCRIPT_DIR, "ifcfg-{}".format(iface)) return _read_file(path) def up(iface, iface_type=None): """ Start up a network interface Args: :param iface: The name of the interface to start up :param iface_type: The type of the interface If ``slave`` is specified, no any action is performing Default is ``None`` Returns: str: The result of ``ifup`` command or ``None`` if ``slave`` iface_type was specified CLI Example: .. code-block:: bash salt '*' ip.up eth0 """ # Slave devices are controlled by the master. if not iface_type or iface_type.lower() != "slave": return __salt__["cmd.run"]("ifup {}".format(iface)) return None def get_routes(iface): """ Return the contents of the interface routes script. Args: :param iface: The name of the interface to get the routes for Returns: dict: A dictionary of file/content CLI Example: .. code-block:: bash salt '*' ip.get_routes eth0 """ if iface == "routes": path = _SUSE_NETWORK_ROUTES_FILE else: path = os.path.join(_SUSE_NETWORK_SCRIPT_DIR, "ifroute-{}".format(iface)) return _read_file(path) def get_network_settings(): """ Return the contents of the global network script. Args: :param iface: The name of the interface to start up :param iface_type: The type of the interface If ``slave`` is specified, no any action is performing Default is ``None`` Returns: dict: A dictionary of file/content CLI Example: .. code-block:: bash salt '*' ip.get_network_settings """ return _read_file(_SUSE_NETWORK_FILE) def apply_network_settings(**settings): """ Apply global network configuration. Args: :param settings: The network settings to apply Returns: The result of ``service.reload`` for ``network`` service CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings """ if "require_reboot" not in settings: settings["require_reboot"] = False if "apply_hostname" not in settings: settings["apply_hostname"] = False hostname_res = True if settings["apply_hostname"] in _CONFIG_TRUE: if "hostname" in settings: hostname_res = __salt__["network.mod_hostname"](settings["hostname"]) else: log.warning( "The network state sls is trying to apply hostname " "changes but no hostname is defined." ) hostname_res = False res = True if settings["require_reboot"] in _CONFIG_TRUE: log.warning( "The network state sls is requiring a reboot of the system to " "properly apply network configuration." ) res = True else: res = __salt__["service.reload"]("network") return hostname_res and res def build_network_settings(**settings): """ Build the global network script. Args: :param settings: The network settings Returns: dict: A dictionary of file/content CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> """ # Read current configuration and store default values current_network_settings = _parse_suse_config(_SUSE_NETWORK_FILE) # Build settings opts = _parse_network_settings(settings, current_network_settings) try: template = JINJA.get_template("network.jinja") except jinja2.exceptions.TemplateNotFound: log.error("Could not load template network.jinja") return "" network = template.render(opts) if settings["test"]: return _get_non_blank_lines(network) # Write settings _write_file_network(network, _SUSE_NETWORK_FILE) __salt__["cmd.run"]("netconfig update -f") return _read_file(_SUSE_NETWORK_FILE)
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/suse_ip.py
0.449634
0.212579
suse_ip.py
pypi
import logging import re import salt.utils.network import salt.utils.path log = logging.getLogger(__name__) __virtualname__ = "dig" def __virtual__(): """ Only load module if dig binary is present """ if salt.utils.path.which("dig"): return __virtualname__ return ( False, "The dig execution module cannot be loaded: the dig binary is not in the path.", ) def check_ip(addr): """ Check if address is a valid IP. returns True if valid, otherwise False. CLI Example: .. code-block:: bash salt ns1 dig.check_ip 127.0.0.1 salt ns1 dig.check_ip 1111:2222:3333:4444:5555:6666:7777:8888 """ try: addr = addr.rsplit("/", 1) except AttributeError: # Non-string passed return False if salt.utils.network.is_ipv4(addr[0]): try: if 1 <= int(addr[1]) <= 32: return True except ValueError: # Non-int subnet notation return False except IndexError: # No subnet notation used (i.e. just an IPv4 address) return True if salt.utils.network.is_ipv6(addr[0]): try: if 8 <= int(addr[1]) <= 128: return True except ValueError: # Non-int subnet notation return False except IndexError: # No subnet notation used (i.e. just an IPv4 address) return True return False def A(host, nameserver=None): """ Return the A record for ``host``. Always returns a list. CLI Example: .. code-block:: bash salt ns1 dig.A www.google.com """ dig = ["dig", "+short", str(host), "A"] if nameserver is not None: dig.append("@{}".format(nameserver)) cmd = __salt__["cmd.run_all"](dig, python_shell=False) # In this case, 0 is not the same as False if cmd["retcode"] != 0: log.warning( "dig returned exit code '%s'. Returning empty list as fallback.", cmd["retcode"], ) return [] # make sure all entries are IPs return [x for x in cmd["stdout"].split("\n") if check_ip(x)] def AAAA(host, nameserver=None): """ Return the AAAA record for ``host``. Always returns a list. CLI Example: .. code-block:: bash salt ns1 dig.AAAA www.google.com """ dig = ["dig", "+short", str(host), "AAAA"] if nameserver is not None: dig.append("@{}".format(nameserver)) cmd = __salt__["cmd.run_all"](dig, python_shell=False) # In this case, 0 is not the same as False if cmd["retcode"] != 0: log.warning( "dig returned exit code '%s'. Returning empty list as fallback.", cmd["retcode"], ) return [] # make sure all entries are IPs return [x for x in cmd["stdout"].split("\n") if check_ip(x)] def CNAME(host, nameserver=None): """ Return the CNAME record for ``host``. .. versionadded:: 3005 CLI Example: .. code-block:: bash salt ns1 dig.CNAME mail.google.com """ dig = ["dig", "+short", str(host), "CNAME"] if nameserver is not None: dig.append("@{}".format(nameserver)) cmd = __salt__["cmd.run_all"](dig, python_shell=False) # In this case, 0 is not the same as False if cmd["retcode"] != 0: log.warning( "dig returned exit code '%s'.", cmd["retcode"], ) return [] return cmd["stdout"] def NS(domain, resolve=True, nameserver=None): """ Return a list of IPs of the nameservers for ``domain`` If ``resolve`` is False, don't resolve names. CLI Example: .. code-block:: bash salt ns1 dig.NS google.com """ dig = ["dig", "+short", str(domain), "NS"] if nameserver is not None: dig.append("@{}".format(nameserver)) cmd = __salt__["cmd.run_all"](dig, python_shell=False) # In this case, 0 is not the same as False if cmd["retcode"] != 0: log.warning( "dig returned exit code '%s'. Returning empty list as fallback.", cmd["retcode"], ) return [] if resolve: ret = [] for ns_host in cmd["stdout"].split("\n"): for ip_addr in A(ns_host, nameserver): ret.append(ip_addr) return ret return cmd["stdout"].split("\n") def SPF(domain, record="SPF", nameserver=None): """ Return the allowed IPv4 ranges in the SPF record for ``domain``. If record is ``SPF`` and the SPF record is empty, the TXT record will be searched automatically. If you know the domain uses TXT and not SPF, specifying that will save a lookup. CLI Example: .. code-block:: bash salt ns1 dig.SPF google.com """ spf_re = re.compile(r"(?:\+|~)?(ip[46]|include):(.+)") cmd = ["dig", "+short", str(domain), record] if nameserver is not None: cmd.append("@{}".format(nameserver)) result = __salt__["cmd.run_all"](cmd, python_shell=False) # In this case, 0 is not the same as False if result["retcode"] != 0: log.warning( "dig returned exit code '%s'. Returning empty list as fallback.", result["retcode"], ) return [] if result["stdout"] == "" and record == "SPF": # empty string is successful query, but nothing to return. So, try TXT # record. return SPF(domain, "TXT", nameserver) sections = re.sub('"', "", result["stdout"]).split() if not sections or sections[0] != "v=spf1": return [] if sections[1].startswith("redirect="): # Run a lookup on the part after 'redirect=' (9 chars) return SPF(sections[1][9:], "SPF", nameserver) ret = [] for section in sections[1:]: try: mechanism, address = spf_re.match(section).groups() except AttributeError: # Regex was not matched continue if mechanism == "include": ret.extend(SPF(address, "SPF", nameserver)) elif mechanism in ("ip4", "ip6") and check_ip(address): ret.append(address) return ret def MX(domain, resolve=False, nameserver=None): """ Return a list of lists for the MX of ``domain``. If the ``resolve`` argument is True, resolve IPs for the servers. It's limited to one IP, because although in practice it's very rarely a round robin, it is an acceptable configuration and pulling just one IP lets the data be similar to the non-resolved version. If you think an MX has multiple IPs, don't use the resolver here, resolve them in a separate step. CLI Example: .. code-block:: bash salt ns1 dig.MX google.com """ dig = ["dig", "+short", str(domain), "MX"] if nameserver is not None: dig.append("@{}".format(nameserver)) cmd = __salt__["cmd.run_all"](dig, python_shell=False) # In this case, 0 is not the same as False if cmd["retcode"] != 0: log.warning( "dig returned exit code '%s'. Returning empty list as fallback.", cmd["retcode"], ) return [] stdout = [x.split() for x in cmd["stdout"].split("\n")] if resolve: return [(lambda x: [x[0], A(x[1], nameserver)[0]])(x) for x in stdout] return stdout def TXT(host, nameserver=None): """ Return the TXT record for ``host``. Always returns a list. CLI Example: .. code-block:: bash salt ns1 dig.TXT google.com """ dig = ["dig", "+short", str(host), "TXT"] if nameserver is not None: dig.append("@{}".format(nameserver)) cmd = __salt__["cmd.run_all"](dig, python_shell=False) if cmd["retcode"] != 0: log.warning( "dig returned exit code '%s'. Returning empty list as fallback.", cmd["retcode"], ) return [] return [i for i in cmd["stdout"].split("\n")] # Let lowercase work, since that is the convention for Salt functions a = A aaaa = AAAA cname = CNAME ns = NS spf = SPF mx = MX
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/dig.py
0.64131
0.228081
dig.py
pypi
import logging import re import shlex import salt.utils.platform try: import pipes HAS_DEPS = True except ImportError: HAS_DEPS = False if hasattr(shlex, "quote"): _quote = shlex.quote elif HAS_DEPS and hasattr(pipes, "quote"): _quote = pipes.quote else: _quote = None log = logging.getLogger(__name__) __virtualname__ = "keychain" def __virtual__(): """ Only work on Mac OS """ if salt.utils.platform.is_darwin() and _quote is not None: return __virtualname__ return (False, "Only available on Mac OS systems with pipes") def install( cert, password, keychain="/Library/Keychains/System.keychain", allow_any=False, keychain_password=None, ): """ Install a certificate cert The certificate to install password The password for the certificate being installed formatted in the way described for openssl command in the PASS PHRASE ARGUMENTS section. Note: The password given here will show up as plaintext in the job returned info. keychain The keychain to install the certificate to, this defaults to /Library/Keychains/System.keychain allow_any Allow any application to access the imported certificate without warning keychain_password If your keychain is likely to be locked pass the password and it will be unlocked before running the import Note: The password given here will show up as plaintext in the returned job info. CLI Example: .. code-block:: bash salt '*' keychain.install test.p12 test123 """ if keychain_password is not None: unlock_keychain(keychain, keychain_password) cmd = "security import {} -P {} -k {}".format(cert, password, keychain) if allow_any: cmd += " -A" return __salt__["cmd.run"](cmd) def uninstall( cert_name, keychain="/Library/Keychains/System.keychain", keychain_password=None ): """ Uninstall a certificate from a keychain cert_name The name of the certificate to remove keychain The keychain to install the certificate to, this defaults to /Library/Keychains/System.keychain keychain_password If your keychain is likely to be locked pass the password and it will be unlocked before running the import Note: The password given here will show up as plaintext in the returned job info. CLI Example: .. code-block:: bash salt '*' keychain.install test.p12 test123 """ if keychain_password is not None: unlock_keychain(keychain, keychain_password) cmd = 'security delete-certificate -c "{}" {}'.format(cert_name, keychain) return __salt__["cmd.run"](cmd) def list_certs(keychain="/Library/Keychains/System.keychain"): """ List all of the installed certificates keychain The keychain to install the certificate to, this defaults to /Library/Keychains/System.keychain CLI Example: .. code-block:: bash salt '*' keychain.list_certs """ cmd = ( 'security find-certificate -a {} | grep -o "alis".*\\" | ' "grep -o '\\\"[-A-Za-z0-9.:() ]*\\\"'".format(_quote(keychain)) ) out = __salt__["cmd.run"](cmd, python_shell=True) return out.replace('"', "").split("\n") def get_friendly_name(cert, password): """ Get the friendly name of the given certificate cert The certificate to install password The password for the certificate being installed formatted in the way described for openssl command in the PASS PHRASE ARGUMENTS section Note: The password given here will show up as plaintext in the returned job info. CLI Example: .. code-block:: bash salt '*' keychain.get_friendly_name /tmp/test.p12 test123 """ cmd = ( "openssl pkcs12 -in {} -passin pass:{} -info -nodes -nokeys 2> /dev/null | " "grep friendlyName:".format(_quote(cert), _quote(password)) ) out = __salt__["cmd.run"](cmd, python_shell=True) return out.replace("friendlyName: ", "").strip() def get_default_keychain(user=None, domain="user"): """ Get the default keychain user The user to check the default keychain of domain The domain to use valid values are user|system|common|dynamic, the default is user CLI Example: .. code-block:: bash salt '*' keychain.get_default_keychain """ cmd = "security default-keychain -d {}".format(domain) return __salt__["cmd.run"](cmd, runas=user) def set_default_keychain(keychain, domain="user", user=None): """ Set the default keychain keychain The location of the keychain to set as default domain The domain to use valid values are user|system|common|dynamic, the default is user user The user to set the default keychain as CLI Example: .. code-block:: bash salt '*' keychain.set_keychain /Users/fred/Library/Keychains/login.keychain """ cmd = "security default-keychain -d {} -s {}".format(domain, keychain) return __salt__["cmd.run"](cmd, runas=user) def unlock_keychain(keychain, password): """ Unlock the given keychain with the password keychain The keychain to unlock password The password to use to unlock the keychain. Note: The password given here will show up as plaintext in the returned job info. CLI Example: .. code-block:: bash salt '*' keychain.unlock_keychain /tmp/test.p12 test123 """ cmd = "security unlock-keychain -p {} {}".format(password, keychain) __salt__["cmd.run"](cmd) def get_hash(name, password=None): """ Returns the hash of a certificate in the keychain. name The name of the certificate (which you can get from keychain.get_friendly_name) or the location of a p12 file. password The password that is used in the certificate. Only required if your passing a p12 file. Note: This will be outputted to logs CLI Example: .. code-block:: bash salt '*' keychain.get_hash /tmp/test.p12 test123 """ if ".p12" in name[-4:]: cmd = "openssl pkcs12 -in {0} -passin pass:{1} -passout pass:{1}".format( name, password ) else: cmd = 'security find-certificate -c "{}" -m -p'.format(name) out = __salt__["cmd.run"](cmd) matches = re.search( "-----BEGIN CERTIFICATE-----(.*)-----END CERTIFICATE-----", out, re.DOTALL | re.MULTILINE, ) if matches: return matches.group(1) else: return False
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/mac_keychain.py
0.58439
0.206454
mac_keychain.py
pypi
import salt.utils.data import salt.utils.files def __virtual__(): """ Only work on Gentoo """ if __grains__["os"] == "Gentoo": return "makeconf" return ( False, "The makeconf execution module cannot be loaded: only available on Gentoo" " systems.", ) def _get_makeconf(): """ Find the correct make.conf. Gentoo recently moved the make.conf but still supports the old location, using the old location first """ old_conf = "/etc/make.conf" new_conf = "/etc/portage/make.conf" if __salt__["file.file_exists"](old_conf): return old_conf elif __salt__["file.file_exists"](new_conf): return new_conf def _add_var(var, value): """ Add a new var to the make.conf. If using layman, the source line for the layman make.conf needs to be at the very end of the config. This ensures that the new var will be above the source line. """ makeconf = _get_makeconf() layman = "source /var/lib/layman/make.conf" fullvar = '{}="{}"'.format(var, value) if __salt__["file.contains"](makeconf, layman): # TODO perhaps make this a function in the file module? cmd = [ "sed", "-i", r"/{}/ i\{}".format(layman.replace("/", "\\/"), fullvar), makeconf, ] __salt__["cmd.run"](cmd) else: __salt__["file.append"](makeconf, fullvar) def set_var(var, value): """ Set a variable in the make.conf Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.set_var 'LINGUAS' 'en' """ makeconf = _get_makeconf() old_value = get_var(var) # If var already in file, replace its value if old_value is not None: __salt__["file.sed"]( makeconf, "^{}=.*".format(var), '{}="{}"'.format(var, value) ) else: _add_var(var, value) new_value = get_var(var) return {var: {"old": old_value, "new": new_value}} def remove_var(var): """ Remove a variable from the make.conf Return a dict containing the new value for the variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.remove_var 'LINGUAS' """ makeconf = _get_makeconf() old_value = get_var(var) # If var is in file if old_value is not None: __salt__["file.sed"](makeconf, "^{}=.*".format(var), "") new_value = get_var(var) return {var: {"old": old_value, "new": new_value}} def append_var(var, value): """ Add to or create a new variable in the make.conf Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.append_var 'LINGUAS' 'en' """ makeconf = _get_makeconf() old_value = get_var(var) # If var already in file, add to its value if old_value is not None: appended_value = "{} {}".format(old_value, value) __salt__["file.sed"]( makeconf, "^{}=.*".format(var), '{}="{}"'.format(var, appended_value) ) else: _add_var(var, value) new_value = get_var(var) return {var: {"old": old_value, "new": new_value}} def trim_var(var, value): """ Remove a value from a variable in the make.conf Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.trim_var 'LINGUAS' 'en' """ makeconf = _get_makeconf() old_value = get_var(var) # If var in file, trim value from its value if old_value is not None: __salt__["file.sed"](makeconf, value, "", limit=var) new_value = get_var(var) return {var: {"old": old_value, "new": new_value}} def get_var(var): """ Get the value of a variable in make.conf Return the value of the variable or None if the variable is not in make.conf CLI Example: .. code-block:: bash salt '*' makeconf.get_var 'LINGUAS' """ makeconf = _get_makeconf() # Open makeconf with salt.utils.files.fopen(makeconf) as fn_: conf_file = salt.utils.data.decode(fn_.readlines()) for line in conf_file: if line.startswith(var): ret = line.split("=", 1)[1] if '"' in ret: ret = ret.split('"')[1] elif "#" in ret: ret = ret.split("#")[0] ret = ret.strip() return ret return None def var_contains(var, value): """ Verify if variable contains a value in make.conf Return True if value is set for var CLI Example: .. code-block:: bash salt '*' makeconf.var_contains 'LINGUAS' 'en' """ setval = get_var(var) # Remove any escaping that was needed to past through salt value = value.replace("\\", "") if setval is None: return False return value in setval.split() def set_cflags(value): """ Set the CFLAGS variable Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.set_cflags '-march=native -O2 -pipe' """ return set_var("CFLAGS", value) def get_cflags(): """ Get the value of CFLAGS variable in the make.conf Return the value of the variable or None if the variable is not in the make.conf CLI Example: .. code-block:: bash salt '*' makeconf.get_cflags """ return get_var("CFLAGS") def append_cflags(value): """ Add to or create a new CFLAGS in the make.conf Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.append_cflags '-pipe' """ return append_var("CFLAGS", value) def trim_cflags(value): """ Remove a value from CFLAGS variable in the make.conf Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.trim_cflags '-pipe' """ return trim_var("CFLAGS", value) def cflags_contains(value): """ Verify if CFLAGS variable contains a value in make.conf Return True if value is set for var CLI Example: .. code-block:: bash salt '*' makeconf.cflags_contains '-pipe' """ return var_contains("CFLAGS", value) def set_cxxflags(value): """ Set the CXXFLAGS variable Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.set_cxxflags '-march=native -O2 -pipe' """ return set_var("CXXFLAGS", value) def get_cxxflags(): """ Get the value of CXXFLAGS variable in the make.conf Return the value of the variable or None if the variable is not in the make.conf CLI Example: .. code-block:: bash salt '*' makeconf.get_cxxflags """ return get_var("CXXFLAGS") def append_cxxflags(value): """ Add to or create a new CXXFLAGS in the make.conf Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.append_cxxflags '-pipe' """ return append_var("CXXFLAGS", value) def trim_cxxflags(value): """ Remove a value from CXXFLAGS variable in the make.conf Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.trim_cxxflags '-pipe' """ return trim_var("CXXFLAGS", value) def cxxflags_contains(value): """ Verify if CXXFLAGS variable contains a value in make.conf Return True if value is set for var CLI Example: .. code-block:: bash salt '*' makeconf.cxxflags_contains '-pipe' """ return var_contains("CXXFLAGS", value) def set_chost(value): """ Set the CHOST variable Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.set_chost 'x86_64-pc-linux-gnu' """ return set_var("CHOST", value) def get_chost(): """ Get the value of CHOST variable in the make.conf Return the value of the variable or None if the variable is not in the make.conf CLI Example: .. code-block:: bash salt '*' makeconf.get_chost """ return get_var("CHOST") def chost_contains(value): """ Verify if CHOST variable contains a value in make.conf Return True if value is set for var CLI Example: .. code-block:: bash salt '*' makeconf.chost_contains 'x86_64-pc-linux-gnu' """ return var_contains("CHOST", value) def set_makeopts(value): """ Set the MAKEOPTS variable Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.set_makeopts '-j3' """ return set_var("MAKEOPTS", value) def get_makeopts(): """ Get the value of MAKEOPTS variable in the make.conf Return the value of the variable or None if the variable is not in the make.conf CLI Example: .. code-block:: bash salt '*' makeconf.get_makeopts """ return get_var("MAKEOPTS") def append_makeopts(value): """ Add to or create a new MAKEOPTS in the make.conf Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.append_makeopts '-j3' """ return append_var("MAKEOPTS", value) def trim_makeopts(value): """ Remove a value from MAKEOPTS variable in the make.conf Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.trim_makeopts '-j3' """ return trim_var("MAKEOPTS", value) def makeopts_contains(value): """ Verify if MAKEOPTS variable contains a value in make.conf Return True if value is set for var CLI Example: .. code-block:: bash salt '*' makeconf.makeopts_contains '-j3' """ return var_contains("MAKEOPTS", value) def set_emerge_default_opts(value): """ Set the EMERGE_DEFAULT_OPTS variable Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.set_emerge_default_opts '--jobs' """ return set_var("EMERGE_DEFAULT_OPTS", value) def get_emerge_default_opts(): """ Get the value of EMERGE_DEFAULT_OPTS variable in the make.conf Return the value of the variable or None if the variable is not in the make.conf CLI Example: .. code-block:: bash salt '*' makeconf.get_emerge_default_opts """ return get_var("EMERGE_DEFAULT_OPTS") def append_emerge_default_opts(value): """ Add to or create a new EMERGE_DEFAULT_OPTS in the make.conf Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.append_emerge_default_opts '--jobs' """ return append_var("EMERGE_DEFAULT_OPTS", value) def trim_emerge_default_opts(value): """ Remove a value from EMERGE_DEFAULT_OPTS variable in the make.conf Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.trim_emerge_default_opts '--jobs' """ return trim_var("EMERGE_DEFAULT_OPTS", value) def emerge_default_opts_contains(value): """ Verify if EMERGE_DEFAULT_OPTS variable contains a value in make.conf Return True if value is set for var CLI Example: .. code-block:: bash salt '*' makeconf.emerge_default_opts_contains '--jobs' """ return var_contains("EMERGE_DEFAULT_OPTS", value) def set_gentoo_mirrors(value): """ Set the GENTOO_MIRRORS variable Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.set_gentoo_mirrors 'http://distfiles.gentoo.org' """ return set_var("GENTOO_MIRRORS", value) def get_gentoo_mirrors(): """ Get the value of GENTOO_MIRRORS variable in the make.conf Return the value of the variable or None if the variable is not in the make.conf CLI Example: .. code-block:: bash salt '*' makeconf.get_gentoo_mirrors """ return get_var("GENTOO_MIRRORS") def append_gentoo_mirrors(value): """ Add to or create a new GENTOO_MIRRORS in the make.conf Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.append_gentoo_mirrors 'http://distfiles.gentoo.org' """ return append_var("GENTOO_MIRRORS", value) def trim_gentoo_mirrors(value): """ Remove a value from GENTOO_MIRRORS variable in the make.conf Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.trim_gentoo_mirrors 'http://distfiles.gentoo.org' """ return trim_var("GENTOO_MIRRORS", value) def gentoo_mirrors_contains(value): """ Verify if GENTOO_MIRRORS variable contains a value in make.conf Return True if value is set for var CLI Example: .. code-block:: bash salt '*' makeconf.gentoo_mirrors_contains 'http://distfiles.gentoo.org' """ return var_contains("GENTOO_MIRRORS", value) def set_sync(value): """ Set the SYNC variable Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.set_sync 'rsync://rsync.namerica.gentoo.org/gentoo-portage' """ return set_var("SYNC", value) def get_sync(): """ Get the value of SYNC variable in the make.conf Return the value of the variable or None if the variable is not in the make.conf CLI Example: .. code-block:: bash salt '*' makeconf.get_sync """ return get_var("SYNC") def sync_contains(value): """ Verify if SYNC variable contains a value in make.conf Return True if value is set for var CLI Example: .. code-block:: bash salt '*' makeconf.sync_contains 'rsync://rsync.namerica.gentoo.org/gentoo-portage' """ return var_contains("SYNC", value) def get_features(): """ Get the value of FEATURES variable in the make.conf Return the value of the variable or None if the variable is not in the make.conf CLI Example: .. code-block:: bash salt '*' makeconf.get_features """ return get_var("FEATURES") def append_features(value): """ Add to or create a new FEATURES in the make.conf Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.append_features 'webrsync-gpg' """ return append_var("FEATURES", value) def trim_features(value): """ Remove a value from FEATURES variable in the make.conf Return a dict containing the new value for variable:: {'<variable>': {'old': '<old-value>', 'new': '<new-value>'}} CLI Example: .. code-block:: bash salt '*' makeconf.trim_features 'webrsync-gpg' """ return trim_var("FEATURES", value) def features_contains(value): """ Verify if FEATURES variable contains a value in make.conf Return True if value is set for var CLI Example: .. code-block:: bash salt '*' makeconf.features_contains 'webrsync-gpg' """ return var_contains("FEATURES", value)
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/makeconf.py
0.479016
0.182626
makeconf.py
pypi
import os HAS_GENTOOLKIT = False try: from gentoolkit.eclean import search, clean, cli, exclude as excludemod HAS_GENTOOLKIT = True except ImportError: pass # Define the module's virtual name __virtualname__ = "gentoolkit" def __virtual__(): """ Only work on Gentoo systems with gentoolkit installed """ if __grains__["os"] == "Gentoo" and HAS_GENTOOLKIT: return __virtualname__ return ( False, "The gentoolkitmod execution module cannot be loaded: either the system is not" " Gentoo or the gentoolkit.eclean python module not available", ) def revdep_rebuild(lib=None): """ Fix up broken reverse dependencies lib Search for reverse dependencies for a particular library rather than every library on the system. It can be a full path to a library or basic regular expression. CLI Example: .. code-block:: bash salt '*' gentoolkit.revdep_rebuild """ cmd = "revdep-rebuild -i --quiet --no-progress" if lib is not None: cmd += " --library={}".format(lib) return __salt__["cmd.retcode"](cmd, python_shell=False) == 0 def _pretty_size(size): """ Print sizes in a similar fashion as eclean """ units = [" G", " M", " K", " B"] while units and size >= 1000: size = size / 1024.0 units.pop() return "{}{}".format(round(size, 1), units[-1]) def _parse_exclude(exclude_file): """ Parse an exclude file. Returns a dict as defined in gentoolkit.eclean.exclude.parseExcludeFile """ if os.path.isfile(exclude_file): exclude = excludemod.parseExcludeFile(exclude_file, lambda x: None) else: exclude = dict() return exclude def eclean_dist( destructive=False, package_names=False, size_limit=0, time_limit=0, fetch_restricted=False, exclude_file="/etc/eclean/distfiles.exclude", ): """ Clean obsolete portage sources destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True size_limit <size> Don't delete distfiles bigger than <size>. <size> is a size specification: "10M" is "ten megabytes", "200K" is "two hundreds kilobytes", etc. Units are: G, M, K and B. time_limit <time> Don't delete distfiles files modified since <time> <time> is an amount of time: "1y" is "one year", "2w" is "two weeks", etc. Units are: y (years), m (months), w (weeks), d (days) and h (hours). fetch_restricted Protect fetch-restricted files. Only meaningful if used with destructive=True exclude_file Path to exclusion file. Default is /etc/eclean/distfiles.exclude This is the same default eclean-dist uses. Use None if this file exists and you want to ignore. Returns a dict containing the cleaned, saved, and deprecated dists: .. code-block:: python {'cleaned': {<dist file>: <size>}, 'deprecated': {<package>: <dist file>}, 'saved': {<package>: <dist file>}, 'total_cleaned': <size>} CLI Example: .. code-block:: bash salt '*' gentoolkit.eclean_dist destructive=True """ if exclude_file is None: exclude = None else: try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: ret = {e: "Invalid exclusion file: {}".format(exclude_file)} return ret if time_limit != 0: time_limit = cli.parseTime(time_limit) if size_limit != 0: size_limit = cli.parseSize(size_limit) clean_size = 0 engine = search.DistfilesSearch(lambda x: None) clean_me, saved, deprecated = engine.findDistfiles( destructive=destructive, package_names=package_names, size_limit=size_limit, time_limit=time_limit, fetch_restricted=fetch_restricted, exclude=exclude, ) cleaned = dict() def _eclean_progress_controller(size, key, *args): cleaned[key] = _pretty_size(size) return True if clean_me: cleaner = clean.CleanUp(_eclean_progress_controller) clean_size = cleaner.clean_dist(clean_me) ret = { "cleaned": cleaned, "saved": saved, "deprecated": deprecated, "total_cleaned": _pretty_size(clean_size), } return ret def eclean_pkg( destructive=False, package_names=False, time_limit=0, exclude_file="/etc/eclean/packages.exclude", ): """ Clean obsolete binary packages destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True time_limit <time> Don't delete distfiles files modified since <time> <time> is an amount of time: "1y" is "one year", "2w" is "two weeks", etc. Units are: y (years), m (months), w (weeks), d (days) and h (hours). exclude_file Path to exclusion file. Default is /etc/eclean/packages.exclude This is the same default eclean-pkg uses. Use None if this file exists and you want to ignore. Returns a dict containing the cleaned binary packages: .. code-block:: python {'cleaned': {<dist file>: <size>}, 'total_cleaned': <size>} CLI Example: .. code-block:: bash salt '*' gentoolkit.eclean_pkg destructive=True """ if exclude_file is None: exclude = None else: try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: ret = {e: "Invalid exclusion file: {}".format(exclude_file)} return ret if time_limit != 0: time_limit = cli.parseTime(time_limit) clean_size = 0 # findPackages requires one arg, but does nothing with it. # So we will just pass None in for the required arg clean_me = search.findPackages( None, destructive=destructive, package_names=package_names, time_limit=time_limit, exclude=exclude, pkgdir=search.pkgdir, ) cleaned = dict() def _eclean_progress_controller(size, key, *args): cleaned[key] = _pretty_size(size) return True if clean_me: cleaner = clean.CleanUp(_eclean_progress_controller) clean_size = cleaner.clean_pkgs(clean_me, search.pkgdir) ret = {"cleaned": cleaned, "total_cleaned": _pretty_size(clean_size)} return ret def _glsa_list_process_output(output): """ Process output from glsa_check_list into a dict Returns a dict containing the glsa id, description, status, and CVEs """ ret = dict() for line in output: try: glsa_id, status, desc = line.split(None, 2) if "U" in status: status += " Not Affected" elif "N" in status: status += " Might be Affected" elif "A" in status: status += " Applied (injected)" if "CVE" in desc: desc, cves = desc.rsplit(None, 1) cves = cves.split(",") else: cves = list() ret[glsa_id] = {"description": desc, "status": status, "CVEs": cves} except ValueError: pass return ret def glsa_check_list(glsa_list): """ List the status of Gentoo Linux Security Advisories glsa_list can contain an arbitrary number of GLSA ids, filenames containing GLSAs or the special identifiers 'all' and 'affected' Returns a dict containing glsa ids with a description, status, and CVEs: .. code-block:: python {<glsa_id>: {'description': <glsa_description>, 'status': <glsa status>, 'CVEs': [<list of CVEs>]}} CLI Example: .. code-block:: bash salt '*' gentoolkit.glsa_check_list 'affected' """ cmd = "glsa-check --quiet --nocolor --cve --list " if isinstance(glsa_list, list): for glsa in glsa_list: cmd += glsa + " " elif glsa_list == "all" or glsa_list == "affected": cmd += glsa_list ret = dict() out = __salt__["cmd.run"](cmd, python_shell=False).split("\n") ret = _glsa_list_process_output(out) return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/gentoolkitmod.py
0.535341
0.232484
gentoolkitmod.py
pypi
import difflib import logging import os import salt.utils.event import salt.utils.files import salt.utils.yaml log = logging.getLogger(__name__) default_event_wait = 60 __func_alias__ = {"list_": "list", "reload_": "reload"} def list_(return_yaml=True, include_pillar=True, include_opts=True, **kwargs): """ List the beacons currently configured on the minion :param return_yaml: Whether to return YAML formatted output, default ``True`` :param include_pillar: Whether to include beacons that are configured in pillar, default is ``True``. :param include_opts: Whether to include beacons that are configured in opts, default is ``True``. :return: List of currently configured Beacons. CLI Example: .. code-block:: bash salt '*' beacons.list """ beacons = None try: with salt.utils.event.get_event( "minion", opts=__opts__, listen=True ) as event_bus: res = __salt__["event.fire"]( { "func": "list", "include_pillar": include_pillar, "include_opts": include_opts, }, "manage_beacons", ) if res: event_ret = event_bus.get_event( tag="/salt/minion/minion_beacons_list_complete", wait=kwargs.get("timeout", default_event_wait), ) log.debug("event_ret %s", event_ret) if event_ret and event_ret["complete"]: beacons = event_ret["beacons"] except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret["result"] = False ret["comment"] = "Event module not available. Beacon list failed." return ret if return_yaml: tmp = {"beacons": beacons} return salt.utils.yaml.safe_dump(tmp, default_flow_style=False) else: return beacons def list_available(return_yaml=True, **kwargs): """ List the beacons currently available on the minion :param return_yaml: Whether to return YAML formatted output, default ``True`` :return: List of currently configured Beacons. CLI Example: .. code-block:: bash salt '*' beacons.list_available """ beacons = None try: with salt.utils.event.get_event( "minion", opts=__opts__, listen=True ) as event_bus: res = __salt__["event.fire"]({"func": "list_available"}, "manage_beacons") if res: event_ret = event_bus.get_event( tag="/salt/minion/minion_beacons_list_available_complete", wait=kwargs.get("timeout", default_event_wait), ) if event_ret and event_ret["complete"]: beacons = event_ret["beacons"] except KeyError as e: # Effectively a no-op, since we can't really return without an event system ret = {} ret["result"] = False ret["comment"] = "Event module not available. Beacon list_available failed." return ret if beacons: if return_yaml: tmp = {"beacons": beacons} return salt.utils.yaml.safe_dump(tmp, default_flow_style=False) else: return beacons else: return {"beacons": {}} def add(name, beacon_data, **kwargs): """ Add a beacon on the minion :param name: Name of the beacon to configure :param beacon_data: Dictionary or list containing configuration for beacon. :return: Boolean and status message on success or failure of add. CLI Example: .. code-block:: bash salt '*' beacons.add ps "[{'processes': {'salt-master': 'stopped', 'apache2': 'stopped'}}]" """ ret = {"comment": "Failed to add beacon {}.".format(name), "result": False} if name in list_(return_yaml=False, **kwargs): ret["comment"] = "Beacon {} is already configured.".format(name) ret["result"] = True return ret # Check to see if a beacon_module is specified, if so, verify it is # valid and available beacon type. if any("beacon_module" in key for key in beacon_data): res = next(value for value in beacon_data if "beacon_module" in value) beacon_name = res["beacon_module"] else: beacon_name = name if beacon_name not in list_available(return_yaml=False, **kwargs): ret["comment"] = 'Beacon "{}" is not available.'.format(beacon_name) return ret if "test" in kwargs and kwargs["test"]: ret["result"] = True ret["comment"] = "Beacon: {} would be added.".format(name) else: try: # Attempt to load the beacon module so we have access to the validate function with salt.utils.event.get_event( "minion", opts=__opts__, listen=True ) as event_bus: res = __salt__["event.fire"]( { "name": name, "beacon_data": beacon_data, "func": "validate_beacon", }, "manage_beacons", ) if res: event_ret = event_bus.get_event( tag="/salt/minion/minion_beacon_validation_complete", wait=kwargs.get("timeout", default_event_wait), ) valid = event_ret["valid"] vcomment = event_ret["vcomment"] if not valid: ret["result"] = False ret[ "comment" ] = "Beacon {} configuration invalid, not adding.\n{}".format( name, vcomment ) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret["result"] = False ret["comment"] = "Event module not available. Beacon validation failed." return ret try: with salt.utils.event.get_event( "minion", opts=__opts__, listen=True ) as event_bus: res = __salt__["event.fire"]( {"name": name, "beacon_data": beacon_data, "func": "add"}, "manage_beacons", ) if res: event_ret = event_bus.get_event( tag="/salt/minion/minion_beacon_add_complete", wait=kwargs.get("timeout", default_event_wait), ) if event_ret and event_ret["complete"]: beacons = event_ret["beacons"] if name in beacons and all( [item in beacons[name] for item in beacon_data] ): ret["result"] = True ret["comment"] = "Added beacon: {}.".format(name) elif event_ret: ret["result"] = False ret["comment"] = event_ret["comment"] else: ret["result"] = False ret["comment"] = ( "Did not receive the beacon add complete event before the" " timeout of {}s".format( kwargs.get("timeout", default_event_wait) ) ) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret["result"] = False ret["comment"] = "Event module not available. Beacon add failed." return ret def modify(name, beacon_data, **kwargs): """ Modify an existing beacon :param name: Name of the beacon to configure :param beacon_data: Dictionary or list containing updated configuration for beacon. :return: Boolean and status message on success or failure of modify. CLI Example: .. code-block:: bash salt '*' beacons.modify ps "[{'salt-master': 'stopped'}, {'apache2': 'stopped'}]" """ ret = {"comment": "", "result": True} current_beacons = list_(return_yaml=False, **kwargs) if name not in current_beacons: ret["comment"] = "Beacon {} is not configured.".format(name) return ret if "test" in kwargs and kwargs["test"]: ret["result"] = True ret["comment"] = "Beacon: {} would be modified.".format(name) else: try: # Attempt to load the beacon module so we have access to the validate function with salt.utils.event.get_event( "minion", opts=__opts__, listen=True ) as event_bus: res = __salt__["event.fire"]( { "name": name, "beacon_data": beacon_data, "func": "validate_beacon", }, "manage_beacons", ) if res: event_ret = event_bus.get_event( tag="/salt/minion/minion_beacon_validation_complete", wait=kwargs.get("timeout", default_event_wait), ) valid = event_ret["valid"] vcomment = event_ret["vcomment"] if not valid: ret["result"] = False ret[ "comment" ] = "Beacon {} configuration invalid, not modifying.\n{}".format( name, vcomment ) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret["result"] = False ret["comment"] = "Event module not available. Beacon modify failed." return ret if not valid: ret["result"] = False ret[ "comment" ] = "Beacon {} configuration invalid, not modifying.\n{}".format( name, vcomment ) return ret _current = current_beacons[name] _new = beacon_data if _new == _current: ret["comment"] = "Job {} in correct state".format(name) return ret _current_lines = [] for _item in _current: _current_lines.extend( ["{}:{}\n".format(key, value) for (key, value) in _item.items()] ) _new_lines = [] for _item in _new: _new_lines.extend( ["{}:{}\n".format(key, value) for (key, value) in _item.items()] ) _diff = difflib.unified_diff(_current_lines, _new_lines) ret["changes"] = {} ret["changes"]["diff"] = "".join(_diff) try: with salt.utils.event.get_event( "minion", opts=__opts__, listen=True ) as event_bus: res = __salt__["event.fire"]( {"name": name, "beacon_data": beacon_data, "func": "modify"}, "manage_beacons", ) if res: event_ret = event_bus.get_event( tag="/salt/minion/minion_beacon_modify_complete", wait=kwargs.get("timeout", default_event_wait), ) if event_ret and event_ret["complete"]: beacons = event_ret["beacons"] if name in beacons and beacons[name] == beacon_data: ret["result"] = True ret["comment"] = "Modified beacon: {}.".format(name) elif event_ret: ret["result"] = False ret["comment"] = event_ret["comment"] else: ret["result"] = False ret["comment"] = ( "Did not receive the beacon modify complete event before" " the timeout of {}s".format( kwargs.get("timeout", default_event_wait) ) ) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret["result"] = False ret["comment"] = "Event module not available. Beacon modify failed." return ret def delete(name, **kwargs): """ Delete a beacon item :param name: Name of the beacon to delete :return: Boolean and status message on success or failure of delete. CLI Example: .. code-block:: bash salt '*' beacons.delete ps salt '*' beacons.delete load """ ret = {"comment": "Failed to delete beacon {}.".format(name), "result": False} if "test" in kwargs and kwargs["test"]: ret["result"] = True ret["comment"] = "Beacon: {} would be deleted.".format(name) else: try: with salt.utils.event.get_event( "minion", opts=__opts__, listen=True ) as event_bus: res = __salt__["event.fire"]( {"name": name, "func": "delete"}, "manage_beacons" ) if res: event_ret = event_bus.get_event( tag="/salt/minion/minion_beacon_delete_complete", wait=kwargs.get("timeout", default_event_wait), ) if event_ret and event_ret["complete"]: beacons = event_ret["beacons"] if name not in beacons: ret["result"] = True ret["comment"] = "Deleted beacon: {}.".format(name) return ret elif event_ret: ret["result"] = False ret["comment"] = event_ret["comment"] else: ret["result"] = False ret["comment"] = ( "Did not receive the beacon delete complete event before" " the timeout of {}s".format( kwargs.get("timeout", default_event_wait) ) ) except KeyError: # Effectively a no-op, since we can't really return without an event system ret["result"] = False ret["comment"] = "Event module not available. Beacon delete failed." return ret def save(**kwargs): """ Save all configured beacons to the minion config :return: Boolean and status message on success or failure of save. CLI Example: .. code-block:: bash salt '*' beacons.save """ ret = {"comment": [], "result": True} beacons = list_(return_yaml=False, include_pillar=False, **kwargs) # move this file into an configurable opt sfn = os.path.join( os.path.dirname(__opts__["conf_file"]), os.path.dirname(__opts__["default_include"]), "beacons.conf", ) if beacons: tmp = {"beacons": beacons} yaml_out = salt.utils.yaml.safe_dump(tmp, default_flow_style=False) else: yaml_out = "" try: with salt.utils.files.fopen(sfn, "w+") as fp_: fp_.write(yaml_out) ret["comment"] = "Beacons saved to {}.".format(sfn) except OSError: ret[ "comment" ] = "Unable to write to beacons file at {}. Check permissions.".format(sfn) ret["result"] = False return ret def enable(**kwargs): """ Enable all beacons on the minion Returns: bool: Boolean and status message on success or failure of enable. CLI Example: .. code-block:: bash salt '*' beacons.enable """ ret = {"comment": [], "result": True} if "test" in kwargs and kwargs["test"]: ret["comment"] = "Beacons would be enabled." else: try: with salt.utils.event.get_event( "minion", opts=__opts__, listen=True ) as event_bus: res = __salt__["event.fire"]({"func": "enable"}, "manage_beacons") if res: event_ret = event_bus.get_event( tag="/salt/minion/minion_beacons_enabled_complete", wait=kwargs.get("timeout", default_event_wait), ) if event_ret and event_ret["complete"]: beacons = event_ret["beacons"] if "enabled" in beacons and beacons["enabled"]: ret["result"] = True ret["comment"] = "Enabled beacons on minion." elif event_ret: ret["result"] = False ret["comment"] = "Failed to enable beacons on minion." else: ret["result"] = False ret["comment"] = ( "Did not receive the beacon enabled complete event" " before the timeout of {}s".format( kwargs.get("timeout", default_event_wait) ) ) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret["result"] = False ret["comment"] = "Event module not available. Beacons enable job failed." return ret def disable(**kwargs): """ Disable all beacons jobs on the minion :return: Boolean and status message on success or failure of disable. CLI Example: .. code-block:: bash salt '*' beacons.disable """ ret = {"comment": [], "result": True} if "test" in kwargs and kwargs["test"]: ret["comment"] = "Beacons would be disabled." else: try: with salt.utils.event.get_event( "minion", opts=__opts__, listen=True ) as event_bus: res = __salt__["event.fire"]({"func": "disable"}, "manage_beacons") if res: event_ret = event_bus.get_event( tag="/salt/minion/minion_beacons_disabled_complete", wait=kwargs.get("timeout", default_event_wait), ) log.debug("event_ret %s", event_ret) if event_ret and event_ret["complete"]: beacons = event_ret["beacons"] if "enabled" in beacons and not beacons["enabled"]: ret["result"] = True ret["comment"] = "Disabled beacons on minion." elif event_ret: ret["result"] = False ret["comment"] = "Failed to disable beacons on minion." else: ret["result"] = False ret["comment"] = ( "Did not receive the beacon disabled complete event" " before the timeout of {}s".format( kwargs.get("timeout", default_event_wait) ) ) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret["result"] = False ret["comment"] = "Event module not available. Beacons disable job failed." return ret def _get_beacon_config_dict(beacon_config): beacon_config_dict = {} if isinstance(beacon_config, list): list(map(beacon_config_dict.update, beacon_config)) else: beacon_config_dict = beacon_config return beacon_config_dict def enable_beacon(name, **kwargs): """ Enable beacon on the minion :name: Name of the beacon to enable. :return: Boolean and status message on success or failure of enable. CLI Example: .. code-block:: bash salt '*' beacons.enable_beacon ps """ ret = {"comment": [], "result": True} if not name: ret["comment"] = "Beacon name is required." ret["result"] = False return ret if "test" in kwargs and kwargs["test"]: ret["comment"] = "Beacon {} would be enabled.".format(name) else: _beacons = list_(return_yaml=False, **kwargs) if name not in _beacons: ret["comment"] = "Beacon {} is not currently configured.".format(name) ret["result"] = False return ret try: with salt.utils.event.get_event( "minion", opts=__opts__, listen=True ) as event_bus: res = __salt__["event.fire"]( {"func": "enable_beacon", "name": name}, "manage_beacons" ) if res: event_ret = event_bus.get_event( tag="/salt/minion/minion_beacon_enabled_complete", wait=kwargs.get("timeout", default_event_wait), ) if event_ret and event_ret["complete"]: beacons = event_ret["beacons"] beacon_config_dict = _get_beacon_config_dict(beacons[name]) if ( "enabled" in beacon_config_dict and beacon_config_dict["enabled"] ): ret["result"] = True ret["comment"] = "Enabled beacon {} on minion.".format(name) else: ret["result"] = False ret[ "comment" ] = "Failed to enable beacon {} on minion.".format(name) elif event_ret: ret["result"] = False ret["comment"] = event_ret["comment"] else: ret["result"] = False ret["comment"] = ( "Did not receive the beacon enabled complete event before" " the timeout of {}s".format( kwargs.get("timeout", default_event_wait) ) ) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret["result"] = False ret[ "comment" ] = "Event module not available. Beacon enable_beacon job failed." return ret def disable_beacon(name, **kwargs): """ Disable a beacon on the minion :name: Name of the beacon to disable. :return: Boolean and status message on success or failure of disable. CLI Example: .. code-block:: bash salt '*' beacons.disable_beacon ps """ ret = {"comment": [], "result": True} if not name: ret["comment"] = "Beacon name is required." ret["result"] = False return ret if "test" in kwargs and kwargs["test"]: ret["comment"] = "Beacons would be disabled." else: _beacons = list_(return_yaml=False, **kwargs) if name not in _beacons: ret["comment"] = "Beacon {} is not currently configured.".format(name) ret["result"] = False return ret try: with salt.utils.event.get_event( "minion", opts=__opts__, listen=True ) as event_bus: res = __salt__["event.fire"]( {"func": "disable_beacon", "name": name}, "manage_beacons" ) if res: event_ret = event_bus.get_event( tag="/salt/minion/minion_beacon_disabled_complete", wait=kwargs.get("timeout", default_event_wait), ) if event_ret and event_ret["complete"]: beacons = event_ret["beacons"] beacon_config_dict = _get_beacon_config_dict(beacons[name]) if ( "enabled" in beacon_config_dict and not beacon_config_dict["enabled"] ): ret["result"] = True ret["comment"] = "Disabled beacon {} on minion.".format( name ) else: ret["result"] = False ret["comment"] = "Failed to disable beacon on minion." elif event_ret: ret["result"] = False ret["comment"] = event_ret["comment"] else: ret["result"] = False ret["comment"] = ( "Did not receive the beacon disabled complete event before" " the timeout of {}s".format( kwargs.get("timeout", default_event_wait) ) ) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret["result"] = False ret[ "comment" ] = "Event module not available. Beacon disable_beacon job failed." return ret def reset(**kwargs): """ Reset beacon configuration on the minion CLI Example: .. code-block:: bash salt '*' beacons.reset """ ret = {"comment": [], "result": True} if kwargs.get("test"): ret["comment"] = "Beacons would be reset." else: try: with salt.utils.event.get_event( "minion", opts=__opts__, listen=True ) as event_bus: res = __salt__["event.fire"]({"func": "reset"}, "manage_beacons") if res: event_ret = event_bus.get_event( tag="/salt/minion/minion_beacon_reset_complete", wait=kwargs.get("timeout", default_event_wait), ) if event_ret and event_ret["complete"]: ret["result"] = True ret["comment"] = "Beacon configuration reset." else: ret["result"] = False if ret is not None: ret["comment"] = event_ret["comment"] else: ret["comment"] = ( "Did not receive the beacon reset event before the" " timeout of {}s".format( kwargs.get("timeout", default_event_wait) ) ) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret["result"] = False ret["comment"] = "Event module not available. Beacon reset job failed." return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/beacons.py
0.585694
0.15428
beacons.py
pypi
import logging from salt.exceptions import CommandExecutionError try: import requests ENABLED = True except ImportError: ENABLED = False log = logging.getLogger(__name__) def __virtual__(): """ Only load this module if the requests python module is available """ if ENABLED: return "uptime" return (False, "uptime module needs the python requests module to work") def create(name, **params): """Create a check on a given URL. Additional parameters can be used and are passed to API (for example interval, maxTime, etc). See the documentation https://github.com/fzaninotto/uptime for a full list of the parameters. CLI Example: .. code-block:: bash salt '*' uptime.create http://example.org """ if check_exists(name): msg = "Trying to create check that already exists : {}".format(name) log.error(msg) raise CommandExecutionError(msg) application_url = _get_application_url() log.debug("[uptime] trying PUT request") params.update(url=name) req = requests.put("{}/api/checks".format(application_url), data=params) if not req.ok: raise CommandExecutionError("request to uptime failed : {}".format(req.reason)) log.debug("[uptime] PUT request successful") return req.json()["_id"] def delete(name): """ Delete a check on a given URL CLI Example: .. code-block:: bash salt '*' uptime.delete http://example.org """ if not check_exists(name): msg = "Trying to delete check that doesn't exists : {}".format(name) log.error(msg) raise CommandExecutionError(msg) application_url = _get_application_url() log.debug("[uptime] trying DELETE request") jcontent = requests.get("{}/api/checks".format(application_url)).json() url_id = [x["_id"] for x in jcontent if x["url"] == name][0] req = requests.delete("{}/api/checks/{}".format(application_url, url_id)) if not req.ok: raise CommandExecutionError("request to uptime failed : {}".format(req.reason)) log.debug("[uptime] DELETE request successful") return True def _get_application_url(): """ Helper function to get application url from pillar """ application_url = __salt__["pillar.get"]("uptime:application_url") if application_url is None: log.error("Could not load uptime:application_url pillar") raise CommandExecutionError( "uptime:application_url pillar is required for authentication" ) return application_url def checks_list(): """ List URL checked by uptime CLI Example: .. code-block:: bash salt '*' uptime.checks_list """ application_url = _get_application_url() log.debug("[uptime] get checks") jcontent = requests.get("{}/api/checks".format(application_url)).json() return [x["url"] for x in jcontent] def check_exists(name): """ Check if a given URL is in being monitored by uptime CLI Example: .. code-block:: bash salt '*' uptime.check_exists http://example.org """ if name in checks_list(): log.debug("[uptime] found %s in checks", name) return True return False
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/uptime.py
0.600071
0.162314
uptime.py
pypi
import logging import os import re import salt.utils.platform import salt.utils.versions log = logging.getLogger(__name__) __virtualname__ = "dism" # We always want to use the version of dism that matches the architecture of the # host machine. On 32bit boxes that will always be System32. On 64bit boxes that # are running 64bit salt that will always be System32. On 64bit boxes that are # running 32bit salt the 64bit dism will be found in SysNative # Sysnative is a virtual folder, a special alias, that can be used to access the # 64-bit System32 folder from a 32-bit application try: # This does not apply to Non-Windows platforms if not salt.utils.platform.is_windows(): raise OSError if os.path.exists(os.path.join(os.environ.get("SystemRoot"), "SysNative")): bin_path = os.path.join(os.environ.get("SystemRoot"), "SysNative") else: bin_path = os.path.join(os.environ.get("SystemRoot"), "System32") bin_dism = os.path.join(bin_path, "dism.exe") except OSError: log.trace("win_dism: Non-Windows system") bin_dism = "dism.exe" def __virtual__(): """ Only work on Windows """ if not salt.utils.platform.is_windows(): return False, "Only available on Windows systems" return __virtualname__ def _get_components(type_regex, plural_type, install_value, image=None): cmd = [ bin_dism, "/English", "/Image:{}".format(image) if image else "/Online", "/Get-{}".format(plural_type), ] out = __salt__["cmd.run"](cmd) pattern = r"{} : (.*)\r\n.*State : {}\r\n".format(type_regex, install_value) capabilities = re.findall(pattern, out, re.MULTILINE) capabilities.sort() return capabilities def add_capability( capability, source=None, limit_access=False, image=None, restart=False ): """ Install a capability Args: capability (str): The capability to install source (Optional[str]): The optional source of the capability. Default is set by group policy and can be Windows Update. limit_access (Optional[bool]): Prevent DISM from contacting Windows Update for the source package image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Raises: NotImplementedError: For all versions of Windows that are not Windows 10 and later. Server editions of Windows use ServerManager instead. Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.add_capability Tools.Graphics.DirectX~~~~0.0.1.0 """ if salt.utils.versions.version_cmp(__grains__["osversion"], "10") == -1: raise NotImplementedError( "`install_capability` is not available on this version of Windows: " "{}".format(__grains__["osversion"]) ) cmd = [ bin_dism, "/Quiet", "/Image:{}".format(image) if image else "/Online", "/Add-Capability", "/CapabilityName:{}".format(capability), ] if source: cmd.append("/Source:{}".format(source)) if limit_access: cmd.append("/LimitAccess") if not restart: cmd.append("/NoRestart") return __salt__["cmd.run_all"](cmd) def remove_capability(capability, image=None, restart=False): """ Uninstall a capability Args: capability(str): The capability to be removed image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Raises: NotImplementedError: For all versions of Windows that are not Windows 10 and later. Server editions of Windows use ServerManager instead. Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.remove_capability Tools.Graphics.DirectX~~~~0.0.1.0 """ if salt.utils.versions.version_cmp(__grains__["osversion"], "10") == -1: raise NotImplementedError( "`uninstall_capability` is not available on this version of " "Windows: {}".format(__grains__["osversion"]) ) cmd = [ bin_dism, "/Quiet", "/Image:{}".format(image) if image else "/Online", "/Remove-Capability", "/CapabilityName:{}".format(capability), ] if not restart: cmd.append("/NoRestart") return __salt__["cmd.run_all"](cmd) def get_capabilities(image=None): """ List all capabilities on the system Args: image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Raises: NotImplementedError: For all versions of Windows that are not Windows 10 and later. Server editions of Windows use ServerManager instead. Returns: list: A list of capabilities CLI Example: .. code-block:: bash salt '*' dism.get_capabilities """ if salt.utils.versions.version_cmp(__grains__["osversion"], "10") == -1: raise NotImplementedError( "`installed_capabilities` is not available on this version of " "Windows: {}".format(__grains__["osversion"]) ) cmd = [ bin_dism, "/English", "/Image:{}".format(image) if image else "/Online", "/Get-Capabilities", ] out = __salt__["cmd.run"](cmd) pattern = r"Capability Identity : (.*)\r\n" capabilities = re.findall(pattern, out, re.MULTILINE) capabilities.sort() return capabilities def installed_capabilities(image=None): """ List the capabilities installed on the system Args: image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Raises: NotImplementedError: For all versions of Windows that are not Windows 10 and later. Server editions of Windows use ServerManager instead. Returns: list: A list of installed capabilities CLI Example: .. code-block:: bash salt '*' dism.installed_capabilities """ if salt.utils.versions.version_cmp(__grains__["osversion"], "10") == -1: raise NotImplementedError( "`installed_capabilities` is not available on this version of " "Windows: {}".format(__grains__["osversion"]) ) return _get_components("Capability Identity", "Capabilities", "Installed") def available_capabilities(image=None): """ List the capabilities available on the system Args: image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Raises: NotImplementedError: For all versions of Windows that are not Windows 10 and later. Server editions of Windows use ServerManager instead. Returns: list: A list of available capabilities CLI Example: .. code-block:: bash salt '*' dism.installed_capabilities """ if salt.utils.versions.version_cmp(__grains__["osversion"], "10") == -1: raise NotImplementedError( "`installed_capabilities` is not available on this version of " "Windows: {}".format(__grains__["osversion"]) ) return _get_components("Capability Identity", "Capabilities", "Not Present") def add_feature( feature, package=None, source=None, limit_access=False, enable_parent=False, image=None, restart=False, ): """ Install a feature using DISM Args: feature (str): The feature to install package (Optional[str]): The parent package for the feature. You do not have to specify the package if it is the Windows Foundation Package. Otherwise, use package to specify the parent package of the feature source (Optional[str]): The optional source of the capability. Default is set by group policy and can be Windows Update limit_access (Optional[bool]): Prevent DISM from contacting Windows Update for the source package enable_parent (Optional[bool]): True will enable all parent features of the specified feature image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.add_feature NetFx3 """ cmd = [ bin_dism, "/Quiet", "/Image:{}".format(image) if image else "/Online", "/Enable-Feature", "/FeatureName:{}".format(feature), ] if package: cmd.append("/PackageName:{}".format(package)) if source: cmd.append("/Source:{}".format(source)) if limit_access: cmd.append("/LimitAccess") if enable_parent: cmd.append("/All") if not restart: cmd.append("/NoRestart") return __salt__["cmd.run_all"](cmd) def remove_feature(feature, remove_payload=False, image=None, restart=False): """ Disables the feature. Args: feature (str): The feature to uninstall remove_payload (Optional[bool]): Remove the feature's payload. Must supply source when enabling in the future. image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.remove_feature NetFx3 """ cmd = [ bin_dism, "/Quiet", "/Image:{}".format(image) if image else "/Online", "/Disable-Feature", "/FeatureName:{}".format(feature), ] if remove_payload: cmd.append("/Remove") if not restart: cmd.append("/NoRestart") return __salt__["cmd.run_all"](cmd) def get_features(package=None, image=None): """ List features on the system or in a package Args: package (Optional[str]): The full path to the package. Can be either a .cab file or a folder. Should point to the original source of the package, not to where the file is installed. You cannot use this command to get package information for .msu files This can also be the name of a package as listed in ``dism.installed_packages`` image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Returns: list: A list of features CLI Example: .. code-block:: bash # Return all features on the system salt '*' dism.get_features # Return all features in package.cab salt '*' dism.get_features C:\\packages\\package.cab # Return all features in the calc package salt '*' dism.get_features Microsoft.Windows.Calc.Demo~6595b6144ccf1df~x86~en~1.0.0.0 """ cmd = [ bin_dism, "/English", "/Image:{}".format(image) if image else "/Online", "/Get-Features", ] if package: if "~" in package: cmd.append("/PackageName:{}".format(package)) else: cmd.append("/PackagePath:{}".format(package)) out = __salt__["cmd.run"](cmd) pattern = r"Feature Name : (.*)\r\n" features = re.findall(pattern, out, re.MULTILINE) features.sort() return features def installed_features(image=None): """ List the features installed on the system Args: image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Returns: list: A list of installed features CLI Example: .. code-block:: bash salt '*' dism.installed_features """ return _get_components("Feature Name", "Features", "Enabled") def available_features(image=None): """ List the features available on the system Args: image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Returns: list: A list of available features CLI Example: .. code-block:: bash salt '*' dism.available_features """ return _get_components("Feature Name", "Features", "Disabled") def add_package( package, ignore_check=False, prevent_pending=False, image=None, restart=False ): """ Install a package using DISM Args: package (str): The package to install. Can be a .cab file, a .msu file, or a folder .. note:: An `.msu` package is supported only when the target image is offline, either mounted or applied. ignore_check (Optional[bool]): Skip installation of the package if the applicability checks fail prevent_pending (Optional[bool]): Skip the installation of the package if there are pending online actions image (Optional[str]): The path to the root directory of an offline Windows image. If ``None`` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism.add_package C:\\Packages\\package.cab """ cmd = [ bin_dism, "/Quiet", "/Image:{}".format(image) if image else "/Online", "/Add-Package", "/PackagePath:{}".format(package), ] if ignore_check: cmd.append("/IgnoreCheck") if prevent_pending: cmd.append("/PreventPending") if not restart: cmd.append("/NoRestart") return __salt__["cmd.run_all"](cmd) def remove_package(package, image=None, restart=False): """ Uninstall a package Args: package (str): The full path to the package. Can be either a .cab file or a folder. Should point to the original source of the package, not to where the file is installed. This can also be the name of a package as listed in ``dism.installed_packages`` image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash # Remove the Calc Package salt '*' dism.remove_package Microsoft.Windows.Calc.Demo~6595b6144ccf1df~x86~en~1.0.0.0 # Remove the package.cab (does not remove C:\\packages\\package.cab) salt '*' dism.remove_package C:\\packages\\package.cab """ cmd = [ bin_dism, "/Quiet", "/Image:{}".format(image) if image else "/Online", "/Remove-Package", ] if not restart: cmd.append("/NoRestart") if "~" in package: cmd.append("/PackageName:{}".format(package)) else: cmd.append("/PackagePath:{}".format(package)) return __salt__["cmd.run_all"](cmd) def installed_packages(image=None): """ List the packages installed on the system Args: image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Returns: list: A list of installed packages CLI Example: .. code-block:: bash salt '*' dism.installed_packages """ return _get_components("Package Identity", "Packages", "Installed") def package_info(package, image=None): """ Display information about a package Args: package (str): The full path to the package. Can be either a .cab file or a folder. Should point to the original source of the package, not to where the file is installed. You cannot use this command to get package information for .msu files image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Returns: dict: A dictionary containing the results of the command CLI Example: .. code-block:: bash salt '*' dism. package_info C:\\packages\\package.cab """ cmd = [ bin_dism, "/English", "/Image:{}".format(image) if image else "/Online", "/Get-PackageInfo", ] if "~" in package: cmd.append("/PackageName:{}".format(package)) else: cmd.append("/PackagePath:{}".format(package)) out = __salt__["cmd.run_all"](cmd) if out["retcode"] == 0: ret = dict() for line in str(out["stdout"]).splitlines(): if " : " in line: info = line.split(" : ") if len(info) < 2: continue ret[info[0]] = info[1] else: ret = out return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/win_dism.py
0.695545
0.1692
win_dism.py
pypi
try: import sqlite3 HAS_SQLITE3 = True except ImportError: HAS_SQLITE3 = False # pylint: disable=C0103 def __virtual__(): if not HAS_SQLITE3: return ( False, "The sqlite3 execution module failed to load: the sqlite3 python library is" " not available.", ) return True def _connect(db=None): if db is None: return False con = sqlite3.connect(db, isolation_level=None) cur = con.cursor() return cur def version(): """ Return version of pysqlite CLI Example: .. code-block:: bash salt '*' sqlite3.version """ return sqlite3.version def sqlite_version(): """ Return version of sqlite CLI Example: .. code-block:: bash salt '*' sqlite3.sqlite_version """ return sqlite3.sqlite_version def modify(db=None, sql=None): """ Issue an SQL query to sqlite3 (with no return data), usually used to modify the database in some way (insert, delete, create, etc) CLI Example: .. code-block:: bash salt '*' sqlite3.modify /root/test.db 'CREATE TABLE test(id INT, testdata TEXT);' """ cur = _connect(db) if not cur: return False cur.execute(sql) return True def fetch(db=None, sql=None): """ Retrieve data from an sqlite3 db (returns all rows, be careful!) CLI Example: .. code-block:: bash salt '*' sqlite3.fetch /root/test.db 'SELECT * FROM test;' """ cur = _connect(db) if not cur: return False cur.execute(sql) rows = cur.fetchall() return rows def tables(db=None): """ Show all tables in the database CLI Example: .. code-block:: bash salt '*' sqlite3.tables /root/test.db """ cur = _connect(db) if not cur: return False cur.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;") rows = cur.fetchall() return rows def indices(db=None): """ Show all indices in the database CLI Example: .. code-block:: bash salt '*' sqlite3.indices /root/test.db """ cur = _connect(db) if not cur: return False cur.execute("SELECT name FROM sqlite_master WHERE type='index' ORDER BY name;") rows = cur.fetchall() return rows def indexes(db=None): """ Show all indices in the database, for people with poor spelling skills CLI Example: .. code-block:: bash salt '*' sqlite3.indexes /root/test.db """ return indices(db)
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/sqlite3.py
0.634883
0.211967
sqlite3.py
pypi
import logging import os import salt.utils.platform log = logging.getLogger(__name__) def __virtual__(): """ No dependency checks, and not renaming, just return True """ return True def setval(key, val, false_unsets=False, permanent=False): """ Set a single salt process environment variable. Returns True on success. key The environment key to set. Must be a string. val The value to set. Must be a string or False. Refer to the 'false_unsets' parameter for behavior when set to False. false_unsets If val is False and false_unsets is True, then the key will be removed from the salt processes environment dict entirely. If val is False and false_unsets is not True, then the key's value will be set to an empty string. Default: False. permanent On Windows minions this will set the environment variable in the registry so that it is always added as an environment variable when applications open. If you want to set the variable to HKLM instead of HKCU just pass in "HKLM" for this parameter. On all other minion types this will be ignored. Note: This will only take affect on applications opened after this has been set. CLI Example: .. code-block:: bash salt '*' environ.setval foo bar salt '*' environ.setval baz val=False false_unsets=True salt '*' environ.setval baz bar permanent=True salt '*' environ.setval baz bar permanent=HKLM """ is_windows = salt.utils.platform.is_windows() if is_windows: permanent_hive = "HKCU" permanent_key = "Environment" if permanent == "HKLM": permanent_hive = "HKLM" permanent_key = ( r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment" ) if not isinstance(key, str): log.debug("%s: 'key' argument is not a string type: '%s'", __name__, key) if val is False: if false_unsets is True: try: os.environ.pop(key, None) if permanent and is_windows: __utils__["reg.delete_value"](permanent_hive, permanent_key, key) __utils__["win_functions.broadcast_setting_change"]() return None except Exception as exc: # pylint: disable=broad-except log.error( "%s: Exception occurred when unsetting environ key '%s': '%s'", __name__, key, exc, ) return False else: val = "" if isinstance(val, str): try: os.environ[key] = val if permanent and is_windows: __utils__["reg.set_value"](permanent_hive, permanent_key, key, val) __utils__["win_functions.broadcast_setting_change"]() return os.environ[key] except Exception as exc: # pylint: disable=broad-except log.error( "%s: Exception occurred when setting environ key '%s': '%s'", __name__, key, exc, ) return False else: log.debug( "%s: 'val' argument for key '%s' is not a string or False: '%s'", __name__, key, val, ) return False def setenv( environ, false_unsets=False, clear_all=False, update_minion=False, permanent=False ): """ Set multiple salt process environment variables from a dict. Returns a dict. environ Must be a dict. The top-level keys of the dict are the names of the environment variables to set. Each key's value must be a string or False. Refer to the 'false_unsets' parameter for behavior when a value set to False. false_unsets If a key's value is False and false_unsets is True, then the key will be removed from the salt processes environment dict entirely. If a key's value is False and false_unsets is not True, then the key's value will be set to an empty string. Default: False clear_all USE WITH CAUTION! This option can unset environment variables needed for salt to function properly. If clear_all is True, then any environment variables not defined in the environ dict will be deleted. Default: False update_minion If True, apply these environ changes to the main salt-minion process. If False, the environ changes will only affect the current salt subprocess. Default: False permanent On Windows minions this will set the environment variable in the registry so that it is always added as an environment variable when applications open. If you want to set the variable to HKLM instead of HKCU just pass in "HKLM" for this parameter. On all other minion types this will be ignored. Note: This will only take affect on applications opened after this has been set. CLI Example: .. code-block:: bash salt '*' environ.setenv '{"foo": "bar", "baz": "quux"}' salt '*' environ.setenv '{"a": "b", "c": False}' false_unsets=True """ ret = {} if not isinstance(environ, dict): log.debug("%s: 'environ' argument is not a dict: '%s'", __name__, environ) return False if clear_all is True: # Unset any keys not defined in 'environ' dict supplied by user to_unset = [key for key in os.environ if key not in environ] for key in to_unset: ret[key] = setval(key, False, false_unsets, permanent=permanent) for key, val in environ.items(): if isinstance(val, str): ret[key] = setval(key, val, permanent=permanent) elif val is False: ret[key] = setval(key, val, false_unsets, permanent=permanent) else: log.debug( "%s: 'val' argument for key '%s' is not a string or False: '%s'", __name__, key, val, ) return False if update_minion is True: __salt__["event.fire"]( { "environ": environ, "false_unsets": false_unsets, "clear_all": clear_all, "permanent": permanent, }, "environ_setenv", ) return ret def get(key, default=""): """ Get a single salt process environment variable. key String used as the key for environment lookup. default If the key is not found in the environment, return this value. Default: '' CLI Example: .. code-block:: bash salt '*' environ.get foo salt '*' environ.get baz default=False """ if not isinstance(key, str): log.debug("%s: 'key' argument is not a string type: '%s'", __name__, key) return False return os.environ.get(key, default) def has_value(key, value=None): """ Determine whether the key exists in the current salt process environment dictionary. Optionally compare the current value of the environment against the supplied value string. key Must be a string. Used as key for environment lookup. value: Optional. If key exists in the environment, compare the current value with this value. Return True if they are equal. CLI Example: .. code-block:: bash salt '*' environ.has_value foo """ if not isinstance(key, str): log.debug("%s: 'key' argument is not a string type: '%s'", __name__, key) return False try: cur_val = os.environ[key] if value is not None: if cur_val == value: return True else: return False except KeyError: return False return True def item(keys, default=""): """ Get one or more salt process environment variables. Returns a dict. keys Either a string or a list of strings that will be used as the keys for environment lookup. default If the key is not found in the environment, return this value. Default: '' CLI Example: .. code-block:: bash salt '*' environ.item foo salt '*' environ.item '[foo, baz]' default=None """ ret = {} key_list = [] if isinstance(keys, str): key_list.append(keys) elif isinstance(keys, list): key_list = keys else: log.debug( "%s: 'keys' argument is not a string or list type: '%s'", __name__, keys ) for key in key_list: ret[key] = os.environ.get(key, default) return ret def items(): """ Return a dict of the entire environment set for the salt process CLI Example: .. code-block:: bash salt '*' environ.items """ return dict(os.environ)
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/environ.py
0.631822
0.184694
environ.py
pypi
import logging import time import salt.utils.compat import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError log = logging.getLogger(__name__) # pylint: disable=import-error try: # pylint: disable=unused-import import boto import boto3 # pylint: enable=unused-import from botocore.exceptions import ClientError logging.getLogger("boto").setLevel(logging.CRITICAL) logging.getLogger("boto3").setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error boto3_param_map = { "allocated_storage": ("AllocatedStorage", int), "allow_major_version_upgrade": ("AllowMajorVersionUpgrade", bool), "apply_immediately": ("ApplyImmediately", bool), "auto_minor_version_upgrade": ("AutoMinorVersionUpgrade", bool), "availability_zone": ("AvailabilityZone", str), "backup_retention_period": ("BackupRetentionPeriod", int), "ca_certificate_identifier": ("CACertificateIdentifier", str), "character_set_name": ("CharacterSetName", str), "copy_tags_to_snapshot": ("CopyTagsToSnapshot", bool), "db_cluster_identifier": ("DBClusterIdentifier", str), "db_instance_class": ("DBInstanceClass", str), "db_name": ("DBName", str), "db_parameter_group_name": ("DBParameterGroupName", str), "db_port_number": ("DBPortNumber", int), "db_security_groups": ("DBSecurityGroups", list), "db_subnet_group_name": ("DBSubnetGroupName", str), "domain": ("Domain", str), "domain_iam_role_name": ("DomainIAMRoleName", str), "engine": ("Engine", str), "engine_version": ("EngineVersion", str), "iops": ("Iops", int), "kms_key_id": ("KmsKeyId", str), "license_model": ("LicenseModel", str), "master_user_password": ("MasterUserPassword", str), "master_username": ("MasterUsername", str), "monitoring_interval": ("MonitoringInterval", int), "monitoring_role_arn": ("MonitoringRoleArn", str), "multi_az": ("MultiAZ", bool), "name": ("DBInstanceIdentifier", str), "new_db_instance_identifier": ("NewDBInstanceIdentifier", str), "option_group_name": ("OptionGroupName", str), "port": ("Port", int), "preferred_backup_window": ("PreferredBackupWindow", str), "preferred_maintenance_window": ("PreferredMaintenanceWindow", str), "promotion_tier": ("PromotionTier", int), "publicly_accessible": ("PubliclyAccessible", bool), "storage_encrypted": ("StorageEncrypted", bool), "storage_type": ("StorageType", str), "tags": ("Tags", list), "tde_credential_arn": ("TdeCredentialArn", str), "tde_credential_password": ("TdeCredentialPassword", str), "vpc_security_group_ids": ("VpcSecurityGroupIds", list), } def __virtual__(): """ Only load if boto libraries exist and if boto libraries are greater than a given version. """ return salt.utils.versions.check_boto_reqs(boto3_ver="1.3.1") def __init__(opts): if HAS_BOTO: __utils__["boto3.assign_funcs"](__name__, "rds") def exists(name, tags=None, region=None, key=None, keyid=None, profile=None): """ Check to see if an RDS exists. CLI Example: .. code-block:: bash salt myminion boto_rds.exists myrds region=us-east-1 """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: rds = conn.describe_db_instances(DBInstanceIdentifier=name) return {"exists": bool(rds)} except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def option_group_exists( name, tags=None, region=None, key=None, keyid=None, profile=None ): """ Check to see if an RDS option group exists. CLI Example: .. code-block:: bash salt myminion boto_rds.option_group_exists myoptiongr region=us-east-1 """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: rds = conn.describe_option_groups(OptionGroupName=name) return {"exists": bool(rds)} except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def parameter_group_exists( name, tags=None, region=None, key=None, keyid=None, profile=None ): """ Check to see if an RDS parameter group exists. CLI Example: .. code-block:: bash salt myminion boto_rds.parameter_group_exists myparametergroup \ region=us-east-1 """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: rds = conn.describe_db_parameter_groups(DBParameterGroupName=name) return {"exists": bool(rds), "error": None} except ClientError as e: resp = {} if e.response["Error"]["Code"] == "DBParameterGroupNotFound": resp["exists"] = False resp["error"] = __utils__["boto3.get_error"](e) return resp def subnet_group_exists( name, tags=None, region=None, key=None, keyid=None, profile=None ): """ Check to see if an RDS subnet group exists. CLI Example: .. code-block:: bash salt myminion boto_rds.subnet_group_exists my-param-group \ region=us-east-1 """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return {"exists": bool(conn)} rds = conn.describe_db_subnet_groups(DBSubnetGroupName=name) return {"exists": bool(rds)} except ClientError as e: if "DBSubnetGroupNotFoundFault" in e.message: return {"exists": False} else: return {"error": __utils__["boto3.get_error"](e)} def create( name, allocated_storage, db_instance_class, engine, master_username, master_user_password, db_name=None, db_security_groups=None, vpc_security_group_ids=None, vpc_security_groups=None, availability_zone=None, db_subnet_group_name=None, preferred_maintenance_window=None, db_parameter_group_name=None, backup_retention_period=None, preferred_backup_window=None, port=None, multi_az=None, engine_version=None, auto_minor_version_upgrade=None, license_model=None, iops=None, option_group_name=None, character_set_name=None, publicly_accessible=None, wait_status=None, tags=None, db_cluster_identifier=None, storage_type=None, tde_credential_arn=None, tde_credential_password=None, storage_encrypted=None, kms_key_id=None, domain=None, copy_tags_to_snapshot=None, monitoring_interval=None, monitoring_role_arn=None, domain_iam_role_name=None, region=None, promotion_tier=None, key=None, keyid=None, profile=None, ): """ Create an RDS Instance CLI example to create an RDS Instance:: salt myminion boto_rds.create myrds 10 db.t2.micro MySQL sqlusr sqlpassw """ if not allocated_storage: raise SaltInvocationError("allocated_storage is required") if not db_instance_class: raise SaltInvocationError("db_instance_class is required") if not engine: raise SaltInvocationError("engine is required") if not master_username: raise SaltInvocationError("master_username is required") if not master_user_password: raise SaltInvocationError("master_user_password is required") if availability_zone and multi_az: raise SaltInvocationError( "availability_zone and multi_az are mutually exclusive arguments." ) if wait_status: wait_stati = ["available", "modifying", "backing-up"] if wait_status not in wait_stati: raise SaltInvocationError( "wait_status can be one of: {}".format(wait_stati) ) if vpc_security_groups: v_tmp = __salt__["boto_secgroup.convert_to_group_ids"]( groups=vpc_security_groups, region=region, key=key, keyid=keyid, profile=profile, ) vpc_security_group_ids = ( vpc_security_group_ids + v_tmp if vpc_security_group_ids else v_tmp ) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return {"results": bool(conn)} kwargs = {} boto_params = set(boto3_param_map.keys()) keys = set(locals().keys()) tags = _tag_doc(tags) for param_key in keys.intersection(boto_params): val = locals()[param_key] if val is not None: mapped = boto3_param_map[param_key] kwargs[mapped[0]] = mapped[1](val) # Validation doesn't want parameters that are None # https://github.com/boto/boto3/issues/400 kwargs = {k: v for k, v in kwargs.items() if v is not None} rds = conn.create_db_instance(**kwargs) if not rds: return {"created": False} if not wait_status: return { "created": True, "message": "RDS instance {} created.".format(name), } while True: jmespath = "DBInstances[*].DBInstanceStatus" status = describe_db_instances( name=name, jmespath=jmespath, region=region, key=key, keyid=keyid, profile=profile, ) if status: stat = status[0] else: # Whoops, something is horribly wrong... return { "created": False, "error": ( "RDS instance {} should have been created but" " now I can't find it.".format(name) ), } if stat == wait_status: return { "created": True, "message": "RDS instance {} created (current status {})".format( name, stat ), } time.sleep(10) log.info("Instance status after 10 seconds is: %s", stat) except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def create_read_replica( name, source_name, db_instance_class=None, availability_zone=None, port=None, auto_minor_version_upgrade=None, iops=None, option_group_name=None, publicly_accessible=None, tags=None, db_subnet_group_name=None, storage_type=None, copy_tags_to_snapshot=None, monitoring_interval=None, monitoring_role_arn=None, region=None, key=None, keyid=None, profile=None, ): """ Create an RDS read replica CLI example to create an RDS read replica:: salt myminion boto_rds.create_read_replica replicaname source_name """ if not backup_retention_period: raise SaltInvocationError("backup_retention_period is required") res = __salt__["boto_rds.exists"](source_name, tags, region, key, keyid, profile) if not res.get("exists"): return { "exists": bool(res), "message": "RDS instance source {} does not exists.".format(source_name), } res = __salt__["boto_rds.exists"](name, tags, region, key, keyid, profile) if res.get("exists"): return { "exists": bool(res), "message": "RDS replica instance {} already exists.".format(name), } try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) kwargs = {} for key in ("OptionGroupName", "MonitoringRoleArn"): if locals()[key] is not None: kwargs[key] = str(locals()[key]) for key in ("MonitoringInterval", "Iops", "Port"): if locals()[key] is not None: kwargs[key] = int(locals()[key]) for key in ("CopyTagsToSnapshot", "AutoMinorVersionUpgrade"): if locals()[key] is not None: kwargs[key] = bool(locals()[key]) taglist = _tag_doc(tags) rds_replica = conn.create_db_instance_read_replica( DBInstanceIdentifier=name, SourceDBInstanceIdentifier=source_name, DBInstanceClass=db_instance_class, AvailabilityZone=availability_zone, PubliclyAccessible=publicly_accessible, Tags=taglist, DBSubnetGroupName=db_subnet_group_name, StorageType=storage_type, **kwargs ) return {"exists": bool(rds_replica)} except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def create_option_group( name, engine_name, major_engine_version, option_group_description, tags=None, region=None, key=None, keyid=None, profile=None, ): """ Create an RDS option group CLI example to create an RDS option group:: salt myminion boto_rds.create_option_group my-opt-group mysql 5.6 \ "group description" """ res = __salt__["boto_rds.option_group_exists"]( name, tags, region, key, keyid, profile ) if res.get("exists"): return {"exists": bool(res)} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return {"results": bool(conn)} taglist = _tag_doc(tags) rds = conn.create_option_group( OptionGroupName=name, EngineName=engine_name, MajorEngineVersion=major_engine_version, OptionGroupDescription=option_group_description, Tags=taglist, ) return {"exists": bool(rds)} except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def create_parameter_group( name, db_parameter_group_family, description, tags=None, region=None, key=None, keyid=None, profile=None, ): """ Create an RDS parameter group CLI example to create an RDS parameter group:: salt myminion boto_rds.create_parameter_group my-param-group mysql5.6 \ "group description" """ res = __salt__["boto_rds.parameter_group_exists"]( name, tags, region, key, keyid, profile ) if res.get("exists"): return {"exists": bool(res)} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return {"results": bool(conn)} taglist = _tag_doc(tags) rds = conn.create_db_parameter_group( DBParameterGroupName=name, DBParameterGroupFamily=db_parameter_group_family, Description=description, Tags=taglist, ) if not rds: return { "created": False, "message": "Failed to create RDS parameter group {}".format(name), } return { "exists": bool(rds), "message": "Created RDS parameter group {}".format(name), } except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def create_subnet_group( name, description, subnet_ids, tags=None, region=None, key=None, keyid=None, profile=None, ): """ Create an RDS subnet group CLI example to create an RDS subnet group:: salt myminion boto_rds.create_subnet_group my-subnet-group \ "group description" '[subnet-12345678, subnet-87654321]' \ region=us-east-1 """ res = __salt__["boto_rds.subnet_group_exists"]( name, tags, region, key, keyid, profile ) if res.get("exists"): return {"exists": bool(res)} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return {"results": bool(conn)} taglist = _tag_doc(tags) rds = conn.create_db_subnet_group( DBSubnetGroupName=name, DBSubnetGroupDescription=description, SubnetIds=subnet_ids, Tags=taglist, ) return {"created": bool(rds)} except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def update_parameter_group( name, parameters, apply_method="pending-reboot", tags=None, region=None, key=None, keyid=None, profile=None, ): """ Update an RDS parameter group. CLI Example: .. code-block:: bash salt myminion boto_rds.update_parameter_group my-param-group \ parameters='{"back_log":1, "binlog_cache_size":4096}' \ region=us-east-1 """ res = __salt__["boto_rds.parameter_group_exists"]( name, tags, region, key, keyid, profile ) if not res.get("exists"): return { "exists": bool(res), "message": "RDS parameter group {} does not exist.".format(name), } param_list = [] for key, value in parameters.items(): item = odict.OrderedDict() item.update({"ParameterName": key}) item.update({"ApplyMethod": apply_method}) if type(value) is bool: item.update({"ParameterValue": "on" if value else "off"}) else: item.update({"ParameterValue": str(value)}) param_list.append(item) if not param_list: return {"results": False} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return {"results": bool(conn)} res = conn.modify_db_parameter_group( DBParameterGroupName=name, Parameters=param_list ) return {"results": bool(res)} except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def describe(name, tags=None, region=None, key=None, keyid=None, profile=None): """ Return RDS instance details. CLI Example: .. code-block:: bash salt myminion boto_rds.describe myrds """ res = __salt__["boto_rds.exists"](name, tags, region, key, keyid, profile) if not res.get("exists"): return { "exists": bool(res), "message": "RDS instance {} does not exist.".format(name), } try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return {"results": bool(conn)} rds = conn.describe_db_instances(DBInstanceIdentifier=name) rds = [ i for i in rds.get("DBInstances", []) if i.get("DBInstanceIdentifier") == name ].pop(0) if rds: keys = ( "DBInstanceIdentifier", "DBInstanceClass", "Engine", "DBInstanceStatus", "DBName", "AllocatedStorage", "PreferredBackupWindow", "BackupRetentionPeriod", "AvailabilityZone", "PreferredMaintenanceWindow", "LatestRestorableTime", "EngineVersion", "AutoMinorVersionUpgrade", "LicenseModel", "Iops", "CharacterSetName", "PubliclyAccessible", "StorageType", "TdeCredentialArn", "DBInstancePort", "DBClusterIdentifier", "StorageEncrypted", "KmsKeyId", "DbiResourceId", "CACertificateIdentifier", "CopyTagsToSnapshot", "MonitoringInterval", "MonitoringRoleArn", "PromotionTier", "DomainMemberships", ) return {"rds": {k: rds.get(k) for k in keys}} else: return {"rds": None} except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} except IndexError: return {"rds": None} def describe_db_instances( name=None, filters=None, jmespath="DBInstances", region=None, key=None, keyid=None, profile=None, ): """ Return a detailed listing of some, or all, DB Instances visible in the current scope. Arbitrary subelements or subsections of the returned dataset can be selected by passing in a valid JMSEPath filter as well. CLI Example: .. code-block:: bash salt myminion boto_rds.describe_db_instances jmespath='DBInstances[*].DBInstanceIdentifier' """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) pag = conn.get_paginator("describe_db_instances") args = {} args.update({"DBInstanceIdentifier": name}) if name else None args.update({"Filters": filters}) if filters else None pit = pag.paginate(**args) pit = pit.search(jmespath) if jmespath else pit try: return [p for p in pit] except ClientError as e: code = getattr(e, "response", {}).get("Error", {}).get("Code") if code != "DBInstanceNotFound": log.error(__utils__["boto3.get_error"](e)) return [] def describe_db_subnet_groups( name=None, filters=None, jmespath="DBSubnetGroups", region=None, key=None, keyid=None, profile=None, ): """ Return a detailed listing of some, or all, DB Subnet Groups visible in the current scope. Arbitrary subelements or subsections of the returned dataset can be selected by passing in a valid JMSEPath filter as well. CLI Example: .. code-block:: bash salt myminion boto_rds.describe_db_subnet_groups """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) pag = conn.get_paginator("describe_db_subnet_groups") args = {} args.update({"DBSubnetGroupName": name}) if name else None args.update({"Filters": filters}) if filters else None pit = pag.paginate(**args) pit = pit.search(jmespath) if jmespath else pit return [p for p in pit] def get_endpoint(name, tags=None, region=None, key=None, keyid=None, profile=None): """ Return the endpoint of an RDS instance. CLI Example: .. code-block:: bash salt myminion boto_rds.get_endpoint myrds """ endpoint = False res = __salt__["boto_rds.exists"](name, tags, region, key, keyid, profile) if res.get("exists"): try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: rds = conn.describe_db_instances(DBInstanceIdentifier=name) if rds and "Endpoint" in rds["DBInstances"][0]: endpoint = rds["DBInstances"][0]["Endpoint"]["Address"] return endpoint except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} return endpoint def delete( name, skip_final_snapshot=None, final_db_snapshot_identifier=None, region=None, key=None, keyid=None, profile=None, tags=None, wait_for_deletion=True, timeout=180, ): """ Delete an RDS instance. CLI Example: .. code-block:: bash salt myminion boto_rds.delete myrds skip_final_snapshot=True \ region=us-east-1 """ if timeout == 180 and not skip_final_snapshot: timeout = 420 if not skip_final_snapshot and not final_db_snapshot_identifier: raise SaltInvocationError( "At least one of the following must" " be specified: skip_final_snapshot" " final_db_snapshot_identifier" ) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return {"deleted": bool(conn)} kwargs = {} if locals()["skip_final_snapshot"] is not None: kwargs["SkipFinalSnapshot"] = bool(locals()["skip_final_snapshot"]) if locals()["final_db_snapshot_identifier"] is not None: kwargs["FinalDBSnapshotIdentifier"] = str( locals()["final_db_snapshot_identifier"] ) res = conn.delete_db_instance(DBInstanceIdentifier=name, **kwargs) if not wait_for_deletion: return { "deleted": bool(res), "message": "Deleted RDS instance {}.".format(name), } start_time = time.time() while True: res = __salt__["boto_rds.exists"]( name=name, tags=tags, region=region, key=key, keyid=keyid, profile=profile, ) if not res.get("exists"): return { "deleted": bool(res), "message": "Deleted RDS instance {} completely.".format(name), } if time.time() - start_time > timeout: raise SaltInvocationError( "RDS instance {} has not been " "deleted completely after {} " "seconds".format(name, timeout) ) log.info( "Waiting up to %s seconds for RDS instance %s to be deleted.", timeout, name, ) time.sleep(10) except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def delete_option_group(name, region=None, key=None, keyid=None, profile=None): """ Delete an RDS option group. CLI Example: .. code-block:: bash salt myminion boto_rds.delete_option_group my-opt-group \ region=us-east-1 """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return {"deleted": bool(conn)} res = conn.delete_option_group(OptionGroupName=name) if not res: return { "deleted": bool(res), "message": "Failed to delete RDS option group {}.".format(name), } return { "deleted": bool(res), "message": "Deleted RDS option group {}.".format(name), } except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def delete_parameter_group(name, region=None, key=None, keyid=None, profile=None): """ Delete an RDS parameter group. CLI Example: .. code-block:: bash salt myminion boto_rds.delete_parameter_group my-param-group \ region=us-east-1 """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return {"results": bool(conn)} r = conn.delete_db_parameter_group(DBParameterGroupName=name) return { "deleted": bool(r), "message": "Deleted RDS parameter group {}.".format(name), } except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def delete_subnet_group(name, region=None, key=None, keyid=None, profile=None): """ Delete an RDS subnet group. CLI Example: .. code-block:: bash salt myminion boto_rds.delete_subnet_group my-subnet-group \ region=us-east-1 """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return {"results": bool(conn)} r = conn.delete_db_subnet_group(DBSubnetGroupName=name) return { "deleted": bool(r), "message": "Deleted RDS subnet group {}.".format(name), } except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def describe_parameter_group( name, Filters=None, MaxRecords=None, Marker=None, region=None, key=None, keyid=None, profile=None, ): """ Returns a list of `DBParameterGroup` descriptions. CLI example to description of parameter group:: salt myminion boto_rds.describe_parameter_group parametergroupname\ region=us-east-1 """ res = __salt__["boto_rds.parameter_group_exists"]( name, tags=None, region=region, key=key, keyid=keyid, profile=profile ) if not res.get("exists"): return {"exists": bool(res)} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return {"results": bool(conn)} kwargs = {} for key in ("Marker", "Filters"): if locals()[key] is not None: kwargs[key] = str(locals()[key]) if locals()["MaxRecords"] is not None: kwargs["MaxRecords"] = int(locals()["MaxRecords"]) info = conn.describe_db_parameter_groups(DBParameterGroupName=name, **kwargs) if not info: return { "results": bool(info), "message": "Failed to get RDS description for group {}.".format(name), } return { "results": bool(info), "message": "Got RDS descrition for group {}.".format(name), } except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def describe_parameters( name, Source=None, MaxRecords=None, Marker=None, region=None, key=None, keyid=None, profile=None, ): """ Returns a list of `DBParameterGroup` parameters. CLI example to description of parameters :: salt myminion boto_rds.describe_parameters parametergroupname\ region=us-east-1 """ res = __salt__["boto_rds.parameter_group_exists"]( name, tags=None, region=region, key=key, keyid=keyid, profile=profile ) if not res.get("exists"): return { "result": False, "message": "Parameter group {} does not exist".format(name), } try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return { "result": False, "message": "Could not establish a connection to RDS", } kwargs = {} kwargs.update({"DBParameterGroupName": name}) for key in ("Marker", "Source"): if locals()[key] is not None: kwargs[key] = str(locals()[key]) if locals()["MaxRecords"] is not None: kwargs["MaxRecords"] = int(locals()["MaxRecords"]) pag = conn.get_paginator("describe_db_parameters") pit = pag.paginate(**kwargs) keys = [ "ParameterName", "ParameterValue", "Description", "Source", "ApplyType", "DataType", "AllowedValues", "IsModifieable", "MinimumEngineVersion", "ApplyMethod", ] parameters = odict.OrderedDict() ret = {"result": True} for p in pit: for result in p["Parameters"]: data = odict.OrderedDict() for k in keys: data[k] = result.get(k) parameters[result.get("ParameterName")] = data ret["parameters"] = parameters return ret except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def modify_db_instance( name, allocated_storage=None, allow_major_version_upgrade=None, apply_immediately=None, auto_minor_version_upgrade=None, backup_retention_period=None, ca_certificate_identifier=None, character_set_name=None, copy_tags_to_snapshot=None, db_cluster_identifier=None, db_instance_class=None, db_name=None, db_parameter_group_name=None, db_port_number=None, db_security_groups=None, db_subnet_group_name=None, domain=None, domain_iam_role_name=None, engine_version=None, iops=None, kms_key_id=None, license_model=None, master_user_password=None, monitoring_interval=None, monitoring_role_arn=None, multi_az=None, new_db_instance_identifier=None, option_group_name=None, preferred_backup_window=None, preferred_maintenance_window=None, promotion_tier=None, publicly_accessible=None, storage_encrypted=None, storage_type=None, tde_credential_arn=None, tde_credential_password=None, vpc_security_group_ids=None, region=None, key=None, keyid=None, profile=None, ): """ Modify settings for a DB instance. CLI example to description of parameters :: salt myminion boto_rds.modify_db_instance db_instance_identifier region=us-east-1 """ res = __salt__["boto_rds.exists"]( name, tags=None, region=region, key=key, keyid=keyid, profile=profile ) if not res.get("exists"): return { "modified": False, "message": "RDS db instance {} does not exist.".format(name), } try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return {"modified": False} kwargs = {} excluded = {"name"} boto_params = set(boto3_param_map.keys()) keys = set(locals().keys()) for key in keys.intersection(boto_params).difference(excluded): val = locals()[key] if val is not None: mapped = boto3_param_map[key] kwargs[mapped[0]] = mapped[1](val) info = conn.modify_db_instance(DBInstanceIdentifier=name, **kwargs) if not info: return { "modified": bool(info), "message": "Failed to modify RDS db instance {}.".format(name), } return { "modified": bool(info), "message": "Modified RDS db instance {}.".format(name), "results": dict(info), } except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def _tag_doc(tags): taglist = [] if tags is not None: for k, v in tags.items(): if str(k).startswith("__"): continue taglist.append({"Key": str(k), "Value": str(v)}) return taglist
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/boto_rds.py
0.457379
0.171165
boto_rds.py
pypi
import logging import salt.utils.platform log = logging.getLogger(__name__) def __virtual__(): """ Only work on POSIX-like systems """ if salt.utils.platform.is_windows(): return ( False, "The extfs execution module cannot be loaded: only available on " "non-Windows systems.", ) return True def mkfs(device, fs_type, **kwargs): """ Create a file system on the specified device CLI Example: .. code-block:: bash salt '*' extfs.mkfs /dev/sda1 fs_type=ext4 opts='acl,noexec' Valid options are: * **block_size**: 1024, 2048 or 4096 * **check**: check for bad blocks * **direct**: use direct IO * **ext_opts**: extended file system options (comma-separated) * **fragment_size**: size of fragments * **force**: setting force to True will cause mke2fs to specify the -F option twice (it is already set once); this is truly dangerous * **blocks_per_group**: number of blocks in a block group * **number_of_groups**: ext4 option for a virtual block group * **bytes_per_inode**: set the bytes/inode ratio * **inode_size**: size of the inode * **journal**: set to True to create a journal (default on ext3/4) * **journal_opts**: options for the fs journal (comma separated) * **blocks_file**: read bad blocks from file * **label**: label to apply to the file system * **reserved**: percentage of blocks reserved for super-user * **last_dir**: last mounted directory * **test**: set to True to not actually create the file system (mke2fs -n) * **number_of_inodes**: override default number of inodes * **creator_os**: override "creator operating system" field * **opts**: mount options (comma separated) * **revision**: set the filesystem revision (default 1) * **super**: write superblock and group descriptors only * **fs_type**: set the filesystem type (REQUIRED) * **usage_type**: how the filesystem is going to be used * **uuid**: set the UUID for the file system See the ``mke2fs(8)`` manpage for a more complete description of these options. """ kwarg_map = { "block_size": "b", "check": "c", "direct": "D", "ext_opts": "E", "fragment_size": "f", "force": "F", "blocks_per_group": "g", "number_of_groups": "G", "bytes_per_inode": "i", "inode_size": "I", "journal": "j", "journal_opts": "J", "blocks_file": "l", "label": "L", "reserved": "m", "last_dir": "M", "test": "n", "number_of_inodes": "N", "creator_os": "o", "opts": "O", "revision": "r", "super": "S", "usage_type": "T", "uuid": "U", } opts = "" for key in kwargs: if key in kwarg_map: opt = kwarg_map[key] if kwargs[key] == "True": opts += "-{} ".format(opt) else: opts += "-{} {} ".format(opt, kwargs[key]) cmd = "mke2fs -F -t {} {}{}".format(fs_type, opts, device) out = __salt__["cmd.run"](cmd, python_shell=False).splitlines() ret = [] for line in out: if not line: continue elif line.startswith("mke2fs"): continue elif line.startswith("Discarding device blocks"): continue elif line.startswith("Allocating group tables"): continue elif line.startswith("Writing inode tables"): continue elif line.startswith("Creating journal"): continue elif line.startswith("Writing superblocks"): continue ret.append(line) return ret def tune(device, **kwargs): """ Set attributes for the specified device (using tune2fs) CLI Example: .. code-block:: bash salt '*' extfs.tune /dev/sda1 force=True label=wildstallyns opts='acl,noexec' Valid options are: * **max**: max mount count * **count**: mount count * **error**: error behavior * **extended_opts**: extended options (comma separated) * **force**: force, even if there are errors (set to True) * **group**: group name or gid that can use the reserved blocks * **interval**: interval between checks * **journal**: set to True to create a journal (default on ext3/4) * **journal_opts**: options for the fs journal (comma separated) * **label**: label to apply to the file system * **reserved**: percentage of blocks reserved for super-user * **last_dir**: last mounted directory * **opts**: mount options (comma separated) * **feature**: set or clear a feature (comma separated) * **mmp_check**: mmp check interval * **reserved**: reserved blocks count * **quota_opts**: quota options (comma separated) * **time**: time last checked * **user**: user or uid who can use the reserved blocks * **uuid**: set the UUID for the file system See the ``mke2fs(8)`` manpage for a more complete description of these options. """ kwarg_map = { "max": "c", "count": "C", "error": "e", "extended_opts": "E", "force": "f", "group": "g", "interval": "i", "journal": "j", "journal_opts": "J", "label": "L", "last_dir": "M", "opts": "o", "feature": "O", "mmp_check": "p", "reserved": "r", "quota_opts": "Q", "time": "T", "user": "u", "uuid": "U", } opts = "" for key in kwargs: if key in kwarg_map: opt = kwarg_map[key] if kwargs[key] == "True": opts += "-{} ".format(opt) else: opts += "-{} {} ".format(opt, kwargs[key]) cmd = "tune2fs {}{}".format(opts, device) out = __salt__["cmd.run"](cmd, python_shell=False).splitlines() return out def attributes(device, args=None): """ Return attributes from dumpe2fs for a specified device CLI Example: .. code-block:: bash salt '*' extfs.attributes /dev/sda1 """ fsdump = dump(device, args) return fsdump["attributes"] def blocks(device, args=None): """ Return block and inode info from dumpe2fs for a specified device CLI Example: .. code-block:: bash salt '*' extfs.blocks /dev/sda1 """ fsdump = dump(device, args) return fsdump["blocks"] def dump(device, args=None): """ Return all contents of dumpe2fs for a specified device CLI Example: .. code-block:: bash salt '*' extfs.dump /dev/sda1 """ cmd = "dumpe2fs {}".format(device) if args: cmd = cmd + " -" + args ret = {"attributes": {}, "blocks": {}} out = __salt__["cmd.run"](cmd, python_shell=False).splitlines() mode = "opts" group = None for line in out: if not line: continue if line.startswith("dumpe2fs"): continue if mode == "opts": line = line.replace("\t", " ") comps = line.split(": ") if line.startswith("Filesystem features"): ret["attributes"][comps[0]] = comps[1].split() elif line.startswith("Group") and not line.startswith( "Group descriptor size" ): mode = "blocks" else: if len(comps) < 2: continue ret["attributes"][comps[0]] = comps[1].strip() if mode == "blocks": if line.startswith("Group"): line = line.replace(":", "") line = line.replace("(", "") line = line.replace(")", "") line = line.replace("[", "") line = line.replace("]", "") comps = line.split() blkgrp = comps[1] group = "Group {}".format(blkgrp) ret["blocks"][group] = {} ret["blocks"][group]["group"] = blkgrp ret["blocks"][group]["range"] = comps[3] # TODO: comps[4:], which may look one one of the following: # ITABLE_ZEROED # INODE_UNINIT, ITABLE_ZEROED # Does anyone know what to call these? ret["blocks"][group]["extra"] = [] elif "Free blocks:" in line: comps = line.split(": ") free_blocks = comps[1].split(", ") ret["blocks"][group]["free blocks"] = free_blocks elif "Free inodes:" in line: comps = line.split(": ") inodes = comps[1].split(", ") ret["blocks"][group]["free inodes"] = inodes else: line = line.strip() ret["blocks"][group]["extra"].append(line) return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/extfs.py
0.715026
0.339718
extfs.py
pypi
import logging import time from datetime import datetime import salt.utils.platform import salt.utils.winapi from salt.exceptions import ArgumentValueError, CommandExecutionError try: import pythoncom import win32com.client HAS_DEPENDENCIES = True except ImportError: HAS_DEPENDENCIES = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = "task" # Define Constants # TASK_ACTION_TYPE TASK_ACTION_EXEC = 0 TASK_ACTION_COM_HANDLER = 5 TASK_ACTION_SEND_EMAIL = 6 TASK_ACTION_SHOW_MESSAGE = 7 # TASK_COMPATIBILITY TASK_COMPATIBILITY_AT = 0 TASK_COMPATIBILITY_V1 = 1 TASK_COMPATIBILITY_V2 = 2 TASK_COMPATIBILITY_V3 = 3 # TASK_CREATION TASK_VALIDATE_ONLY = 0x1 TASK_CREATE = 0x2 TASK_UPDATE = 0x4 TASK_CREATE_OR_UPDATE = 0x6 TASK_DISABLE = 0x8 TASK_DONT_ADD_PRINCIPAL_ACE = 0x10 TASK_IGNORE_REGISTRATION_TRIGGERS = 0x20 # TASK_INSTANCES_POLICY TASK_INSTANCES_PARALLEL = 0 TASK_INSTANCES_QUEUE = 1 TASK_INSTANCES_IGNORE_NEW = 2 TASK_INSTANCES_STOP_EXISTING = 3 # TASK_LOGON_TYPE TASK_LOGON_NONE = 0 TASK_LOGON_PASSWORD = 1 TASK_LOGON_S4U = 2 TASK_LOGON_INTERACTIVE_TOKEN = 3 TASK_LOGON_GROUP = 4 TASK_LOGON_SERVICE_ACCOUNT = 5 TASK_LOGON_INTERACTIVE_TOKEN_OR_PASSWORD = 6 # TASK_RUNLEVEL_TYPE TASK_RUNLEVEL_LUA = 0 TASK_RUNLEVEL_HIGHEST = 1 # TASK_STATE_TYPE TASK_STATE_UNKNOWN = 0 TASK_STATE_DISABLED = 1 TASK_STATE_QUEUED = 2 TASK_STATE_READY = 3 TASK_STATE_RUNNING = 4 # TASK_TRIGGER_TYPE TASK_TRIGGER_EVENT = 0 TASK_TRIGGER_TIME = 1 TASK_TRIGGER_DAILY = 2 TASK_TRIGGER_WEEKLY = 3 TASK_TRIGGER_MONTHLY = 4 TASK_TRIGGER_MONTHLYDOW = 5 TASK_TRIGGER_IDLE = 6 TASK_TRIGGER_REGISTRATION = 7 TASK_TRIGGER_BOOT = 8 TASK_TRIGGER_LOGON = 9 TASK_TRIGGER_SESSION_STATE_CHANGE = 11 duration = { "Immediately": "PT0M", "Indefinitely": "", "Do not wait": "PT0M", "15 seconds": "PT15S", "30 seconds": "PT30S", "1 minute": "PT1M", "5 minutes": "PT5M", "10 minutes": "PT10M", "15 minutes": "PT15M", "30 minutes": "PT30M", "1 hour": "PT1H", "2 hours": "PT2H", "4 hours": "PT4H", "8 hours": "PT8H", "12 hours": "PT12H", "1 day": ["P1D", "PT24H"], "3 days": ["P3D", "PT72H"], "30 days": "P30D", "90 days": "P90D", "180 days": "P180D", "365 days": "P365D", } action_types = { "Execute": TASK_ACTION_EXEC, "Email": TASK_ACTION_SEND_EMAIL, "Message": TASK_ACTION_SHOW_MESSAGE, } trigger_types = { "Event": TASK_TRIGGER_EVENT, "Once": TASK_TRIGGER_TIME, "Daily": TASK_TRIGGER_DAILY, "Weekly": TASK_TRIGGER_WEEKLY, "Monthly": TASK_TRIGGER_MONTHLY, "MonthlyDay": TASK_TRIGGER_MONTHLYDOW, "OnIdle": TASK_TRIGGER_IDLE, "OnTaskCreation": TASK_TRIGGER_REGISTRATION, "OnBoot": TASK_TRIGGER_BOOT, "OnLogon": TASK_TRIGGER_LOGON, "OnSessionChange": TASK_TRIGGER_SESSION_STATE_CHANGE, } states = { TASK_STATE_UNKNOWN: "Unknown", TASK_STATE_DISABLED: "Disabled", TASK_STATE_QUEUED: "Queued", TASK_STATE_READY: "Ready", TASK_STATE_RUNNING: "Running", } instances = { "Parallel": TASK_INSTANCES_PARALLEL, "Queue": TASK_INSTANCES_QUEUE, "No New Instance": TASK_INSTANCES_IGNORE_NEW, "Stop Existing": TASK_INSTANCES_STOP_EXISTING, } results = { 0x0: "The operation completed successfully", 0x1: "Incorrect or unknown function called", 0x2: "File not found", 0xA: "The environment is incorrect", 0x41300: "Task is ready to run at its next scheduled time", 0x41301: "Task is currently running", 0x41302: "Task is disabled", 0x41303: "Task has not yet run", 0x41304: "There are no more runs scheduled for this task", 0x41306: "Task was terminated by the user", 0x8004130F: "Credentials became corrupted", 0x8004131F: "An instance of this task is already running", 0x800710E0: "The operator or administrator has refused the request", 0x800704DD: "The service is not available (Run only when logged in?)", 0xC000013A: "The application terminated as a result of CTRL+C", 0xC06D007E: "Unknown software exception", } def __virtual__(): """ Only works on Windows systems """ if salt.utils.platform.is_windows(): if not HAS_DEPENDENCIES: log.warning("Could not load dependencies for %s", __virtualname__) return __virtualname__ return False, "Module win_task: module only works on Windows systems" def _get_date_time_format(dt_string): """ Copied from win_system.py (_get_date_time_format) Function that detects the date/time format for the string passed. :param str dt_string: A date/time string :return: The format of the passed dt_string :rtype: str """ valid_formats = [ "%I:%M:%S %p", "%I:%M %p", "%H:%M:%S", "%H:%M", "%Y-%m-%d", "%m-%d-%y", "%m-%d-%Y", "%m/%d/%y", "%m/%d/%Y", "%Y/%m/%d", ] for dt_format in valid_formats: try: datetime.strptime(dt_string, dt_format) return dt_format except ValueError: continue return False def _get_date_value(date): """ Function for dealing with PyTime values with invalid dates. ie: 12/30/1899 which is the windows task scheduler value for Never :param obj date: A PyTime object :return: A string value representing the date or the word "Never" for invalid date strings :rtype: str """ try: return "{}".format(date) except ValueError: return "Never" def _reverse_lookup(dictionary, value): """ Lookup the key in a dictionary by its value. Will return the first match. :param dict dictionary: The dictionary to search :param str value: The value to search for. :return: Returns the first key to match the value :rtype: str """ value_index = -1 for idx, dict_value in enumerate(dictionary.values()): if type(dict_value) == list: if value in dict_value: value_index = idx break elif value == dict_value: value_index = idx break return list(dictionary)[value_index] def _lookup_first(dictionary, key): """ Lookup the first value given a key. Returns the first value if the key refers to a list or the value itself. :param dict dictionary: The dictionary to search :param str key: The key to get :return: Returns the first value available for the key :rtype: str """ value = dictionary[key] if type(value) == list: return value[0] else: return value def _save_task_definition( name, task_folder, task_definition, user_name, password, logon_type ): """ Internal function to save the task definition. :param str name: The name of the task. :param str task_folder: The object representing the folder in which to save the task :param str task_definition: The object representing the task to be saved :param str user_name: The user_account under which to run the task :param str password: The password that corresponds to the user account :param int logon_type: The logon type for the task. :return: True if successful, False if not :rtype: bool """ try: task_folder.RegisterTaskDefinition( name, task_definition, TASK_CREATE_OR_UPDATE, user_name, password, logon_type, ) return True except pythoncom.com_error as error: hr, msg, exc, arg = error.args # pylint: disable=W0633 fc = { -2147024773: ( "The filename, directory name, or volume label syntax is incorrect" ), -2147024894: "The system cannot find the file specified", -2147216615: "Required element or attribute missing", -2147216616: "Value incorrectly formatted or out of range", -2147352571: "Access denied", } try: failure_code = fc[exc[5]] except KeyError: failure_code = "Unknown Failure: {}".format(error) log.debug("Failed to modify task: %s", failure_code) return "Failed to modify task: {}".format(failure_code) def list_tasks(location="\\"): r""" List all tasks located in a specific location in the task scheduler. Args: location (str): A string value representing the folder from which you want to list tasks. Default is ``\`` which is the root for the task scheduler (``C:\Windows\System32\tasks``). Returns: list: Returns a list of tasks CLI Example: .. code-block:: bash # List all tasks in the default location salt 'minion-id' task.list_tasks # List all tasks in the Microsoft\XblGameSave Directory salt 'minion-id' task.list_tasks Microsoft\XblGameSave """ # Create the task service object with salt.utils.winapi.Com(): task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() # Get the folder to list tasks from task_folder = task_service.GetFolder(location) tasks = task_folder.GetTasks(0) ret = [] for task in tasks: ret.append(task.Name) return ret def list_folders(location="\\"): r""" List all folders located in a specific location in the task scheduler. Args: location (str): A string value representing the folder from which you want to list tasks. Default is ``\`` which is the root for the task scheduler (``C:\Windows\System32\tasks``). Returns: list: Returns a list of folders. CLI Example: .. code-block:: bash # List all folders in the default location salt 'minion-id' task.list_folders # List all folders in the Microsoft directory salt 'minion-id' task.list_folders Microsoft """ # Create the task service object with salt.utils.winapi.Com(): task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() # Get the folder to list folders from task_folder = task_service.GetFolder(location) folders = task_folder.GetFolders(0) ret = [] for folder in folders: ret.append(folder.Name) return ret def list_triggers(name, location="\\"): r""" List all triggers that pertain to a task in the specified location. Args: name (str): The name of the task for which list triggers. location (str): A string value representing the location of the task from which to list triggers. Default is ``\`` which is the root for the task scheduler (``C:\Windows\System32\tasks``). Returns: list: Returns a list of triggers. CLI Example: .. code-block:: bash # List all triggers for a task in the default location salt 'minion-id' task.list_triggers <task_name> # List all triggers for the XblGameSaveTask in the Microsoft\XblGameSave # location salt '*' task.list_triggers XblGameSaveTask Microsoft\XblGameSave """ # Create the task service object with salt.utils.winapi.Com(): task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() # Get the folder to list folders from task_folder = task_service.GetFolder(location) task_definition = task_folder.GetTask(name).Definition triggers = task_definition.Triggers ret = [] for trigger in triggers: ret.append(trigger.Id) return ret def list_actions(name, location="\\"): r""" List all actions that pertain to a task in the specified location. Args: name (str): The name of the task for which list actions. location (str): A string value representing the location of the task from which to list actions. Default is ``\`` which is the root for the task scheduler (``C:\Windows\System32\tasks``). Returns: list: Returns a list of actions. CLI Example: .. code-block:: bash # List all actions for a task in the default location salt 'minion-id' task.list_actions <task_name> # List all actions for the XblGameSaveTask in the Microsoft\XblGameSave # location salt 'minion-id' task.list_actions XblGameSaveTask Microsoft\XblGameSave """ # Create the task service object with salt.utils.winapi.Com(): task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() # Get the folder to list folders from task_folder = task_service.GetFolder(location) task_definition = task_folder.GetTask(name).Definition actions = task_definition.Actions ret = [] for action in actions: ret.append(action.Id) return ret def create_task( name, location="\\", user_name="System", password=None, force=False, **kwargs ): r""" Create a new task in the designated location. This function has many keyword arguments that are not listed here. For additional arguments see: - :py:func:`edit_task` - :py:func:`add_action` - :py:func:`add_trigger` Args: name (str): The name of the task. This will be displayed in the task scheduler. location (str): A string value representing the location in which to create the task. Default is ``\`` which is the root for the task scheduler (``C:\Windows\System32\tasks``). user_name (str): The user account under which to run the task. To specify the 'System' account, use 'System'. The password will be ignored. password (str): The password to use for authentication. This should set the task to run whether the user is logged in or not, but is currently not working. force (bool): If the task exists, overwrite the existing task. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' task.create_task <task_name> user_name=System force=True action_type=Execute cmd='del /Q /S C:\\Temp' trigger_type=Once start_date=2016-12-1 start_time=01:00 """ # Check for existing task if name in list_tasks(location) and not force: # Connect to an existing task definition return "{} already exists".format(name) # connect to the task scheduler with salt.utils.winapi.Com(): task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() # Create a new task definition task_definition = task_service.NewTask(0) # Modify task settings edit_task( task_definition=task_definition, user_name=user_name, password=password, **kwargs ) # Add Action add_action(task_definition=task_definition, **kwargs) # Add Trigger add_trigger(task_definition=task_definition, **kwargs) # get the folder to create the task in task_folder = task_service.GetFolder(location) # Save the task _save_task_definition( name=name, task_folder=task_folder, task_definition=task_definition, user_name=task_definition.Principal.UserID, password=password, logon_type=task_definition.Principal.LogonType, ) # Verify task was created return name in list_tasks(location) def create_task_from_xml( name, location="\\", xml_text=None, xml_path=None, user_name="System", password=None ): r""" Create a task based on XML. Source can be a file or a string of XML. Args: name (str): The name of the task. This will be displayed in the task scheduler. location (str): A string value representing the location in which to create the task. Default is ``\`` which is the root for the task scheduler (``C:\Windows\System32\tasks``). xml_text (str): A string of xml representing the task to be created. This will be overridden by ``xml_path`` if passed. xml_path (str): The path to an XML file on the local system containing the xml that defines the task. This will override ``xml_text`` user_name (str): The user account under which to run the task. To specify the 'System' account, use 'System'. The password will be ignored. password (str): The password to use for authentication. This should set the task to run whether the user is logged in or not, but is currently not working. Returns: bool: ``True`` if successful, otherwise ``False`` str: A string with the error message if there is an error Raises: ArgumentValueError: If arguments are invalid CommandExecutionError CLI Example: .. code-block:: bash salt '*' task.create_task_from_xml <task_name> xml_path=C:\task.xml """ # Check for existing task if name in list_tasks(location): # Connect to an existing task definition return "{} already exists".format(name) if not xml_text and not xml_path: raise ArgumentValueError("Must specify either xml_text or xml_path") # Create the task service object with salt.utils.winapi.Com(): task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() # Load xml from file, overrides xml_text # Need to figure out how to load contents of xml if xml_path: xml_text = xml_path # Get the folder to list folders from task_folder = task_service.GetFolder(location) # Determine logon type if user_name: if user_name.lower() == "system": logon_type = TASK_LOGON_SERVICE_ACCOUNT user_name = "SYSTEM" password = None else: if password: logon_type = TASK_LOGON_PASSWORD else: logon_type = TASK_LOGON_INTERACTIVE_TOKEN else: password = None logon_type = TASK_LOGON_NONE # Save the task try: task_folder.RegisterTask( name, xml_text, TASK_CREATE, user_name, password, logon_type ) except pythoncom.com_error as error: hr, msg, exc, arg = error.args # pylint: disable=W0633 error_code = hex(exc[5] + 2 ** 32) fc = { 0x80041319: "Required element or attribute missing", 0x80041318: "Value incorrectly formatted or out of range", 0x80020005: "Access denied", 0x80041309: "A task's trigger is not found", 0x8004130A: ( "One or more of the properties required to run this " "task have not been set" ), 0x8004130C: ( "The Task Scheduler service is not installed on this computer" ), 0x8004130D: "The task object could not be opened", 0x8004130E: ( "The object is either an invalid task object or is not " "a task object" ), 0x8004130F: ( "No account information could be found in the Task " "Scheduler security database for the task indicated" ), 0x80041310: "Unable to establish existence of the account specified", 0x80041311: ( "Corruption was detected in the Task Scheduler " "security database; the database has been reset" ), 0x80041313: "The task object version is either unsupported or invalid", 0x80041314: ( "The task has been configured with an unsupported " "combination of account settings and run time options" ), 0x80041315: "The Task Scheduler Service is not running", 0x80041316: "The task XML contains an unexpected node", 0x80041317: ( "The task XML contains an element or attribute from an " "unexpected namespace" ), 0x8004131A: "The task XML is malformed", 0x0004131C: ( "The task is registered, but may fail to start. Batch " "logon privilege needs to be enabled for the task principal" ), 0x8004131D: "The task XML contains too many nodes of the same type", } try: failure_code = fc[error_code] except KeyError: failure_code = "Unknown Failure: {}".format(error_code) finally: log.debug("Failed to create task: %s", failure_code) raise CommandExecutionError(failure_code) # Verify creation return name in list_tasks(location) def create_folder(name, location="\\"): r""" Create a folder in which to create tasks. Args: name (str): The name of the folder. This will be displayed in the task scheduler. location (str): A string value representing the location in which to create the folder. Default is ``\`` which is the root for the task scheduler (``C:\Windows\System32\tasks``). Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' task.create_folder <folder_name> """ # Check for existing folder if name in list_folders(location): # Connect to an existing task definition return "{} already exists".format(name) # Create the task service object with salt.utils.winapi.Com(): task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() # Get the folder to list folders from task_folder = task_service.GetFolder(location) task_folder.CreateFolder(name) # Verify creation return name in list_folders(location) def edit_task( name=None, location="\\", # General Tab user_name=None, password=None, description=None, enabled=None, hidden=None, # Conditions Tab run_if_idle=None, idle_duration=None, idle_wait_timeout=None, idle_stop_on_end=None, idle_restart=None, ac_only=None, stop_if_on_batteries=None, wake_to_run=None, run_if_network=None, network_id=None, network_name=None, # Settings Tab allow_demand_start=None, start_when_available=None, restart_every=None, restart_count=3, execution_time_limit=None, force_stop=None, delete_after=None, multiple_instances=None, **kwargs ): r""" Edit the parameters of a task. Triggers and Actions cannot be edited yet. Args: name (str): The name of the task. This will be displayed in the task scheduler. location (str): A string value representing the location in which to create the task. Default is ``\`` which is the root for the task scheduler (``C:\Windows\System32\tasks``). user_name (str): The user account under which to run the task. To specify the 'System' account, use 'System'. The password will be ignored. password (str): The password to use for authentication. This should set the task to run whether the user is logged in or not, but is currently not working. .. note:: The combination of user_name and password determine how the task runs. For example, if a username is passed without at password the task will only run when the user is logged in. If a password is passed as well the task will run whether the user is logged on or not. If you pass 'System' as the username the task will run as the system account (the password parameter is ignored). description (str): A string representing the text that will be displayed in the description field in the task scheduler. enabled (bool): A boolean value representing whether or not the task is enabled. hidden (bool): A boolean value representing whether or not the task is hidden. run_if_idle (bool): Boolean value that indicates that the Task Scheduler will run the task only if the computer is in an idle state. idle_duration (str): A value that indicates the amount of time that the computer must be in an idle state before the task is run. Valid values are: - 1 minute - 5 minutes - 10 minutes - 15 minutes - 30 minutes - 1 hour idle_wait_timeout (str): A value that indicates the amount of time that the Task Scheduler will wait for an idle condition to occur. Valid values are: - Do not wait - 1 minute - 5 minutes - 10 minutes - 15 minutes - 30 minutes - 1 hour - 2 hours idle_stop_on_end (bool): Boolean value that indicates that the Task Scheduler will terminate the task if the idle condition ends before the task is completed. idle_restart (bool): Boolean value that indicates whether the task is restarted when the computer cycles into an idle condition more than once. ac_only (bool): Boolean value that indicates that the Task Scheduler will launch the task only while on AC power. stop_if_on_batteries (bool): Boolean value that indicates that the task will be stopped if the computer begins to run on battery power. wake_to_run (bool): Boolean value that indicates that the Task Scheduler will wake the computer when it is time to run the task. run_if_network (bool): Boolean value that indicates that the Task Scheduler will run the task only when a network is available. network_id (guid): GUID value that identifies a network profile. network_name (str): Sets the name of a network profile. The name is used for display purposes. allow_demand_start (bool): Boolean value that indicates that the task can be started by using either the Run command or the Context menu. start_when_available (bool): Boolean value that indicates that the Task Scheduler can start the task at any time after its scheduled time has passed. restart_every (str): A value that specifies the interval between task restart attempts. Valid values are: - False (to disable) - 1 minute - 5 minutes - 10 minutes - 15 minutes - 30 minutes - 1 hour - 2 hours restart_count (int): The number of times the Task Scheduler will attempt to restart the task. Valid values are integers 1 - 999. execution_time_limit (bool, str): The amount of time allowed to complete the task. Valid values are: - False (to disable) - 1 hour - 2 hours - 4 hours - 8 hours - 12 hours - 1 day - 3 days force_stop (bool): Boolean value that indicates that the task may be terminated by using TerminateProcess. delete_after (bool, str): The amount of time that the Task Scheduler will wait before deleting the task after it expires. Requires a trigger with an expiration date. Valid values are: - False (to disable) - Immediately - 30 days - 90 days - 180 days - 365 days multiple_instances (str): Sets the policy that defines how the Task Scheduler deals with multiple instances of the task. Valid values are: - Parallel - Queue - No New Instance - Stop Existing Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' task.edit_task <task_name> description='This task is awesome' """ # TODO: Add more detailed return for items changed with salt.utils.winapi.Com(): # Check for passed task_definition # If not passed, open a task definition for an existing task save_definition = False if kwargs.get("task_definition", False): task_definition = kwargs.get("task_definition") else: save_definition = True # Make sure a name was passed if not name: return 'Required parameter "name" not passed' # Make sure task exists to modify if name in list_tasks(location): # Connect to the task scheduler task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() # get the folder to create the task in task_folder = task_service.GetFolder(location) # Connect to an existing task definition task_definition = task_folder.GetTask(name).Definition else: # Not found and create_new not set, return not found return "{} not found".format(name) # General Information if save_definition: task_definition.RegistrationInfo.Author = "Salt Minion" task_definition.RegistrationInfo.Source = "Salt Minion Daemon" if description is not None: task_definition.RegistrationInfo.Description = description # General Information: Security Options if user_name: # Determine logon type if user_name.lower() == "system": logon_type = TASK_LOGON_SERVICE_ACCOUNT user_name = "SYSTEM" password = None else: task_definition.Principal.Id = user_name if password: logon_type = TASK_LOGON_PASSWORD else: logon_type = TASK_LOGON_INTERACTIVE_TOKEN task_definition.Principal.UserID = user_name task_definition.Principal.DisplayName = user_name task_definition.Principal.LogonType = logon_type task_definition.Principal.RunLevel = TASK_RUNLEVEL_HIGHEST else: user_name = None password = None # Settings # https://msdn.microsoft.com/en-us/library/windows/desktop/aa383480(v=vs.85).aspx if enabled is not None: task_definition.Settings.Enabled = enabled # Settings: General Tab if hidden is not None: task_definition.Settings.Hidden = hidden # Settings: Conditions Tab (Idle) # https://msdn.microsoft.com/en-us/library/windows/desktop/aa380669(v=vs.85).aspx if run_if_idle is not None: task_definition.Settings.RunOnlyIfIdle = run_if_idle if task_definition.Settings.RunOnlyIfIdle: if idle_stop_on_end is not None: task_definition.Settings.IdleSettings.StopOnIdleEnd = idle_stop_on_end if idle_restart is not None: task_definition.Settings.IdleSettings.RestartOnIdle = idle_restart if idle_duration is not None: if idle_duration in duration: task_definition.Settings.IdleSettings.IdleDuration = _lookup_first( duration, idle_duration ) else: return 'Invalid value for "idle_duration"' if idle_wait_timeout is not None: if idle_wait_timeout in duration: task_definition.Settings.IdleSettings.WaitTimeout = _lookup_first( duration, idle_wait_timeout ) else: return 'Invalid value for "idle_wait_timeout"' # Settings: Conditions Tab (Power) if ac_only is not None: task_definition.Settings.DisallowStartIfOnBatteries = ac_only if stop_if_on_batteries is not None: task_definition.Settings.StopIfGoingOnBatteries = stop_if_on_batteries if wake_to_run is not None: task_definition.Settings.WakeToRun = wake_to_run # Settings: Conditions Tab (Network) # https://msdn.microsoft.com/en-us/library/windows/desktop/aa382067(v=vs.85).aspx if run_if_network is not None: task_definition.Settings.RunOnlyIfNetworkAvailable = run_if_network if task_definition.Settings.RunOnlyIfNetworkAvailable: if network_id: task_definition.Settings.NetworkSettings.Id = network_id if network_name: task_definition.Settings.NetworkSettings.Name = network_name # Settings: Settings Tab if allow_demand_start is not None: task_definition.Settings.AllowDemandStart = allow_demand_start if start_when_available is not None: task_definition.Settings.StartWhenAvailable = start_when_available if restart_every is not None: if restart_every is False: task_definition.Settings.RestartInterval = "" else: if restart_every in duration: task_definition.Settings.RestartInterval = _lookup_first( duration, restart_every ) else: return 'Invalid value for "restart_every"' if task_definition.Settings.RestartInterval: if restart_count is not None: if restart_count in range(1, 999): task_definition.Settings.RestartCount = restart_count else: return '"restart_count" must be a value between 1 and 999' if execution_time_limit is not None: if execution_time_limit is False: task_definition.Settings.ExecutionTimeLimit = "PT0S" else: if execution_time_limit in duration: task_definition.Settings.ExecutionTimeLimit = _lookup_first( duration, execution_time_limit ) else: return 'Invalid value for "execution_time_limit"' if force_stop is not None: task_definition.Settings.AllowHardTerminate = force_stop if delete_after is not None: # TODO: Check triggers for end_boundary if delete_after is False: task_definition.Settings.DeleteExpiredTaskAfter = "" if delete_after in duration: task_definition.Settings.DeleteExpiredTaskAfter = _lookup_first( duration, delete_after ) else: return 'Invalid value for "delete_after"' if multiple_instances is not None: task_definition.Settings.MultipleInstances = instances[multiple_instances] # Save the task if save_definition: # Save the Changes return _save_task_definition( name=name, task_folder=task_folder, task_definition=task_definition, user_name=user_name, password=password, logon_type=task_definition.Principal.LogonType, ) def delete_task(name, location="\\"): r""" Delete a task from the task scheduler. Args: name (str): The name of the task to delete. location (str): A string value representing the location of the task. Default is ``\`` which is the root for the task scheduler (``C:\Windows\System32\tasks``). Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' task.delete_task <task_name> """ # Check for existing task if name not in list_tasks(location): return "{} not found in {}".format(name, location) # connect to the task scheduler with salt.utils.winapi.Com(): task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() # get the folder to delete the task from task_folder = task_service.GetFolder(location) task_folder.DeleteTask(name, 0) # Verify deletion return name not in list_tasks(location) def delete_folder(name, location="\\"): r""" Delete a folder from the task scheduler. Args: name (str): The name of the folder to delete. location (str): A string value representing the location of the folder. Default is ``\`` which is the root for the task scheduler (``C:\Windows\System32\tasks``). Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' task.delete_folder <folder_name> """ # Check for existing folder if name not in list_folders(location): return "{} not found in {}".format(name, location) # connect to the task scheduler with salt.utils.winapi.Com(): task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() # get the folder to delete the folder from task_folder = task_service.GetFolder(location) # Delete the folder task_folder.DeleteFolder(name, 0) # Verify deletion return name not in list_folders(location) def run(name, location="\\"): r""" Run a scheduled task manually. Args: name (str): The name of the task to run. location (str): A string value representing the location of the task. Default is ``\`` which is the root for the task scheduler (``C:\Windows\System32\tasks``). Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' task.run <task_name> """ # Check for existing folder if name not in list_tasks(location): return "{} not found in {}".format(name, location) # connect to the task scheduler with salt.utils.winapi.Com(): task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() # get the folder to delete the folder from task_folder = task_service.GetFolder(location) task = task_folder.GetTask(name) try: task.Run("") return True except pythoncom.com_error: return False def run_wait(name, location="\\"): r""" Run a scheduled task and return when the task finishes Args: name (str): The name of the task to run. location (str): A string value representing the location of the task. Default is ``\`` which is the root for the task scheduler (``C:\Windows\System32\tasks``). Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' task.run_wait <task_name> """ # Check for existing folder if name not in list_tasks(location): return "{} not found in {}".format(name, location) # connect to the task scheduler with salt.utils.winapi.Com(): task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() # get the folder to delete the folder from task_folder = task_service.GetFolder(location) task = task_folder.GetTask(name) # Is the task already running if task.State == TASK_STATE_RUNNING: return "Task already running" try: task.Run("") time.sleep(1) running = True except pythoncom.com_error: return False while running: running = False try: running_tasks = task_service.GetRunningTasks(0) if running_tasks.Count: for item in running_tasks: if item.Name == name: running = True except pythoncom.com_error: running = False return True def stop(name, location="\\"): r""" Stop a scheduled task. Args: name (str): The name of the task to stop. location (str): A string value representing the location of the task. Default is ``\`` which is the root for the task scheduler (``C:\Windows\System32\tasks``). Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' task.list_stop <task_name> """ # Check for existing folder if name not in list_tasks(location): return "{} not found in {}".format(name, location) # connect to the task scheduler with salt.utils.winapi.Com(): task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() # get the folder to delete the folder from task_folder = task_service.GetFolder(location) task = task_folder.GetTask(name) try: task.Stop(0) return True except pythoncom.com_error: return False def status(name, location="\\"): r""" Determine the status of a task. Is it Running, Queued, Ready, etc. Args: name (str): The name of the task for which to return the status location (str): A string value representing the location of the task. Default is ``\`` which is the root for the task scheduler (``C:\Windows\System32\tasks``). Returns: str: The current status of the task. Will be one of the following: - Unknown - Disabled - Queued - Ready - Running CLI Example: .. code-block:: bash salt 'minion-id' task.list_status <task_name> """ # Check for existing folder if name not in list_tasks(location): return "{} not found in {}".format(name, location) # connect to the task scheduler with salt.utils.winapi.Com(): task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() # get the folder where the task is defined task_folder = task_service.GetFolder(location) task = task_folder.GetTask(name) return states[task.State] def info(name, location="\\"): r""" Get the details about a task in the task scheduler. Args: name (str): The name of the task for which to return the status location (str): A string value representing the location of the task. Default is ``\`` which is the root for the task scheduler (``C:\Windows\System32\tasks``). Returns: dict: A dictionary containing the task configuration CLI Example: .. code-block:: bash salt 'minion-id' task.info <task_name> """ # Check for existing folder if name not in list_tasks(location): return "{} not found in {}".format(name, location) # connect to the task scheduler with salt.utils.winapi.Com(): task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() # get the folder to delete the folder from task_folder = task_service.GetFolder(location) task = task_folder.GetTask(name) properties = { "enabled": task.Enabled, "last_run": _get_date_value(task.LastRunTime), "last_run_result": results[task.LastTaskResult], "missed_runs": task.NumberOfMissedRuns, "next_run": _get_date_value(task.NextRunTime), "status": states[task.State], } def_set = task.Definition.Settings settings = { "allow_demand_start": def_set.AllowDemandStart, "force_stop": def_set.AllowHardTerminate, } if def_set.DeleteExpiredTaskAfter == "": settings["delete_after"] = False elif def_set.DeleteExpiredTaskAfter == "PT0S": settings["delete_after"] = "Immediately" else: settings["delete_after"] = _reverse_lookup( duration, def_set.DeleteExpiredTaskAfter ) if def_set.ExecutionTimeLimit == "": settings["execution_time_limit"] = False else: settings["execution_time_limit"] = _reverse_lookup( duration, def_set.ExecutionTimeLimit ) settings["multiple_instances"] = _reverse_lookup( instances, def_set.MultipleInstances ) if def_set.RestartInterval == "": settings["restart_interval"] = False else: settings["restart_interval"] = _reverse_lookup( duration, def_set.RestartInterval ) if settings["restart_interval"]: settings["restart_count"] = def_set.RestartCount settings["stop_if_on_batteries"] = def_set.StopIfGoingOnBatteries settings["wake_to_run"] = def_set.WakeToRun conditions = { "ac_only": def_set.DisallowStartIfOnBatteries, "run_if_idle": def_set.RunOnlyIfIdle, "run_if_network": def_set.RunOnlyIfNetworkAvailable, "start_when_available": def_set.StartWhenAvailable, } if conditions["run_if_idle"]: idle_set = def_set.IdleSettings conditions["idle_duration"] = idle_set.IdleDuration conditions["idle_restart"] = idle_set.RestartOnIdle conditions["idle_stop_on_end"] = idle_set.StopOnIdleEnd conditions["idle_wait_timeout"] = idle_set.WaitTimeout if conditions["run_if_network"]: net_set = def_set.NetworkSettings conditions["network_id"] = net_set.Id conditions["network_name"] = net_set.Name actions = [] for actionObj in task.Definition.Actions: action = {"action_type": _reverse_lookup(action_types, actionObj.Type)} if actionObj.Path: action["cmd"] = actionObj.Path if actionObj.Arguments: action["arguments"] = actionObj.Arguments if actionObj.WorkingDirectory: action["working_dir"] = actionObj.WorkingDirectory actions.append(action) triggers = [] for triggerObj in task.Definition.Triggers: trigger = {"trigger_type": _reverse_lookup(trigger_types, triggerObj.Type)} if triggerObj.ExecutionTimeLimit: trigger["execution_time_limit"] = _reverse_lookup( duration, triggerObj.ExecutionTimeLimit ) if triggerObj.StartBoundary: start_date, start_time = triggerObj.StartBoundary.split("T", 1) trigger["start_date"] = start_date trigger["start_time"] = start_time if triggerObj.EndBoundary: end_date, end_time = triggerObj.EndBoundary.split("T", 1) trigger["end_date"] = end_date trigger["end_time"] = end_time trigger["enabled"] = triggerObj.Enabled if hasattr(triggerObj, "RandomDelay"): if triggerObj.RandomDelay: trigger["random_delay"] = _reverse_lookup( duration, triggerObj.RandomDelay ) else: trigger["random_delay"] = False if hasattr(triggerObj, "Delay"): if triggerObj.Delay: trigger["delay"] = _reverse_lookup(duration, triggerObj.Delay) else: trigger["delay"] = False triggers.append(trigger) properties["settings"] = settings properties["conditions"] = conditions properties["actions"] = actions properties["triggers"] = triggers ret = properties return ret def add_action(name=None, location="\\", action_type="Execute", **kwargs): r""" Add an action to a task. Args: name (str): The name of the task to which to add the action. location (str): A string value representing the location of the task. Default is ``\`` which is the root for the task scheduler (``C:\Windows\System32\tasks``). action_type (str): The type of action to add. There are three action types. Each one requires its own set of Keyword Arguments (kwargs). Valid values are: - Execute - Email - Message Required arguments for each action_type: **Execute** Execute a command or an executable cmd (str): (required) The command or executable to run. arguments (str): (optional) Arguments to be passed to the command or executable. To launch a script the first command will need to be the interpreter for the script. For example, to run a vbscript you would pass ``cscript.exe`` in the ``cmd`` parameter and pass the script in the ``arguments`` parameter as follows: - ``cmd='cscript.exe' arguments='c:\scripts\myscript.vbs'`` Batch files do not need an interpreter and may be passed to the cmd parameter directly. start_in (str): (optional) The current working directory for the command. **Email** Send and email. Requires ``server``, ``from``, and ``to`` or ``cc``. from (str): The sender reply_to (str): Who to reply to to (str): The recipient cc (str): The CC recipient bcc (str): The BCC recipient subject (str): The subject of the email body (str): The Message Body of the email server (str): The server used to send the email attachments (list): A list of attachments. These will be the paths to the files to attach. ie: ``attachments="['C:\attachment1.txt', 'C:\attachment2.txt']"`` **Message** Display a dialog box. The task must be set to "Run only when user is logged on" in order for the dialog box to display. Both parameters are required. title (str): The dialog box title. message (str): The dialog box message body Returns: dict: A dictionary containing the task configuration CLI Example: .. code-block:: bash salt 'minion-id' task.add_action <task_name> cmd='del /Q /S C:\\Temp' """ with salt.utils.winapi.Com(): save_definition = False if kwargs.get("task_definition", False): task_definition = kwargs.get("task_definition") else: save_definition = True # Make sure a name was passed if not name: return 'Required parameter "name" not passed' # Make sure task exists if name in list_tasks(location): # Connect to the task scheduler task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() # get the folder to create the task in task_folder = task_service.GetFolder(location) # Connect to an existing task definition task_definition = task_folder.GetTask(name).Definition else: # Not found and create_new not set, return not found return "{} not found".format(name) # Action Settings task_action = task_definition.Actions.Create(action_types[action_type]) if action_types[action_type] == TASK_ACTION_EXEC: task_action.Id = "Execute_ID1" if kwargs.get("cmd", False): task_action.Path = kwargs.get("cmd") else: return 'Required parameter "cmd" not found' task_action.Arguments = kwargs.get("arguments", "") task_action.WorkingDirectory = kwargs.get("start_in", "") elif action_types[action_type] == TASK_ACTION_SEND_EMAIL: task_action.Id = "Email_ID1" # Required Parameters if kwargs.get("server", False): task_action.Server = kwargs.get("server") else: return 'Required parameter "server" not found' if kwargs.get("from", False): task_action.From = kwargs.get("from") else: return 'Required parameter "from" not found' if kwargs.get("to", False) or kwargs.get("cc", False): if kwargs.get("to"): task_action.To = kwargs.get("to") if kwargs.get("cc"): task_action.Cc = kwargs.get("cc") else: return 'Required parameter "to" or "cc" not found' # Optional Parameters if kwargs.get("reply_to"): task_action.ReplyTo = kwargs.get("reply_to") if kwargs.get("bcc"): task_action.Bcc = kwargs.get("bcc") if kwargs.get("subject"): task_action.Subject = kwargs.get("subject") if kwargs.get("body"): task_action.Body = kwargs.get("body") if kwargs.get("attachments"): task_action.Attachments = kwargs.get("attachments") elif action_types[action_type] == TASK_ACTION_SHOW_MESSAGE: task_action.Id = "Message_ID1" if kwargs.get("title", False): task_action.Title = kwargs.get("title") else: return 'Required parameter "title" not found' if kwargs.get("message", False): task_action.MessageBody = kwargs.get("message") else: return 'Required parameter "message" not found' # Save the task if save_definition: # Save the Changes return _save_task_definition( name=name, task_folder=task_folder, task_definition=task_definition, user_name=task_definition.Principal.UserID, password=None, logon_type=task_definition.Principal.LogonType, ) def _clear_actions(name, location="\\"): r""" Remove all actions from the task. :param str name: The name of the task from which to clear all actions. :param str location: A string value representing the location of the task. Default is ``\`` which is the root for the task scheduler (``C:\Windows\System32\tasks``). :return: True if successful, False if unsuccessful :rtype: bool """ # TODO: The problem is, you have to have at least one action for the task to # TODO: be valid, so this will always fail with a 'Required element or # TODO: attribute missing' error. # TODO: Make this an internal function that clears the functions but doesn't # TODO: save it. Then you can add a new function. Maybe for editing an # TODO: action. # Check for existing task if name not in list_tasks(location): return "{} not found in {}".format(name, location) # Create the task service object with salt.utils.winapi.Com(): task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() # Get the actions from the task task_folder = task_service.GetFolder(location) task_definition = task_folder.GetTask(name).Definition actions = task_definition.Actions actions.Clear() # Save the Changes return _save_task_definition( name=name, task_folder=task_folder, task_definition=task_definition, user_name=task_definition.Principal.UserID, password=None, logon_type=task_definition.Principal.LogonType, ) def add_trigger( name=None, location="\\", trigger_type=None, trigger_enabled=True, start_date=None, start_time=None, end_date=None, end_time=None, random_delay=None, repeat_interval=None, repeat_duration=None, repeat_stop_at_duration_end=False, execution_time_limit=None, delay=None, **kwargs ): r""" Add a trigger to a Windows Scheduled task .. note:: Arguments are parsed by the YAML loader and are subject to yaml's idiosyncrasies. Therefore, time values in some formats (``%H:%M:%S`` and ``%H:%M``) should to be quoted. See `YAML IDIOSYNCRASIES`_ for more details. .. _`YAML IDIOSYNCRASIES`: https://docs.saltproject.io/en/latest/topics/troubleshooting/yaml_idiosyncrasies.html#time-expressions Args: name (str): The name of the task to which to add the trigger. location (str): A string value representing the location of the task. Default is ``\`` which is the root for the task scheduler (``C:\Windows\System32\tasks``). trigger_type (str): The type of trigger to create. This is defined when the trigger is created and cannot be changed later. Options are as follows: - Event - Once - Daily - Weekly - Monthly - MonthlyDay - OnIdle - OnTaskCreation - OnBoot - OnLogon - OnSessionChange trigger_enabled (bool): Boolean value that indicates whether the trigger is enabled. start_date (str): The date when the trigger is activated. If no value is passed, the current date will be used. Can be one of the following formats: - %Y-%m-%d - %m-%d-%y - %m-%d-%Y - %m/%d/%y - %m/%d/%Y - %Y/%m/%d start_time (str): The time when the trigger is activated. If no value is passed, midnight will be used. Can be one of the following formats: - %I:%M:%S %p - %I:%M %p - %H:%M:%S - %H:%M end_date (str): The date when the trigger is deactivated. The trigger cannot start the task after it is deactivated. Can be one of the following formats: - %Y-%m-%d - %m-%d-%y - %m-%d-%Y - %m/%d/%y - %m/%d/%Y - %Y/%m/%d end_time (str): The time when the trigger is deactivated. If this is not passed with ``end_date`` it will be set to midnight. Can be one of the following formats: - %I:%M:%S %p - %I:%M %p - %H:%M:%S - %H:%M random_delay (str): The delay time that is randomly added to the start time of the trigger. Valid values are: - 30 seconds - 1 minute - 30 minutes - 1 hour - 8 hours - 1 day .. note:: This parameter applies to the following trigger types - Once - Daily - Weekly - Monthly - MonthlyDay repeat_interval (str): The amount of time between each restart of the task. Valid values are: - 5 minutes - 10 minutes - 15 minutes - 30 minutes - 1 hour repeat_duration (str): How long the pattern is repeated. Valid values are: - Indefinitely - 15 minutes - 30 minutes - 1 hour - 12 hours - 1 day repeat_stop_at_duration_end (bool): Boolean value that indicates if a running instance of the task is stopped at the end of the repetition pattern duration. execution_time_limit (str): The maximum amount of time that the task launched by the trigger is allowed to run. Valid values are: - 30 minutes - 1 hour - 2 hours - 4 hours - 8 hours - 12 hours - 1 day - 3 days (default) delay (str): The time the trigger waits after its activation to start the task. Valid values are: - 15 seconds - 30 seconds - 1 minute - 30 minutes - 1 hour - 8 hours - 1 day .. note:: This parameter applies to the following trigger types: - OnLogon - OnBoot - Event - OnTaskCreation - OnSessionChange **kwargs** There are optional keyword arguments determined by the type of trigger being defined. They are as follows: *Event* The trigger will be fired by an event. subscription (str): An event definition in xml format that fires the trigger. The easiest way to get this would is to create an event in Windows Task Scheduler and then copy the xml text. *Once* No special parameters required. *Daily* The task will run daily. days_interval (int): The interval between days in the schedule. An interval of 1 produces a daily schedule. An interval of 2 produces an every-other day schedule. If no interval is specified, 1 is used. Valid entries are 1 - 999. *Weekly* The task will run weekly. weeks_interval (int): The interval between weeks in the schedule. An interval of 1 produces a weekly schedule. An interval of 2 produces an every-other week schedule. If no interval is specified, 1 is used. Valid entries are 1 - 52. days_of_week (list): Sets the days of the week on which the task runs. Should be a list. ie: ``['Monday','Wednesday','Friday']``. Valid entries are the names of the days of the week. *Monthly* The task will run monthly. months_of_year (list): Sets the months of the year during which the task runs. Should be a list. ie: ``['January','July']``. Valid entries are the full names of all the months. days_of_month (list): Sets the days of the month during which the task runs. Should be a list. ie: ``[1, 15, 'Last']``. Options are all days of the month 1 - 31 and the word 'Last' to indicate the last day of the month. last_day_of_month (bool): Boolean value that indicates that the task runs on the last day of the month regardless of the actual date of that day. .. note:: You can set the task to run on the last day of the month by either including the word 'Last' in the list of days, or setting the parameter 'last_day_of_month' equal to ``True``. *MonthlyDay* The task will run monthly on the specified day. months_of_year (list): Sets the months of the year during which the task runs. Should be a list. ie: ``['January','July']``. Valid entries are the full names of all the months. weeks_of_month (list): Sets the weeks of the month during which the task runs. Should be a list. ie: ``['First','Third']``. Valid options are: - First - Second - Third - Fourth last_week_of_month (bool): Boolean value that indicates that the task runs on the last week of the month. days_of_week (list): Sets the days of the week during which the task runs. Should be a list. ie: ``['Monday','Wednesday','Friday']``. Valid entries are the names of the days of the week. *OnIdle* No special parameters required. *OnTaskCreation* No special parameters required. *OnBoot* No special parameters required. *OnLogon* No special parameters required. *OnSessionChange* The task will be triggered by a session change. session_user_name (str): Sets the user for the Terminal Server session. When a session state change is detected for this user, a task is started. To detect session status change for any user, do not pass this parameter. state_change (str): Sets the kind of Terminal Server session change that would trigger a task launch. Valid options are: - ConsoleConnect: When you connect to a user session (switch users) - ConsoleDisconnect: When you disconnect a user session (switch users) - RemoteConnect: When a user connects via Remote Desktop - RemoteDisconnect: When a user disconnects via Remote Desktop - SessionLock: When the workstation is locked - SessionUnlock: When the workstation is unlocked Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' task.add_trigger <task_name> trigger_type=Once trigger_enabled=True start_date=2016/12/1 start_time='"12:01"' """ if not trigger_type: return 'Required parameter "trigger_type" not specified' # Define lookup dictionaries state_changes = { "ConsoleConnect": 1, "ConsoleDisconnect": 2, "RemoteConnect": 3, "RemoteDisconnect": 4, "SessionLock": 7, "SessionUnlock": 8, } days = { 1: 0x1, 2: 0x2, 3: 0x4, 4: 0x8, 5: 0x10, 6: 0x20, 7: 0x40, 8: 0x80, 9: 0x100, 10: 0x200, 11: 0x400, 12: 0x800, 13: 0x1000, 14: 0x2000, 15: 0x4000, 16: 0x8000, 17: 0x10000, 18: 0x20000, 19: 0x40000, 20: 0x80000, 21: 0x100000, 22: 0x200000, 23: 0x400000, 24: 0x800000, 25: 0x1000000, 26: 0x2000000, 27: 0x4000000, 28: 0x8000000, 29: 0x10000000, 30: 0x20000000, 31: 0x40000000, "Last": 0x80000000, } weekdays = { "Sunday": 0x1, "Monday": 0x2, "Tuesday": 0x4, "Wednesday": 0x8, "Thursday": 0x10, "Friday": 0x20, "Saturday": 0x40, } weeks = {"First": 0x1, "Second": 0x2, "Third": 0x4, "Fourth": 0x8} months = { "January": 0x1, "February": 0x2, "March": 0x4, "April": 0x8, "May": 0x10, "June": 0x20, "July": 0x40, "August": 0x80, "September": 0x100, "October": 0x200, "November": 0x400, "December": 0x800, } # Format Date Parameters if start_date: date_format = _get_date_time_format(start_date) if date_format: dt_obj = datetime.strptime(start_date, date_format) else: return "Invalid start_date" else: dt_obj = datetime.now() if start_time: time_format = _get_date_time_format(start_time) if time_format: tm_obj = datetime.strptime(start_time, time_format) else: return "Invalid start_time" else: tm_obj = datetime.strptime("00:00:00", "%H:%M:%S") start_boundary = "{}T{}".format( dt_obj.strftime("%Y-%m-%d"), tm_obj.strftime("%H:%M:%S") ) dt_obj = None if end_date: date_format = _get_date_time_format(end_date) if date_format: dt_obj = datetime.strptime(end_date, date_format) else: return "Invalid end_date" if end_time: time_format = _get_date_time_format(end_time) if time_format: tm_obj = datetime.strptime(end_time, time_format) else: return "Invalid end_time" else: tm_obj = datetime.strptime("00:00:00", "%H:%M:%S") end_boundary = None if dt_obj and tm_obj: end_boundary = "{}T{}".format( dt_obj.strftime("%Y-%m-%d"), tm_obj.strftime("%H:%M:%S") ) with salt.utils.winapi.Com(): save_definition = False if kwargs.get("task_definition", False): task_definition = kwargs.get("task_definition") else: save_definition = True # Make sure a name was passed if not name: return 'Required parameter "name" not passed' # Make sure task exists if name in list_tasks(location): # Connect to the task scheduler task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() # get the folder to create the task in task_folder = task_service.GetFolder(location) # Connect to an existing task definition task_definition = task_folder.GetTask(name).Definition else: # Not found and create_new not set, return not found return "{} not found".format(name) # Create a New Trigger trigger = task_definition.Triggers.Create(trigger_types[trigger_type]) # Shared Trigger Parameters # Settings trigger.StartBoundary = start_boundary # Advanced Settings if delay: trigger.Delay = _lookup_first(duration, delay) if random_delay: trigger.RandomDelay = _lookup_first(duration, random_delay) if repeat_interval: trigger.Repetition.Interval = _lookup_first(duration, repeat_interval) if repeat_duration: trigger.Repetition.Duration = _lookup_first(duration, repeat_duration) trigger.Repetition.StopAtDurationEnd = repeat_stop_at_duration_end if execution_time_limit: trigger.ExecutionTimeLimit = _lookup_first(duration, execution_time_limit) if end_boundary: trigger.EndBoundary = end_boundary trigger.Enabled = trigger_enabled # Trigger Specific Parameters # Event Trigger Parameters if trigger_types[trigger_type] == TASK_TRIGGER_EVENT: # Check for required kwargs if kwargs.get("subscription", False): trigger.Id = "Event_ID1" trigger.Subscription = kwargs.get("subscription") else: return 'Required parameter "subscription" not passed' elif trigger_types[trigger_type] == TASK_TRIGGER_TIME: trigger.Id = "Once_ID1" # Daily Trigger Parameters elif trigger_types[trigger_type] == TASK_TRIGGER_DAILY: trigger.Id = "Daily_ID1" trigger.DaysInterval = kwargs.get("days_interval", 1) # Weekly Trigger Parameters elif trigger_types[trigger_type] == TASK_TRIGGER_WEEKLY: trigger.Id = "Weekly_ID1" trigger.WeeksInterval = kwargs.get("weeks_interval", 1) if kwargs.get("days_of_week", False): bits_days = 0 for weekday in kwargs.get("days_of_week"): bits_days |= weekdays[weekday] trigger.DaysOfWeek = bits_days else: return 'Required parameter "days_of_week" not passed' # Monthly Trigger Parameters elif trigger_types[trigger_type] == TASK_TRIGGER_MONTHLY: trigger.Id = "Monthly_ID1" if kwargs.get("months_of_year", False): bits_months = 0 for month in kwargs.get("months_of_year"): bits_months |= months[month] trigger.MonthsOfYear = bits_months else: return 'Required parameter "months_of_year" not passed' if kwargs.get("days_of_month", False) or kwargs.get( "last_day_of_month", False ): if kwargs.get("days_of_month", False): bits_days = 0 for day in kwargs.get("days_of_month"): bits_days |= days[day] trigger.DaysOfMonth = bits_days trigger.RunOnLastDayOfMonth = kwargs.get("last_day_of_month", False) else: return ( 'Monthly trigger requires "days_of_month" or "last_day_of_' 'month" parameters' ) # Monthly Day Of Week Trigger Parameters elif trigger_types[trigger_type] == TASK_TRIGGER_MONTHLYDOW: trigger.Id = "Monthly_DOW_ID1" if kwargs.get("months_of_year", False): bits_months = 0 for month in kwargs.get("months_of_year"): bits_months |= months[month] trigger.MonthsOfYear = bits_months else: return 'Required parameter "months_of_year" not passed' if kwargs.get("weeks_of_month", False) or kwargs.get( "last_week_of_month", False ): if kwargs.get("weeks_of_month", False): bits_weeks = 0 for week in kwargs.get("weeks_of_month"): bits_weeks |= weeks[week] trigger.WeeksOfMonth = bits_weeks trigger.RunOnLastWeekOfMonth = kwargs.get("last_week_of_month", False) else: return ( 'Monthly DOW trigger requires "weeks_of_month" or "last_' 'week_of_month" parameters' ) if kwargs.get("days_of_week", False): bits_days = 0 for weekday in kwargs.get("days_of_week"): bits_days |= weekdays[weekday] trigger.DaysOfWeek = bits_days else: return 'Required parameter "days_of_week" not passed' # On Idle Trigger Parameters elif trigger_types[trigger_type] == TASK_TRIGGER_IDLE: trigger.Id = "OnIdle_ID1" # On Task Creation Trigger Parameters elif trigger_types[trigger_type] == TASK_TRIGGER_REGISTRATION: trigger.Id = "OnTaskCreation_ID1" # On Boot Trigger Parameters elif trigger_types[trigger_type] == TASK_TRIGGER_BOOT: trigger.Id = "OnBoot_ID1" # On Logon Trigger Parameters elif trigger_types[trigger_type] == TASK_TRIGGER_LOGON: trigger.Id = "OnLogon_ID1" # On Session State Change Trigger Parameters elif trigger_types[trigger_type] == TASK_TRIGGER_SESSION_STATE_CHANGE: trigger.Id = "OnSessionStateChange_ID1" if kwargs.get("session_user_name", False): trigger.UserId = kwargs.get("session_user_name") if kwargs.get("state_change", False): trigger.StateChange = state_changes[kwargs.get("state_change")] else: return 'Required parameter "state_change" not passed' # Save the task if save_definition: # Save the Changes return _save_task_definition( name=name, task_folder=task_folder, task_definition=task_definition, user_name=task_definition.Principal.UserID, password=None, logon_type=task_definition.Principal.LogonType, ) def clear_triggers(name, location="\\"): r""" Remove all triggers from the task. Args: name (str): The name of the task from which to clear all triggers. location (str): A string value representing the location of the task. Default is ``\`` which is the root for the task scheduler (``C:\Windows\System32\tasks``). Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' task.clear_trigger <task_name> """ # Check for existing task if name not in list_tasks(location): return "{} not found in {}".format(name, location) # Create the task service object with salt.utils.winapi.Com(): task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() # Get the triggers from the task task_folder = task_service.GetFolder(location) task_definition = task_folder.GetTask(name).Definition triggers = task_definition.Triggers triggers.Clear() # Save the Changes return _save_task_definition( name=name, task_folder=task_folder, task_definition=task_definition, user_name=task_definition.Principal.UserID, password=None, logon_type=task_definition.Principal.LogonType, )
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/win_task.py
0.409693
0.15704
win_task.py
pypi
import re import salt.utils.path from salt.exceptions import CommandExecutionError, SaltInvocationError def __virtual__(): """ Only load if csf exists on the system """ if salt.utils.path.which("csf") is None: return (False, "The csf execution module cannot be loaded: csf unavailable.") else: return True def _temp_exists(method, ip): """ Checks if the ip exists as a temporary rule based on the method supplied, (tempallow, tempdeny). """ _type = method.replace("temp", "").upper() cmd = ( "csf -t | awk -v code=1 -v type=_type -v ip=ip '$1==type && $2==ip {{code=0}}" " END {{exit code}}'".format(_type=_type, ip=ip) ) exists = __salt__["cmd.run_all"](cmd) return not bool(exists["retcode"]) def _exists_with_port(method, rule): path = "/etc/csf/csf.{}".format(method) return __salt__["file.contains"](path, rule) def exists( method, ip, port=None, proto="tcp", direction="in", port_origin="d", ip_origin="d", ttl=None, comment="", ): """ Returns true a rule for the ip already exists based on the method supplied. Returns false if not found. CLI Example: .. code-block:: bash salt '*' csf.exists allow 1.2.3.4 salt '*' csf.exists tempdeny 1.2.3.4 """ if method.startswith("temp"): return _temp_exists(method, ip) if port: rule = _build_port_rule( ip, port, proto, direction, port_origin, ip_origin, comment ) return _exists_with_port(method, rule) exists = __salt__["cmd.run_all"]("egrep ^'{} +' /etc/csf/csf.{}".format(ip, method)) return not bool(exists["retcode"]) def __csf_cmd(cmd): """ Execute csf command """ csf_cmd = "{} {}".format(salt.utils.path.which("csf"), cmd) out = __salt__["cmd.run_all"](csf_cmd) if out["retcode"] != 0: if not out["stderr"]: ret = out["stdout"] else: ret = out["stderr"] raise CommandExecutionError("csf failed: {}".format(ret)) else: ret = out["stdout"] return ret def _status_csf(): """ Return True if csf is running otherwise return False """ cmd = "test -e /etc/csf/csf.disable" out = __salt__["cmd.run_all"](cmd) return bool(out["retcode"]) def _get_opt(method): """ Returns the cmd option based on a long form argument. """ opts = { "allow": "-a", "deny": "-d", "unallow": "-ar", "undeny": "-dr", "tempallow": "-ta", "tempdeny": "-td", "temprm": "-tr", } return opts[method] def _build_args(method, ip, comment): """ Returns the cmd args for csf basic allow/deny commands. """ opt = _get_opt(method) args = "{} {}".format(opt, ip) if comment: args += " {}".format(comment) return args def _access_rule( method, ip=None, port=None, proto="tcp", direction="in", port_origin="d", ip_origin="d", comment="", ): """ Handles the cmd execution for allow and deny commands. """ if _status_csf(): if ip is None: return {"error": "You must supply an ip address or CIDR."} if port is None: args = _build_args(method, ip, comment) return __csf_cmd(args) else: if method not in ["allow", "deny"]: return { "error": ( "Only allow and deny rules are allowed when specifying a port." ) } return _access_rule_with_port( method=method, ip=ip, port=port, proto=proto, direction=direction, port_origin=port_origin, ip_origin=ip_origin, comment=comment, ) def _build_port_rule(ip, port, proto, direction, port_origin, ip_origin, comment): kwargs = { "ip": ip, "port": port, "proto": proto, "direction": direction, "port_origin": port_origin, "ip_origin": ip_origin, } rule = "{proto}|{direction}|{port_origin}={port}|{ip_origin}={ip}".format(**kwargs) if comment: rule += " #{}".format(comment) return rule def _remove_access_rule_with_port( method, ip, port, proto="tcp", direction="in", port_origin="d", ip_origin="d", ttl=None, ): rule = _build_port_rule( ip, port=port, proto=proto, direction=direction, port_origin=port_origin, ip_origin=ip_origin, comment="", ) rule = rule.replace("|", "[|]") rule = rule.replace(".", "[.]") result = __salt__["file.replace"]( "/etc/csf/csf.{}".format(method), pattern="^{}(( +)?\\#.*)?$\n".format(rule), # pylint: disable=W1401 repl="", ) return result def _csf_to_list(option): """ Extract comma-separated values from a csf.conf option and return a list. """ result = [] line = get_option(option) if line: csv = line.split("=")[1].replace(" ", "").replace('"', "") result = csv.split(",") return result def split_option(option): return re.split(r"(?: +)?\=(?: +)?", option) def get_option(option): pattern = r'^{}(\ +)?\=(\ +)?".*"$'.format(option) # pylint: disable=W1401 grep = __salt__["file.grep"]("/etc/csf/csf.conf", pattern, "-E") if "stdout" in grep and grep["stdout"]: line = grep["stdout"] return line return None def set_option(option, value): current_option = get_option(option) if not current_option: return {"error": "No such option exists in csf.conf"} result = __salt__["file.replace"]( "/etc/csf/csf.conf", pattern=r'^{}(\ +)?\=(\ +)?".*"'.format(option), # pylint: disable=W1401 repl='{} = "{}"'.format(option, value), ) return result def get_skipped_nics(ipv6=False): if ipv6: option = "ETH6_DEVICE_SKIP" else: option = "ETH_DEVICE_SKIP" skipped_nics = _csf_to_list(option) return skipped_nics def skip_nic(nic, ipv6=False): nics = get_skipped_nics(ipv6=ipv6) nics.append(nic) return skip_nics(nics, ipv6) def skip_nics(nics, ipv6=False): if ipv6: ipv6 = "6" else: ipv6 = "" nics_csv = ",".join(map(str, nics)) result = __salt__["file.replace"]( "/etc/csf/csf.conf", # pylint: disable=anomalous-backslash-in-string pattern=r'^ETH{}_DEVICE_SKIP(\ +)?\=(\ +)?".*"'.format(ipv6), # pylint: enable=anomalous-backslash-in-string repl='ETH{}_DEVICE_SKIP = "{}"'.format(ipv6, nics_csv), ) return result def _access_rule_with_port( method, ip, port, proto="tcp", direction="in", port_origin="d", ip_origin="d", ttl=None, comment="", ): results = {} if direction == "both": directions = ["in", "out"] else: directions = [direction] for direction in directions: _exists = exists( method, ip, port=port, proto=proto, direction=direction, port_origin=port_origin, ip_origin=ip_origin, ttl=ttl, comment=comment, ) if not _exists: rule = _build_port_rule( ip, port=port, proto=proto, direction=direction, port_origin=port_origin, ip_origin=ip_origin, comment=comment, ) path = "/etc/csf/csf.{}".format(method) results[direction] = __salt__["file.append"](path, rule) return results def _tmp_access_rule( method, ip=None, ttl=None, port=None, direction="in", port_origin="d", ip_origin="d", comment="", ): """ Handles the cmd execution for tempdeny and tempallow commands. """ if _status_csf(): if ip is None: return {"error": "You must supply an ip address or CIDR."} if ttl is None: return {"error": "You must supply a ttl."} args = _build_tmp_access_args(method, ip, ttl, port, direction, comment) return __csf_cmd(args) def _build_tmp_access_args(method, ip, ttl, port, direction, comment): """ Builds the cmd args for temporary access/deny opts. """ opt = _get_opt(method) args = "{} {} {}".format(opt, ip, ttl) if port: args += " -p {}".format(port) if direction: args += " -d {}".format(direction) if comment: args += " #{}".format(comment) return args def running(): """ Check csf status CLI Example: .. code-block:: bash salt '*' csf.running """ return _status_csf() def disable(): """ Disable csf permanently CLI Example: .. code-block:: bash salt '*' csf.disable """ if _status_csf(): return __csf_cmd("-x") def enable(): """ Activate csf if not running CLI Example: .. code-block:: bash salt '*' csf.enable """ if not _status_csf(): return __csf_cmd("-e") def reload(): """ Restart csf CLI Example: .. code-block:: bash salt '*' csf.reload """ return __csf_cmd("-r") def tempallow(ip=None, ttl=None, port=None, direction=None, comment=""): """ Add an rule to the temporary ip allow list. See :func:`_access_rule`. 1- Add an IP: CLI Example: .. code-block:: bash salt '*' csf.tempallow 127.0.0.1 3600 port=22 direction='in' comment='# Temp dev ssh access' """ return _tmp_access_rule("tempallow", ip, ttl, port, direction, comment) def tempdeny(ip=None, ttl=None, port=None, direction=None, comment=""): """ Add a rule to the temporary ip deny list. See :func:`_access_rule`. 1- Add an IP: CLI Example: .. code-block:: bash salt '*' csf.tempdeny 127.0.0.1 300 port=22 direction='in' comment='# Brute force attempt' """ return _tmp_access_rule("tempdeny", ip, ttl, port, direction, comment) def allow( ip, port=None, proto="tcp", direction="in", port_origin="d", ip_origin="s", ttl=None, comment="", ): """ Add an rule to csf allowed hosts See :func:`_access_rule`. 1- Add an IP: CLI Example: .. code-block:: bash salt '*' csf.allow 127.0.0.1 salt '*' csf.allow 127.0.0.1 comment="Allow localhost" """ return _access_rule( "allow", ip, port=port, proto=proto, direction=direction, port_origin=port_origin, ip_origin=ip_origin, comment=comment, ) def deny( ip, port=None, proto="tcp", direction="in", port_origin="d", ip_origin="d", ttl=None, comment="", ): """ Add an rule to csf denied hosts See :func:`_access_rule`. 1- Deny an IP: CLI Example: .. code-block:: bash salt '*' csf.deny 127.0.0.1 salt '*' csf.deny 127.0.0.1 comment="Too localhosty" """ return _access_rule( "deny", ip, port, proto, direction, port_origin, ip_origin, comment ) def remove_temp_rule(ip): opt = _get_opt("temprm") args = "{} {}".format(opt, ip) return __csf_cmd(args) def unallow(ip): """ Remove a rule from the csf denied hosts See :func:`_access_rule`. 1- Deny an IP: CLI Example: .. code-block:: bash salt '*' csf.unallow 127.0.0.1 """ return _access_rule("unallow", ip) def undeny(ip): """ Remove a rule from the csf denied hosts See :func:`_access_rule`. 1- Deny an IP: CLI Example: .. code-block:: bash salt '*' csf.undeny 127.0.0.1 """ return _access_rule("undeny", ip) def remove_rule( method, ip, port=None, proto="tcp", direction="in", port_origin="d", ip_origin="s", ttl=None, comment="", ): if method.startswith("temp") or ttl: return remove_temp_rule(ip) if not port: if method == "allow": return unallow(ip) elif method == "deny": return undeny(ip) if port: return _remove_access_rule_with_port( method=method, ip=ip, port=port, proto=proto, direction=direction, port_origin=port_origin, ip_origin=ip_origin, ) def allow_ports(ports, proto="tcp", direction="in"): """ Fully replace the incoming or outgoing ports line in the csf.conf file - e.g. TCP_IN, TCP_OUT, UDP_IN, UDP_OUT, etc. CLI Example: .. code-block:: bash salt '*' csf.allow_ports ports="[22,80,443,4505,4506]" proto='tcp' direction='in' """ results = [] ports = set(ports) ports = list(ports) proto = proto.upper() direction = direction.upper() _validate_direction_and_proto(direction, proto) ports_csv = ",".join(map(str, ports)) directions = build_directions(direction) for direction in directions: result = __salt__["file.replace"]( "/etc/csf/csf.conf", # pylint: disable=anomalous-backslash-in-string pattern=r'^{}_{}(\ +)?\=(\ +)?".*"$'.format(proto, direction), # pylint: enable=anomalous-backslash-in-string repl='{}_{} = "{}"'.format(proto, direction, ports_csv), ) results.append(result) return results def get_ports(proto="tcp", direction="in"): """ Lists ports from csf.conf based on direction and protocol. e.g. - TCP_IN, TCP_OUT, UDP_IN, UDP_OUT, etc.. CLI Example: .. code-block:: bash salt '*' csf.allow_port 22 proto='tcp' direction='in' """ proto = proto.upper() direction = direction.upper() results = {} _validate_direction_and_proto(direction, proto) directions = build_directions(direction) for direction in directions: option = "{}_{}".format(proto, direction) results[direction] = _csf_to_list(option) return results def _validate_direction_and_proto(direction, proto): if direction.upper() not in ["IN", "OUT", "BOTH"]: raise SaltInvocationError("You must supply a direction of in, out, or both") if proto.upper() not in ["TCP", "UDP", "TCP6", "UDP6"]: raise SaltInvocationError( "You must supply tcp, udp, tcp6, or udp6 for the proto keyword" ) return def build_directions(direction): direction = direction.upper() if direction == "BOTH": directions = ["IN", "OUT"] else: directions = [direction] return directions def allow_port(port, proto="tcp", direction="both"): """ Like allow_ports, but it will append to the existing entry instead of replacing it. Takes a single port instead of a list of ports. CLI Example: .. code-block:: bash salt '*' csf.allow_port 22 proto='tcp' direction='in' """ ports = get_ports(proto=proto, direction=direction) direction = direction.upper() _validate_direction_and_proto(direction, proto) directions = build_directions(direction) results = [] for direction in directions: _ports = ports[direction] _ports.append(port) results += allow_ports(_ports, proto=proto, direction=direction) return results def get_testing_status(): testing = _csf_to_list("TESTING")[0] return testing def _toggle_testing(val): if val == "on": val = "1" elif val == "off": val = "0" else: raise SaltInvocationError("Only valid arg is 'on' or 'off' here.") result = __salt__["file.replace"]( "/etc/csf/csf.conf", pattern=r'^TESTING(\ +)?\=(\ +)?".*"', # pylint: disable=W1401 repl='TESTING = "{}"'.format(val), ) return result def enable_testing_mode(): return _toggle_testing("on") def disable_testing_mode(): return _toggle_testing("off")
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/csf.py
0.520496
0.154376
csf.py
pypi
import logging import salt.utils.platform log = logging.getLogger(__name__) __func_alias__ = {"list_": "list"} # Define the module's virtual name __virtualname__ = "service" def __virtual__(): """ Only work on systems that are a proxy minion """ try: if salt.utils.platform.is_proxy() and __opts__["proxy"]["proxytype"] == "dummy": return __virtualname__ except KeyError: return ( False, "The dummyproxy_service execution module failed to load. Check " "the proxy key in pillar or /etc/salt/proxy.", ) return ( False, "The dummyproxy_service execution module failed to load: only works " "on the integration testsuite dummy proxy minion.", ) def get_all(): """ Return a list of all available services .. versionadded:: 2016.11.3 CLI Example: .. code-block:: bash salt '*' service.get_all """ proxy_fn = "dummy.service_list" return __proxy__[proxy_fn]() def list_(): """ Return a list of all available services. .. versionadded:: 2016.11.3 CLI Example: .. code-block:: bash salt '*' service.list """ return get_all() def start(name, sig=None): """ Start the specified service on the dummy .. versionadded:: 2016.11.3 CLI Example: .. code-block:: bash salt '*' service.start <service name> """ proxy_fn = "dummy.service_start" return __proxy__[proxy_fn](name) def stop(name, sig=None): """ Stop the specified service on the dummy .. versionadded:: 2016.11.3 CLI Example: .. code-block:: bash salt '*' service.stop <service name> """ proxy_fn = "dummy.service_stop" return __proxy__[proxy_fn](name) def restart(name, sig=None): """ Restart the specified service with dummy. .. versionadded:: 2016.11.3 CLI Example: .. code-block:: bash salt '*' service.restart <service name> """ proxy_fn = "dummy.service_restart" return __proxy__[proxy_fn](name) def status(name, sig=None): """ Return the status for a service via dummy, returns a bool whether the service is running. .. versionadded:: 2016.11.3 CLI Example: .. code-block:: bash salt '*' service.status <service name> """ proxy_fn = "dummy.service_status" resp = __proxy__[proxy_fn](name) if resp["comment"] == "stopped": return False if resp["comment"] == "running": return True def running(name, sig=None): """ Return whether this service is running. .. versionadded:: 2016.11.3 """ return status(name).get(name, False) def enabled(name, sig=None): """ Only the 'redbull' service is 'enabled' in the test .. versionadded:: 2016.11.3 """ return name == "redbull"
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/dummyproxy_service.py
0.700485
0.182207
dummyproxy_service.py
pypi
import datetime import logging import salt.utils.compat import salt.utils.json import salt.utils.versions log = logging.getLogger(__name__) # pylint: disable=import-error try: # pylint: disable=unused-import import boto import boto3 # pylint: enable=unused-import from botocore.exceptions import ClientError from botocore import __version__ as found_botocore_version logging.getLogger("boto3").setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error def __virtual__(): """ Only load if boto libraries exist and if boto libraries are greater than a given version. """ # the boto_lambda execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 return salt.utils.versions.check_boto_reqs(boto3_ver="1.2.1", botocore_ver="1.4.41") def __init__(opts): if HAS_BOTO: __utils__["boto3.assign_funcs"](__name__, "iot") def thing_type_exists(thingTypeName, region=None, key=None, keyid=None, profile=None): """ Given a thing type name, check to see if the given thing type exists Returns True if the given thing type exists and returns False if the given thing type does not exist. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_iot.thing_type_exists mythingtype """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) res = conn.describe_thing_type(thingTypeName=thingTypeName) if res.get("thingTypeName"): return {"exists": True} else: return {"exists": False} except ClientError as e: err = __utils__["boto3.get_error"](e) if e.response.get("Error", {}).get("Code") == "ResourceNotFoundException": return {"exists": False} return {"error": err} def describe_thing_type(thingTypeName, region=None, key=None, keyid=None, profile=None): """ Given a thing type name describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_iot.describe_thing_type mythingtype """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) res = conn.describe_thing_type(thingTypeName=thingTypeName) if res: res.pop("ResponseMetadata", None) thingTypeMetadata = res.get("thingTypeMetadata") if thingTypeMetadata: for dtype in ("creationDate", "deprecationDate"): dval = thingTypeMetadata.get(dtype) if dval and isinstance(dval, datetime.date): thingTypeMetadata[dtype] = "{}".format(dval) return {"thing_type": res} else: return {"thing_type": None} except ClientError as e: err = __utils__["boto3.get_error"](e) if e.response.get("Error", {}).get("Code") == "ResourceNotFoundException": return {"thing_type": None} return {"error": err} def create_thing_type( thingTypeName, thingTypeDescription, searchableAttributesList, region=None, key=None, keyid=None, profile=None, ): """ Given a valid config, create a thing type. Returns {created: true} if the thing type was created and returns {created: False} if the thing type was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_iot.create_thing_type mythingtype \\ thingtype_description_string '["searchable_attr_1", "searchable_attr_2"]' """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) thingTypeProperties = dict( thingTypeDescription=thingTypeDescription, searchableAttributes=searchableAttributesList, ) thingtype = conn.create_thing_type( thingTypeName=thingTypeName, thingTypeProperties=thingTypeProperties ) if thingtype: log.info( "The newly created thing type ARN is %s", thingtype["thingTypeArn"] ) return {"created": True, "thingTypeArn": thingtype["thingTypeArn"]} else: log.warning("thing type was not created") return {"created": False} except ClientError as e: return {"created": False, "error": __utils__["boto3.get_error"](e)} def deprecate_thing_type( thingTypeName, undoDeprecate=False, region=None, key=None, keyid=None, profile=None ): """ Given a thing type name, deprecate it when undoDeprecate is False and undeprecate it when undoDeprecate is True. Returns {deprecated: true} if the thing type was deprecated and returns {deprecated: false} if the thing type was not deprecated. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_iot.deprecate_thing_type mythingtype """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.deprecate_thing_type( thingTypeName=thingTypeName, undoDeprecate=undoDeprecate ) deprecated = True if undoDeprecate is False else False return {"deprecated": deprecated} except ClientError as e: return {"deprecated": False, "error": __utils__["boto3.get_error"](e)} def delete_thing_type(thingTypeName, region=None, key=None, keyid=None, profile=None): """ Given a thing type name, delete it. Returns {deleted: true} if the thing type was deleted and returns {deleted: false} if the thing type was not deleted. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_iot.delete_thing_type mythingtype """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_thing_type(thingTypeName=thingTypeName) return {"deleted": True} except ClientError as e: err = __utils__["boto3.get_error"](e) if e.response.get("Error", {}).get("Code") == "ResourceNotFoundException": return {"deleted": True} return {"deleted": False, "error": err} def policy_exists(policyName, region=None, key=None, keyid=None, profile=None): """ Given a policy name, check to see if the given policy exists. Returns True if the given policy exists and returns False if the given policy does not exist. CLI Example: .. code-block:: bash salt myminion boto_iot.policy_exists mypolicy """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.get_policy(policyName=policyName) return {"exists": True} except ClientError as e: err = __utils__["boto3.get_error"](e) if e.response.get("Error", {}).get("Code") == "ResourceNotFoundException": return {"exists": False} return {"error": err} def create_policy( policyName, policyDocument, region=None, key=None, keyid=None, profile=None ): """ Given a valid config, create a policy. Returns {created: true} if the policy was created and returns {created: False} if the policy was not created. CLI Example: .. code-block:: bash salt myminion boto_iot.create_policy my_policy \\ '{"Version":"2015-12-12",\\ "Statement":[{"Effect":"Allow",\\ "Action":["iot:Publish"],\\ "Resource":["arn:::::topic/foo/bar"]}]}' """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policyDocument, str): policyDocument = salt.utils.json.dumps(policyDocument) policy = conn.create_policy( policyName=policyName, policyDocument=policyDocument ) if policy: log.info( "The newly created policy version is %s", policy["policyVersionId"] ) return {"created": True, "versionId": policy["policyVersionId"]} else: log.warning("Policy was not created") return {"created": False} except ClientError as e: return {"created": False, "error": __utils__["boto3.get_error"](e)} def delete_policy(policyName, region=None, key=None, keyid=None, profile=None): """ Given a policy name, delete it. Returns {deleted: true} if the policy was deleted and returns {deleted: false} if the policy was not deleted. CLI Example: .. code-block:: bash salt myminion boto_iot.delete_policy mypolicy """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_policy(policyName=policyName) return {"deleted": True} except ClientError as e: return {"deleted": False, "error": __utils__["boto3.get_error"](e)} def describe_policy(policyName, region=None, key=None, keyid=None, profile=None): """ Given a policy name describe its properties. Returns a dictionary of interesting properties. CLI Example: .. code-block:: bash salt myminion boto_iot.describe_policy mypolicy """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy = conn.get_policy(policyName=policyName) if policy: keys = ("policyName", "policyArn", "policyDocument", "defaultVersionId") return {"policy": {k: policy.get(k) for k in keys}} else: return {"policy": None} except ClientError as e: err = __utils__["boto3.get_error"](e) if e.response.get("Error", {}).get("Code") == "ResourceNotFoundException": return {"policy": None} return {"error": __utils__["boto3.get_error"](e)} def policy_version_exists( policyName, policyVersionId, region=None, key=None, keyid=None, profile=None ): """ Given a policy name and version ID, check to see if the given policy version exists. Returns True if the given policy version exists and returns False if the given policy version does not exist. CLI Example: .. code-block:: bash salt myminion boto_iot.policy_version_exists mypolicy versionid """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy = conn.get_policy_version( policyName=policyName, policyversionId=policyVersionId ) return {"exists": bool(policy)} except ClientError as e: err = __utils__["boto3.get_error"](e) if e.response.get("Error", {}).get("Code") == "ResourceNotFoundException": return {"exists": False} return {"error": __utils__["boto3.get_error"](e)} def create_policy_version( policyName, policyDocument, setAsDefault=False, region=None, key=None, keyid=None, profile=None, ): """ Given a valid config, create a new version of a policy. Returns {created: true} if the policy version was created and returns {created: False} if the policy version was not created. CLI Example: .. code-block:: bash salt myminion boto_iot.create_policy_version my_policy \\ '{"Statement":[{"Effect":"Allow","Action":["iot:Publish"],"Resource":["arn:::::topic/foo/bar"]}]}' """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policyDocument, str): policyDocument = salt.utils.json.dumps(policyDocument) policy = conn.create_policy_version( policyName=policyName, policyDocument=policyDocument, setAsDefault=setAsDefault, ) if policy: log.info( "The newly created policy version is %s", policy["policyVersionId"] ) return {"created": True, "name": policy["policyVersionId"]} else: log.warning("Policy version was not created") return {"created": False} except ClientError as e: return {"created": False, "error": __utils__["boto3.get_error"](e)} def delete_policy_version( policyName, policyVersionId, region=None, key=None, keyid=None, profile=None ): """ Given a policy name and version, delete it. Returns {deleted: true} if the policy version was deleted and returns {deleted: false} if the policy version was not deleted. CLI Example: .. code-block:: bash salt myminion boto_iot.delete_policy_version mypolicy version """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_policy_version( policyName=policyName, policyVersionId=policyVersionId ) return {"deleted": True} except ClientError as e: return {"deleted": False, "error": __utils__["boto3.get_error"](e)} def describe_policy_version( policyName, policyVersionId, region=None, key=None, keyid=None, profile=None ): """ Given a policy name and version describe its properties. Returns a dictionary of interesting properties. CLI Example: .. code-block:: bash salt myminion boto_iot.describe_policy_version mypolicy version """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy = conn.get_policy_version( policyName=policyName, policyVersionId=policyVersionId ) if policy: keys = ( "policyName", "policyArn", "policyDocument", "policyVersionId", "isDefaultVersion", ) return {"policy": {k: policy.get(k) for k in keys}} else: return {"policy": None} except ClientError as e: err = __utils__["boto3.get_error"](e) if e.response.get("Error", {}).get("Code") == "ResourceNotFoundException": return {"policy": None} return {"error": __utils__["boto3.get_error"](e)} def list_policies(region=None, key=None, keyid=None, profile=None): """ List all policies Returns list of policies CLI Example: .. code-block:: bash salt myminion boto_iot.list_policies Example Return: .. code-block:: yaml policies: - {...} - {...} """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policies = [] for ret in __utils__["boto3.paged_call"]( conn.list_policies, marker_flag="nextMarker", marker_arg="marker" ): policies.extend(ret["policies"]) if not bool(policies): log.warning("No policies found") return {"policies": policies} except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def list_policy_versions(policyName, region=None, key=None, keyid=None, profile=None): """ List the versions available for the given policy. CLI Example: .. code-block:: bash salt myminion boto_iot.list_policy_versions mypolicy Example Return: .. code-block:: yaml policyVersions: - {...} - {...} """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vers = [] for ret in __utils__["boto3.paged_call"]( conn.list_policy_versions, marker_flag="nextMarker", marker_arg="marker", policyName=policyName, ): vers.extend(ret["policyVersions"]) if not bool(vers): log.warning("No versions found") return {"policyVersions": vers} except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def set_default_policy_version( policyName, policyVersionId, region=None, key=None, keyid=None, profile=None ): """ Sets the specified version of the specified policy as the policy's default (operative) version. This action affects all certificates that the policy is attached to. Returns {changed: true} if the policy version was set {changed: False} if the policy version was not set. CLI Example: .. code-block:: bash salt myminion boto_iot.set_default_policy_version mypolicy versionid """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.set_default_policy_version( policyName=policyName, policyVersionId=str(policyVersionId) ) return {"changed": True} except ClientError as e: return {"changed": False, "error": __utils__["boto3.get_error"](e)} def list_principal_policies(principal, region=None, key=None, keyid=None, profile=None): """ List the policies attached to the given principal. CLI Example: .. code-block:: bash salt myminion boto_iot.list_principal_policies myprincipal Example Return: .. code-block:: yaml policies: - {...} - {...} """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vers = [] for ret in __utils__["boto3.paged_call"]( conn.list_principal_policies, principal=principal, marker_flag="nextMarker", marker_arg="marker", ): vers.extend(ret["policies"]) if not bool(vers): log.warning("No policies found") return {"policies": vers} except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def attach_principal_policy( policyName, principal, region=None, key=None, keyid=None, profile=None ): """ Attach the specified policy to the specified principal (certificate or other credential.) Returns {attached: true} if the policy was attached {attached: False} if the policy was not attached. CLI Example: .. code-block:: bash salt myminion boto_iot.attach_principal_policy mypolicy mycognitoID """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_principal_policy(policyName=policyName, principal=principal) return {"attached": True} except ClientError as e: return {"attached": False, "error": __utils__["boto3.get_error"](e)} def detach_principal_policy( policyName, principal, region=None, key=None, keyid=None, profile=None ): """ Detach the specified policy from the specified principal (certificate or other credential.) Returns {detached: true} if the policy was detached {detached: False} if the policy was not detached. CLI Example: .. code-block:: bash salt myminion boto_iot.detach_principal_policy mypolicy mycognitoID """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_principal_policy(policyName=policyName, principal=principal) return {"detached": True} except ClientError as e: return {"detached": False, "error": __utils__["boto3.get_error"](e)} def topic_rule_exists(ruleName, region=None, key=None, keyid=None, profile=None): """ Given a rule name, check to see if the given rule exists. Returns True if the given rule exists and returns False if the given rule does not exist. CLI Example: .. code-block:: bash salt myminion boto_iot.topic_rule_exists myrule """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) rule = conn.get_topic_rule(ruleName=ruleName) return {"exists": True} except ClientError as e: # Nonexistent rules show up as unauthorized exceptions. It's unclear how # to distinguish this from a real authorization exception. In practical # use, it's more useful to assume lack of existence than to assume a # genuine authorization problem; authorization problems should not be # the common case. err = __utils__["boto3.get_error"](e) if e.response.get("Error", {}).get("Code") == "UnauthorizedException": return {"exists": False} return {"error": __utils__["boto3.get_error"](e)} def create_topic_rule( ruleName, sql, actions, description, ruleDisabled=False, region=None, key=None, keyid=None, profile=None, ): """ Given a valid config, create a topic rule. Returns {created: true} if the rule was created and returns {created: False} if the rule was not created. CLI Example: .. code-block:: bash salt myminion boto_iot.create_topic_rule my_rule "SELECT * FROM 'some/thing'" \\ '[{"lambda":{"functionArn":"arn:::::something"}},{"sns":{\\ "targetArn":"arn:::::something","roleArn":"arn:::::something"}}]' """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.create_topic_rule( ruleName=ruleName, topicRulePayload={ "sql": sql, "description": description, "actions": actions, "ruleDisabled": ruleDisabled, }, ) return {"created": True} except ClientError as e: return {"created": False, "error": __utils__["boto3.get_error"](e)} def replace_topic_rule( ruleName, sql, actions, description, ruleDisabled=False, region=None, key=None, keyid=None, profile=None, ): """ Given a valid config, replace a topic rule with the new values. Returns {created: true} if the rule was created and returns {created: False} if the rule was not created. CLI Example: .. code-block:: bash salt myminion boto_iot.replace_topic_rule my_rule 'SELECT * FROM some.thing' \\ '[{"lambda":{"functionArn":"arn:::::something"}},{"sns":{\\ "targetArn":"arn:::::something","roleArn":"arn:::::something"}}]' """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.replace_topic_rule( ruleName=ruleName, topicRulePayload={ "sql": sql, "description": description, "actions": actions, "ruleDisabled": ruleDisabled, }, ) return {"replaced": True} except ClientError as e: return {"replaced": False, "error": __utils__["boto3.get_error"](e)} def delete_topic_rule(ruleName, region=None, key=None, keyid=None, profile=None): """ Given a rule name, delete it. Returns {deleted: true} if the rule was deleted and returns {deleted: false} if the rule was not deleted. CLI Example: .. code-block:: bash salt myminion boto_iot.delete_rule myrule """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_topic_rule(ruleName=ruleName) return {"deleted": True} except ClientError as e: return {"deleted": False, "error": __utils__["boto3.get_error"](e)} def describe_topic_rule(ruleName, region=None, key=None, keyid=None, profile=None): """ Given a topic rule name describe its properties. Returns a dictionary of interesting properties. CLI Example: .. code-block:: bash salt myminion boto_iot.describe_topic_rule myrule """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) rule = conn.get_topic_rule(ruleName=ruleName) if rule and "rule" in rule: rule = rule["rule"] keys = ("ruleName", "sql", "description", "actions", "ruleDisabled") return {"rule": {k: rule.get(k) for k in keys}} else: return {"rule": None} except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def list_topic_rules( topic=None, ruleDisabled=None, region=None, key=None, keyid=None, profile=None ): """ List all rules (for a given topic, if specified) Returns list of rules CLI Example: .. code-block:: bash salt myminion boto_iot.list_topic_rules Example Return: .. code-block:: yaml rules: - {...} - {...} """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) kwargs = {} if topic is not None: kwargs["topic"] = topic if ruleDisabled is not None: kwargs["ruleDisabled"] = ruleDisabled rules = [] for ret in __utils__["boto3.paged_call"]( conn.list_topic_rules, marker_flag="nextToken", marker_arg="nextToken", **kwargs ): rules.extend(ret["rules"]) if not bool(rules): log.warning("No rules found") return {"rules": rules} except ClientError as e: return {"error": __utils__["boto3.get_error"](e)}
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/boto_iot.py
0.559651
0.178741
boto_iot.py
pypi
from salt.exceptions import SaltException # Import Salt modules try: import ciscoconfparse HAS_CISCOCONFPARSE = True except ImportError: HAS_CISCOCONFPARSE = False # ------------------------------------------------------------------------------ # module properties # ------------------------------------------------------------------------------ __virtualname__ = "ciscoconfparse" # ------------------------------------------------------------------------------ # property functions # ------------------------------------------------------------------------------ def __virtual__(): if HAS_CISCOCONFPARSE: return HAS_CISCOCONFPARSE else: return (False, "Missing dependency ciscoconfparse") # ------------------------------------------------------------------------------ # helper functions -- will not be exported # ------------------------------------------------------------------------------ def _get_ccp(config=None, config_path=None, saltenv="base"): """ """ if config_path: config = __salt__["cp.get_file_str"](config_path, saltenv=saltenv) if config is False: raise SaltException("{} is not available".format(config_path)) if isinstance(config, str): config = config.splitlines() ccp = ciscoconfparse.CiscoConfParse(config) return ccp # ------------------------------------------------------------------------------ # callable functions # ------------------------------------------------------------------------------ def find_objects(config=None, config_path=None, regex=None, saltenv="base"): """ Return all the line objects that match the expression in the ``regex`` argument. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines <salt.ciscoconfparse_mod.find_lines>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects'](config_path='salt://path/to/config.txt', regex='Gigabit') for obj in objects: print(obj.text) """ ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects(regex) return lines def find_lines(config=None, config_path=None, regex=None, saltenv="base"): """ Return all the lines (as text) that match the expression in the ``regex`` argument. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines config_path=https://bit.ly/2mAdq7z regex='ip address' Output example: .. code-block:: text cisco-ios-router: - ip address dhcp - ip address 172.20.0.1 255.255.255.0 - no ip address """ lines = find_objects( config=config, config_path=config_path, regex=regex, saltenv=saltenv ) return [line.text for line in lines] def find_objects_w_child( config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv="base", ): """ Parse through the children of all parent lines matching ``parent_regex``, and return a list of child objects, which matched the ``child_regex``. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines_w_child <salt.ciscoconfparse_mod.find_lines_w_child>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects_w_child'](config_path='https://bit.ly/2mAdq7z', parent_regex='line con', child_regex='stopbits') for obj in objects: print(obj.text) """ ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects_w_child(parent_regex, child_regex, ignore_ws=ignore_ws) return lines def find_lines_w_child( config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv="base", ): r""" Return a list of parent lines (as text) matching the regular expression ``parent_regex`` that have children lines matching ``child_regex``. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2uIRxau parent_regex='ge-(.*)' child_regex='unit \d+' """ lines = find_objects_w_child( config=config, config_path=config_path, parent_regex=parent_regex, child_regex=child_regex, ignore_ws=ignore_ws, saltenv=saltenv, ) return [line.text for line in lines] def find_objects_wo_child( config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv="base", ): """ Return a list of parent ``ciscoconfparse.IOSCfgLine`` objects, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` objects will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines_wo_child <salt.ciscoconfparse_mod.find_lines_wo_child>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects_wo_child'](config_path='https://bit.ly/2mAdq7z', parent_regex='line con', child_regex='stopbits') for obj in objects: print(obj.text) """ ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects_wo_child(parent_regex, child_regex, ignore_ws=ignore_ws) return lines def find_lines_wo_child( config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv="base", ): """ Return a list of parent ``ciscoconfparse.IOSCfgLine`` lines as text, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` text lines will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_wo_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' """ lines = find_objects_wo_child( config=config, config_path=config_path, parent_regex=parent_regex, child_regex=child_regex, ignore_ws=ignore_ws, saltenv=saltenv, ) return [line.text for line in lines] def filter_lines( config=None, config_path=None, parent_regex=None, child_regex=None, saltenv="base" ): """ Return a list of detailed matches, for the configuration blocks (parent-child relationship) whose parent respects the regular expressions configured via the ``parent_regex`` argument, and the child matches the ``child_regex`` regular expression. The result is a list of dictionaries with the following keys: - ``match``: a boolean value that tells whether ``child_regex`` matched any children lines. - ``parent``: the parent line (as text). - ``child``: the child line (as text). If no child line matched, this field will be ``None``. Note that the return list contains the elements that matched the parent condition, the ``parent_regex`` regular expression. Therefore, the ``parent`` field will always have a valid value, while ``match`` and ``child`` may default to ``False`` and ``None`` respectively when there is not child match. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.filter_lines config_path=https://bit.ly/2mAdq7z parent_regex='Gigabit' child_regex='shutdown' Example output (for the example above): .. code-block:: python [ { 'parent': 'interface GigabitEthernet1', 'match': False, 'child': None }, { 'parent': 'interface GigabitEthernet2', 'match': True, 'child': ' shutdown' }, { 'parent': 'interface GigabitEthernet3', 'match': True, 'child': ' shutdown' } ] """ ret = [] ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) parent_lines = ccp.find_objects(parent_regex) for parent_line in parent_lines: child_lines = parent_line.re_search_children(child_regex) if child_lines: for child_line in child_lines: ret.append( { "match": True, "parent": parent_line.text, "child": child_line.text, } ) else: ret.append({"match": False, "parent": parent_line.text, "child": None}) return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/ciscoconfparse_mod.py
0.796807
0.196865
ciscoconfparse_mod.py
pypi
import logging import re import uuid # Solve the Chicken and egg problem where grains need to run before any # of the modules are loaded and are generally available for any usage. import salt.modules.cmdmod import salt.utils.path log = logging.getLogger(__name__) def __virtual__(): """ Only work when dmidecode is installed. """ return ( bool(salt.utils.path.which_bin(["dmidecode", "smbios"])), "The smbios execution module failed to load: neither dmidecode nor smbios in" " the path.", ) def get(string, clean=True): """ Get an individual DMI string from SMBIOS info string The string to fetch. DMIdecode supports: - ``bios-vendor`` - ``bios-version`` - ``bios-release-date`` - ``system-manufacturer`` - ``system-product-name`` - ``system-version`` - ``system-serial-number`` - ``system-uuid`` - ``baseboard-manufacturer`` - ``baseboard-product-name`` - ``baseboard-version`` - ``baseboard-serial-number`` - ``baseboard-asset-tag`` - ``chassis-manufacturer`` - ``chassis-type`` - ``chassis-version`` - ``chassis-serial-number`` - ``chassis-asset-tag`` - ``processor-family`` - ``processor-manufacturer`` - ``processor-version`` - ``processor-frequency`` clean | Don't return well-known false information | (invalid UUID's, serial 000000000's, etcetera) | Defaults to ``True`` CLI Example: .. code-block:: bash salt '*' smbios.get system-uuid clean=False """ val = _dmidecoder("-s {}".format(string)).strip() # Cleanup possible comments in strings. val = "\n".join([v for v in val.split("\n") if not v.startswith("#")]) if val.startswith("/dev/mem") or clean and not _dmi_isclean(string, val): val = None return val def records(rec_type=None, fields=None, clean=True): """ Return DMI records from SMBIOS type Return only records of type(s) The SMBIOS specification defines the following DMI types: ==== ====================================== Type Information ==== ====================================== 0 BIOS 1 System 2 Baseboard 3 Chassis 4 Processor 5 Memory Controller 6 Memory Module 7 Cache 8 Port Connector 9 System Slots 10 On Board Devices 11 OEM Strings 12 System Configuration Options 13 BIOS Language 14 Group Associations 15 System Event Log 16 Physical Memory Array 17 Memory Device 18 32-bit Memory Error 19 Memory Array Mapped Address 20 Memory Device Mapped Address 21 Built-in Pointing Device 22 Portable Battery 23 System Reset 24 Hardware Security 25 System Power Controls 26 Voltage Probe 27 Cooling Device 28 Temperature Probe 29 Electrical Current Probe 30 Out-of-band Remote Access 31 Boot Integrity Services 32 System Boot 33 64-bit Memory Error 34 Management Device 35 Management Device Component 36 Management Device Threshold Data 37 Memory Channel 38 IPMI Device 39 Power Supply 40 Additional Information 41 Onboard Devices Extended Information 42 Management Controller Host Interface ==== ====================================== clean | Don't return well-known false information | (invalid UUID's, serial 000000000's, etcetera) | Defaults to ``True`` CLI Example: .. code-block:: bash salt '*' smbios.records clean=False salt '*' smbios.records 14 salt '*' smbios.records 4 core_count,thread_count,current_speed """ if rec_type is None: smbios = _dmi_parse(_dmidecoder(), clean, fields) else: smbios = _dmi_parse(_dmidecoder("-t {}".format(rec_type)), clean, fields) return smbios def _dmi_parse(data, clean=True, fields=None): """ Structurize DMI records into a nice list Optionally trash bogus entries and filter output """ dmi = [] # Detect & split Handle records dmi_split = re.compile( "(handle [0-9]x[0-9a-f]+[^\n]+)\n", re.MULTILINE + re.IGNORECASE ) dmi_raw = iter(re.split(dmi_split, data)[1:]) for handle, dmi_raw in zip(dmi_raw, dmi_raw): handle, htype = [hline.split()[-1] for hline in handle.split(",")][0:2] dmi_raw = dmi_raw.split("\n") # log.debug('%s record contains %s', handle, dmi_raw) log.debug("Parsing handle %s", handle) # The first line of a handle is a description of the type record = { "handle": handle, "description": dmi_raw.pop(0).strip(), "type": int(htype), } if not dmi_raw: # empty record if not clean: dmi.append(record) continue # log.debug('%s record contains %s', record, dmi_raw) dmi_data = _dmi_data(dmi_raw, clean, fields) if dmi_data: record["data"] = dmi_data dmi.append(record) elif not clean: dmi.append(record) return dmi def _dmi_data(dmi_raw, clean, fields): """ Parse the raw DMIdecode output of a single handle into a nice dict """ dmi_data = {} key = None key_data = [None, []] for line in dmi_raw: if re.match(r"\t[^\s]+", line): # Finish previous key if key is not None: # log.debug('Evaluating DMI key {0}: {1}'.format(key, key_data)) value, vlist = key_data if vlist: if value is not None: # On the rare occasion # (I counted 1 on all systems we have) # that there's both a value <and> a list # just insert the value on top of the list vlist.insert(0, value) dmi_data[key] = vlist elif value is not None: dmi_data[key] = value # Family: Core i5 # Keyboard Password Status: Not Implemented key, val = line.split(":", 1) key = key.strip().lower().replace(" ", "_") if (clean and key == "header_and_data") or (fields and key not in fields): key = None continue else: key_data = [_dmi_cast(key, val.strip(), clean), []] elif key is None: continue elif re.match(r"\t\t[^\s]+", line): # Installable Languages: 1 # en-US # Characteristics: # PCI is supported # PNP is supported val = _dmi_cast(key, line.strip(), clean) if val is not None: # log.debug('DMI key %s gained list item %s', key, val) key_data[1].append(val) return dmi_data def _dmi_cast(key, val, clean=True): """ Simple caster thingy for trying to fish out at least ints & lists from strings """ if clean and not _dmi_isclean(key, val): return elif not re.match(r"serial|part|asset|product", key, flags=re.IGNORECASE): if "," in val: val = [el.strip() for el in val.split(",")] else: try: val = int(val) except Exception: # pylint: disable=broad-except pass return val def _dmi_isclean(key, val): """ Clean out well-known bogus values """ if val is None or not val or re.match("none", val, flags=re.IGNORECASE): # log.debug('DMI {0} value {1} seems invalid or empty'.format(key, val)) return False elif "uuid" in key: # Try each version (1-5) of RFC4122 to check if it's actually a UUID for uuidver in range(1, 5): try: uuid.UUID(val, version=uuidver) return True except ValueError: continue log.trace("DMI %s value %s is an invalid UUID", key, val.replace("\n", " ")) return False elif re.search("serial|part|version", key): # 'To be filled by O.E.M. # 'Not applicable' etc. # 'Not specified' etc. # 0000000, 1234667 etc. # begone! return ( not re.match(r"^[0]+$", val) and not re.match(r"[0]?1234567[8]?[9]?[0]?", val) and not re.search( r"sernum|part[_-]?number|specified|filled|applicable", val, flags=re.IGNORECASE, ) ) elif re.search("asset|manufacturer", key): # AssetTag0. Manufacturer04. Begone. return not re.search( r"manufacturer|to be filled|available|asset|^no(ne|t)", val, flags=re.IGNORECASE, ) else: # map unspecified, undefined, unknown & whatever to None return not re.search( r"to be filled", val, flags=re.IGNORECASE ) and not re.search( r"un(known|specified)|no(t|ne)?" r" (asset|provided|defined|available|present|specified)", val, flags=re.IGNORECASE, ) def _dmidecoder(args=None): """ Call DMIdecode """ dmidecoder = salt.utils.path.which_bin(["dmidecode", "smbios"]) if not args: out = salt.modules.cmdmod._run_quiet(dmidecoder) else: out = salt.modules.cmdmod._run_quiet("{} {}".format(dmidecoder, args)) return out
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/smbios.py
0.593374
0.175344
smbios.py
pypi
import logging import salt.utils.path log = logging.getLogger(__name__) def __virtual__(): """ Only load if pcs package is installed """ if salt.utils.path.which("pcs"): return "pcs" return (False, "Missing dependency: pcs") def __use_new_commands(): """ The command line arguments of pcs changed after version 0.10 This will return True if the new arguments are needed and false if the old ones are needed """ pcs_version = __salt__["pkg.version"]("pcs") log.debug("PCS package version %s", pcs_version) if __salt__["pkg.version_cmp"](pcs_version, "0.10") == 1: log.debug("New version, new command") return True else: log.debug("Old Version") return False def item_show( item, item_id=None, item_type=None, show="show", extra_args=None, cibfile=None ): """ Show an item via pcs command (mainly for use with the pcs state module) item config, property, resource, constraint etc. item_id id of the item item_type item type show show command (probably None, default: show or status for newer implementation) extra_args additional options for the pcs command cibfile use cibfile instead of the live CIB """ new_commands = __use_new_commands() cmd = ["pcs"] if isinstance(cibfile, str): cmd += ["-f", cibfile] if isinstance(item, str): cmd += [item] elif isinstance(item, (list, tuple)): cmd += item # constraint command follows a different order if item in ["constraint"]: cmd += [item_type] # New implementions use config instead of show. This resolves that issue. if new_commands and ( item != "config" and item != "constraint" and item != "property" ): if show == "show": show = "config" elif isinstance(show, (list, tuple)): for index, value in enumerate(show): if show[index] == "show": show[index] = "config" if isinstance(show, str): cmd += [show] elif isinstance(show, (list, tuple)): cmd += show if isinstance(item_id, str): cmd += [item_id] if isinstance(extra_args, (list, tuple)): cmd += extra_args # constraint command only shows id, when using '--full'-parameter if item in ["constraint"]: if not isinstance(extra_args, (list, tuple)) or "--full" not in extra_args: cmd += ["--full"] log.debug("Running item show %s", cmd) return __salt__["cmd.run_all"](cmd, output_loglevel="trace", python_shell=False) def item_create( item, item_id, item_type, create="create", extra_args=None, cibfile=None ): """ Create an item via pcs command (mainly for use with the pcs state module) item config, property, resource, constraint etc. item_id id of the item item_type item type create create command (create or set f.e., default: create) extra_args additional options for the pcs command cibfile use cibfile instead of the live CIB """ cmd = ["pcs"] if isinstance(cibfile, str): cmd += ["-f", cibfile] if isinstance(item, str): cmd += [item] elif isinstance(item, (list, tuple)): cmd += item # constraint command follows a different order if item in ["constraint"]: if isinstance(item_type, str): cmd += [item_type] if isinstance(create, str): cmd += [create] elif isinstance(create, (list, tuple)): cmd += create # constraint command needs item_id in format 'id=<id' after all params # constraint command follows a different order if item not in ["constraint"]: cmd += [item_id] if isinstance(item_type, str): cmd += [item_type] if isinstance(extra_args, (list, tuple)): # constraint command needs item_id in format 'id=<id' after all params if item in ["constraint"]: extra_args = extra_args + ["id={}".format(item_id)] cmd += extra_args return __salt__["cmd.run_all"](cmd, output_loglevel="trace", python_shell=False) def auth(nodes, pcsuser="hacluster", pcspasswd="hacluster", extra_args=None): """ Authorize nodes to the cluster nodes a list of nodes which should be authorized to the cluster pcsuser user for communitcation with PCS (default: hacluster) pcspasswd password for pcsuser (default: hacluster) extra_args list of extra option for the \'pcs cluster auth\' command. The newer cluster host command has no extra args and so will ignore it. CLI Example: .. code-block:: bash salt '*' pcs.auth nodes='[ node1.example.org node2.example.org ]' pcsuser=hacluster pcspasswd=hoonetorg extra_args=[ '--force' ] """ if __use_new_commands(): cmd = ["pcs", "host", "auth"] else: cmd = ["pcs", "cluster", "auth"] cmd.extend(["-u", pcsuser, "-p", pcspasswd]) if not __use_new_commands() and isinstance(extra_args, (list, tuple)): cmd += extra_args cmd += nodes return __salt__["cmd.run_all"](cmd, output_loglevel="trace", python_shell=False) def is_auth(nodes, pcsuser="hacluster", pcspasswd="hacluster"): """ Check if nodes are already authorized nodes a list of nodes to be checked for authorization to the cluster pcsuser user for communitcation with PCS (default: hacluster) pcspasswd password for pcsuser (default: hacluster) CLI Example: .. code-block:: bash salt '*' pcs.is_auth nodes='[node1.example.org node2.example.org]' pcsuser=hacluster pcspasswd=hoonetorg """ if __use_new_commands(): cmd = ["pcs", "host", "auth", "-u", pcsuser, "-p", pcspasswd] else: cmd = ["pcs", "cluster", "auth"] cmd += nodes return __salt__["cmd.run_all"]( cmd, stdin="\n\n", output_loglevel="trace", python_shell=False ) def cluster_setup(nodes, pcsclustername="pcscluster", extra_args=None): """ Setup pacemaker cluster via pcs command nodes a list of nodes which should be set up pcsclustername Name of the Pacemaker cluster (default: pcscluster) extra_args list of extra option for the \'pcs cluster setup\' command CLI Example: .. code-block:: bash salt '*' pcs.cluster_setup nodes='[ node1.example.org node2.example.org ]' pcsclustername=pcscluster """ cmd = ["pcs", "cluster", "setup"] if __use_new_commands(): cmd += [pcsclustername] else: cmd += ["--name", pcsclustername] cmd += nodes if isinstance(extra_args, (list, tuple)): cmd += extra_args log.debug("Running cluster setup: %s", cmd) return __salt__["cmd.run_all"](cmd, output_loglevel="trace", python_shell=False) def cluster_destroy(extra_args=None): """ Destroy corosync cluster using the pcs command extra_args list of extra option for the \'pcs cluster destroy\' command (only really --all) CLI Example: .. code-block:: bash salt '*' pcs.cluster_destroy extra_args=--all """ cmd = ["pcs", "cluster", "destroy"] if isinstance(extra_args, (list, tuple)): cmd += extra_args log.debug("Running cluster destroy: %s", cmd) return __salt__["cmd.run_all"](cmd, output_loglevel="trace", python_shell=False) def cluster_node_add(node, extra_args=None): """ Add a node to the pacemaker cluster via pcs command node node that should be added extra_args list of extra option for the \'pcs cluster node add\' command CLI Example: .. code-block:: bash salt '*' pcs.cluster_node_add node=node2.example.org """ cmd = ["pcs", "cluster", "node", "add"] cmd += [node] if isinstance(extra_args, (list, tuple)): cmd += extra_args return __salt__["cmd.run_all"](cmd, output_loglevel="trace", python_shell=False) def cib_create(cibfile, scope="configuration", extra_args=None): """ Create a CIB-file from the current CIB of the cluster cibfile name/path of the file containing the CIB scope specific section of the CIB (default: configuration) extra_args additional options for creating the CIB-file CLI Example: .. code-block:: bash salt '*' pcs.cib_create cibfile='/tmp/VIP_apache_1.cib' scope=False """ cmd = ["pcs", "cluster", "cib", cibfile] if isinstance(scope, str): cmd += ["scope={}".format(scope)] if isinstance(extra_args, (list, tuple)): cmd += extra_args return __salt__["cmd.run_all"](cmd, output_loglevel="trace", python_shell=False) def cib_push(cibfile, scope="configuration", extra_args=None): """ Push a CIB-file as the new CIB to the cluster cibfile name/path of the file containing the CIB scope specific section of the CIB (default: configuration) extra_args additional options for creating the CIB-file CLI Example: .. code-block:: bash salt '*' pcs.cib_push cibfile='/tmp/VIP_apache_1.cib' scope=False """ cmd = ["pcs", "cluster", "cib-push", cibfile] if isinstance(scope, str): cmd += ["scope={}".format(scope)] if isinstance(extra_args, (list, tuple)): cmd += extra_args return __salt__["cmd.run_all"](cmd, output_loglevel="trace", python_shell=False) def config_show(cibfile=None): """ Show config of cluster cibfile name/path of the file containing the CIB CLI Example: .. code-block:: bash salt '*' pcs.config_show cibfile='/tmp/cib_for_galera' """ return item_show(item="config", item_id=None, extra_args=None, cibfile=cibfile) def prop_show(prop, extra_args=None, cibfile=None): """ Show the value of a cluster property prop name of the property extra_args additional options for the pcs property command cibfile use cibfile instead of the live CIB CLI Example: .. code-block:: bash salt '*' pcs.prop_show cibfile='/tmp/2_node_cluster.cib' prop='no-quorum-policy' cibfile='/tmp/2_node_cluster.cib' """ return item_show( item="property", item_id=prop, extra_args=extra_args, cibfile=cibfile ) def prop_set(prop, value, extra_args=None, cibfile=None): """ Set the value of a cluster property prop name of the property value value of the property prop extra_args additional options for the pcs property command cibfile use cibfile instead of the live CIB CLI Example: .. code-block:: bash salt '*' pcs.prop_set prop='no-quorum-policy' value='ignore' cibfile='/tmp/2_node_cluster.cib' """ return item_create( item="property", item_id="{}={}".format(prop, value), item_type=None, create="set", extra_args=extra_args, cibfile=cibfile, ) def stonith_show(stonith_id, extra_args=None, cibfile=None): """ Show the value of a cluster stonith stonith_id name for the stonith resource extra_args additional options for the pcs stonith command cibfile use cibfile instead of the live CIB CLI Example: .. code-block:: bash salt '*' pcs.stonith_show stonith_id='eps_fence' cibfile='/tmp/2_node_cluster.cib' """ return item_show( item="stonith", item_id=stonith_id, extra_args=extra_args, cibfile=cibfile ) def stonith_create( stonith_id, stonith_device_type, stonith_device_options=None, cibfile=None ): """ Create a stonith resource via pcs command stonith_id name for the stonith resource stonith_device_type name of the stonith agent fence_eps, fence_xvm f.e. stonith_device_options additional options for creating the stonith resource cibfile use cibfile instead of the live CIB for manipulation CLI Example: .. code-block:: bash salt '*' pcs.stonith_create stonith_id='eps_fence' stonith_device_type='fence_eps' stonith_device_options="['pcmk_host_map=node1.example.org:01;node2.example.org:02', 'ipaddr=myepsdevice.example.org', 'action=reboot', 'power_wait=5', 'verbose=1', 'debug=/var/log/pcsd/eps_fence.log', 'login=hidden', 'passwd=hoonetorg']" cibfile='/tmp/cib_for_stonith.cib' """ return item_create( item="stonith", item_id=stonith_id, item_type=stonith_device_type, extra_args=stonith_device_options, cibfile=cibfile, ) def resource_show(resource_id, extra_args=None, cibfile=None): """ Show a resource via pcs command resource_id name of the resource extra_args additional options for the pcs command cibfile use cibfile instead of the live CIB CLI Example: .. code-block:: bash salt '*' pcs.resource_show resource_id='galera' cibfile='/tmp/cib_for_galera.cib' """ return item_show( item="resource", item_id=resource_id, extra_args=extra_args, cibfile=cibfile ) def resource_create(resource_id, resource_type, resource_options=None, cibfile=None): """ Create a resource via pcs command resource_id name for the resource resource_type resource type (f.e. ocf:heartbeat:IPaddr2 or VirtualIP) resource_options additional options for creating the resource cibfile use cibfile instead of the live CIB for manipulation CLI Example: .. code-block:: bash salt '*' pcs.resource_create resource_id='galera' resource_type='ocf:heartbeat:galera' resource_options="['wsrep_cluster_address=gcomm://node1.example.org,node2.example.org,node3.example.org', '--master']" cibfile='/tmp/cib_for_galera.cib' """ return item_create( item="resource", item_id=resource_id, item_type=resource_type, extra_args=resource_options, cibfile=cibfile, )
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/pcs.py
0.454714
0.16975
pcs.py
pypi
import logging import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = "virt" def __virtual__(): """ Provides virt on SmartOS """ if salt.utils.platform.is_smartos_globalzone() and salt.utils.path.which("vmadm"): return __virtualname__ return ( False, "{} module can only be loaded on SmartOS compute nodes".format(__virtualname__), ) def init(**kwargs): """ Initialize a new VM CLI Example: .. code-block:: bash salt '*' virt.init image_uuid='...' alias='...' [...] """ return __salt__["vmadm.create"](**kwargs) def list_domains(): """ Return a list of virtual machine names on the minion CLI Example: .. code-block:: bash salt '*' virt.list_domains """ data = __salt__["vmadm.list"](keyed=True) vms = [ "UUID TYPE RAM STATE ALIAS" ] for vm in data: vms.append( "{vmuuid}{vmtype}{vmram}{vmstate}{vmalias}".format( vmuuid=vm.ljust(38), vmtype=data[vm]["type"].ljust(6), vmram=data[vm]["ram"].ljust(9), vmstate=data[vm]["state"].ljust(18), vmalias=data[vm]["alias"], ) ) return vms def list_active_vms(): """ Return a list of uuids for active virtual machine on the minion CLI Example: .. code-block:: bash salt '*' virt.list_active_vms """ return __salt__["vmadm.list"](search="state='running'", order="uuid") def list_inactive_vms(): """ Return a list of uuids for inactive virtual machine on the minion CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms """ return __salt__["vmadm.list"](search="state='stopped'", order="uuid") def vm_info(domain): """ Return a dict with information about the specified VM on this CN CLI Example: .. code-block:: bash salt '*' virt.vm_info <domain> """ return __salt__["vmadm.get"](domain) def start(domain): """ Start a defined domain CLI Example: .. code-block:: bash salt '*' virt.start <domain> """ if domain in list_active_vms(): raise CommandExecutionError("The specified vm is already running") __salt__["vmadm.start"](domain) return domain in list_active_vms() def shutdown(domain): """ Send a soft shutdown signal to the named vm CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> """ if domain in list_inactive_vms(): raise CommandExecutionError("The specified vm is already stopped") __salt__["vmadm.stop"](domain) return domain in list_inactive_vms() def reboot(domain): """ Reboot a domain via ACPI request CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> """ if domain in list_inactive_vms(): raise CommandExecutionError("The specified vm is stopped") __salt__["vmadm.reboot"](domain) return domain in list_active_vms() def stop(domain): """ Hard power down the virtual machine, this is equivalent to powering off the hardware. CLI Example: .. code-block:: bash salt '*' virt.destroy <domain> """ if domain in list_inactive_vms(): raise CommandExecutionError("The specified vm is stopped") return __salt__["vmadm.delete"](domain) def vm_virt_type(domain): """ Return VM virtualization type : OS or KVM CLI Example: .. code-block:: bash salt '*' virt.vm_virt_type <domain> """ ret = __salt__["vmadm.lookup"]( search="uuid={uuid}".format(uuid=domain), order="type" ) if len(ret) < 1: raise CommandExecutionError("We can't determine the type of this VM") return ret[0]["type"] def setmem(domain, memory): """ Change the amount of memory allocated to VM. <memory> is to be specified in MB. Note for KVM : this would require a restart of the VM. CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> 512 """ vmtype = vm_virt_type(domain) if vmtype == "OS": return __salt__["vmadm.update"](vm=domain, max_physical_memory=memory) elif vmtype == "LX": return __salt__["vmadm.update"](vm=domain, max_physical_memory=memory) elif vmtype == "KVM": log.warning("Changes will be applied after the VM restart.") return __salt__["vmadm.update"](vm=domain, ram=memory) else: raise CommandExecutionError("Unknown VM type") return False def get_macs(domain): """ Return a list off MAC addresses from the named VM CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> """ macs = [] ret = __salt__["vmadm.lookup"]( search="uuid={uuid}".format(uuid=domain), order="nics" ) if len(ret) < 1: raise CommandExecutionError("We can't find the MAC address of this VM") else: for nic in ret[0]["nics"]: macs.append(nic["mac"]) return macs
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/smartos_virt.py
0.715623
0.216798
smartos_virt.py
pypi
import logging import salt.utils.files import salt.utils.path log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = "rbac" def __virtual__(): """ Provides rbac if we are running on a solaris like system """ if __grains__["kernel"] == "SunOS" and salt.utils.path.which("profiles"): return __virtualname__ return ( False, "{} module can only be loaded on a solaris like system".format(__virtualname__), ) def profile_list(default_only=False): """ List all available profiles default_only : boolean return only default profile CLI Example: .. code-block:: bash salt '*' rbac.profile_list """ profiles = {} default_profiles = ["All"] ## lookup default profile(s) with salt.utils.files.fopen("/etc/security/policy.conf", "r") as policy_conf: for policy in policy_conf: policy = salt.utils.stringutils.to_unicode(policy) policy = policy.split("=") if policy[0].strip() == "PROFS_GRANTED": default_profiles.extend(policy[1].strip().split(",")) ## read prof_attr file (profname:res1:res2:desc:attr) with salt.utils.files.fopen("/etc/security/prof_attr", "r") as prof_attr: for profile in prof_attr: profile = salt.utils.stringutils.to_unicode(profile) profile = profile.split(":") # skip comments and non complaint lines if len(profile) != 5: continue # add profile info to dict profiles[profile[0]] = profile[3] ## filtered profiles if default_only: for p in [p for p in profiles if p not in default_profiles]: del profiles[p] return profiles def profile_get(user, default_hidden=True): """ List profiles for user user : string username default_hidden : boolean hide default profiles CLI Example: .. code-block:: bash salt '*' rbac.profile_get leo salt '*' rbac.profile_get leo default_hidden=False """ user_profiles = [] ## read user_attr file (user:qualifier:res1:res2:attr) with salt.utils.files.fopen("/etc/user_attr", "r") as user_attr: for profile in user_attr: profile = salt.utils.stringutils.to_unicode(profile) profile = profile.strip().split(":") # skip comments and non complaint lines if len(profile) != 5: continue # skip other users if profile[0] != user: continue # parse attr attrs = {} for attr in profile[4].strip().split(";"): attr_key, attr_val = attr.strip().split("=") if attr_key in ["auths", "profiles", "roles"]: attrs[attr_key] = attr_val.strip().split(",") else: attrs[attr_key] = attr_val if "profiles" in attrs: user_profiles.extend(attrs["profiles"]) ## remove default profiles if default_hidden: for profile in profile_list(default_only=True): if profile in user_profiles: user_profiles.remove(profile) return list(set(user_profiles)) def profile_add(user, profile): """ Add profile to user user : string username profile : string profile name CLI Example: .. code-block:: bash salt '*' rbac.profile_add martine 'Primary Administrator' salt '*' rbac.profile_add martine 'User Management,User Security' """ ret = {} ## validate profiles profiles = profile.split(",") known_profiles = profile_list().keys() valid_profiles = [p for p in profiles if p in known_profiles] log.debug( "rbac.profile_add - profiles=%s, known_profiles=%s, valid_profiles=%s", profiles, known_profiles, valid_profiles, ) ## update user profiles if len(valid_profiles) > 0: res = __salt__["cmd.run_all"]( 'usermod -P "{profiles}" {login}'.format( login=user, profiles=",".join(set(profile_get(user) + valid_profiles)), ) ) if res["retcode"] > 0: ret["Error"] = { "retcode": res["retcode"], "message": res["stderr"] if "stderr" in res else res["stdout"], } return ret ## update return value active_profiles = profile_get(user, False) for p in profiles: if p not in valid_profiles: ret[p] = "Unknown" elif p in active_profiles: ret[p] = "Added" else: ret[p] = "Failed" return ret def profile_rm(user, profile): """ Remove profile from user user : string username profile : string profile name CLI Example: .. code-block:: bash salt '*' rbac.profile_rm jorge 'Primary Administrator' salt '*' rbac.profile_rm jorge 'User Management,User Security' """ ret = {} ## validate profiles profiles = profile.split(",") known_profiles = profile_list().keys() valid_profiles = [p for p in profiles if p in known_profiles] log.debug( "rbac.profile_rm - profiles=%s, known_profiles=%s, valid_profiles=%s", profiles, known_profiles, valid_profiles, ) ## update user profiles if len(valid_profiles) > 0: res = __salt__["cmd.run_all"]( 'usermod -P "{profiles}" {login}'.format( login=user, profiles=",".join( [p for p in profile_get(user) if p not in valid_profiles] ), ) ) if res["retcode"] > 0: ret["Error"] = { "retcode": res["retcode"], "message": res["stderr"] if "stderr" in res else res["stdout"], } return ret ## update return value active_profiles = profile_get(user, False) for p in profiles: if p not in valid_profiles: ret[p] = "Unknown" elif p in active_profiles: ret[p] = "Failed" else: ret[p] = "Remove" return ret def role_list(): """ List all available roles CLI Example: .. code-block:: bash salt '*' rbac.role_list """ roles = {} ## read user_attr file (user:qualifier:res1:res2:attr) with salt.utils.files.fopen("/etc/user_attr", "r") as user_attr: for role in user_attr: role = salt.utils.stringutils.to_unicode(role) role = role.split(":") # skip comments and non complaint lines if len(role) != 5: continue # parse attr attrs = {} for attr in role[4].split(";"): attr_key, attr_val = attr.split("=") if attr_key in ["auths", "profiles", "roles"]: attrs[attr_key] = attr_val.split(",") else: attrs[attr_key] = attr_val role[4] = attrs # add role info to dict if "type" in role[4] and role[4]["type"] == "role": del role[4]["type"] roles[role[0]] = role[4] return roles def role_get(user): """ List roles for user user : string username CLI Example: .. code-block:: bash salt '*' rbac.role_get leo """ user_roles = [] ## read user_attr file (user:qualifier:res1:res2:attr) with salt.utils.files.fopen("/etc/user_attr", "r") as user_attr: for role in user_attr: role = salt.utils.stringutils.to_unicode(role) role = role.strip().strip().split(":") # skip comments and non complaint lines if len(role) != 5: continue # skip other users if role[0] != user: continue # parse attr attrs = {} for attr in role[4].strip().split(";"): attr_key, attr_val = attr.strip().split("=") if attr_key in ["auths", "profiles", "roles"]: attrs[attr_key] = attr_val.strip().split(",") else: attrs[attr_key] = attr_val if "roles" in attrs: user_roles.extend(attrs["roles"]) return list(set(user_roles)) def role_add(user, role): """ Add role to user user : string username role : string role name CLI Example: .. code-block:: bash salt '*' rbac.role_add martine netcfg salt '*' rbac.role_add martine netcfg,zfssnap """ ret = {} ## validate roles roles = role.split(",") known_roles = role_list().keys() valid_roles = [r for r in roles if r in known_roles] log.debug( "rbac.role_add - roles=%s, known_roles=%s, valid_roles=%s", roles, known_roles, valid_roles, ) ## update user roles if len(valid_roles) > 0: res = __salt__["cmd.run_all"]( 'usermod -R "{roles}" {login}'.format( login=user, roles=",".join(set(role_get(user) + valid_roles)), ) ) if res["retcode"] > 0: ret["Error"] = { "retcode": res["retcode"], "message": res["stderr"] if "stderr" in res else res["stdout"], } return ret ## update return value active_roles = role_get(user) for r in roles: if r not in valid_roles: ret[r] = "Unknown" elif r in active_roles: ret[r] = "Added" else: ret[r] = "Failed" return ret def role_rm(user, role): """ Remove role from user user : string username role : string role name CLI Example: .. code-block:: bash salt '*' rbac.role_rm jorge netcfg salt '*' rbac.role_rm jorge netcfg,zfssnap """ ret = {} ## validate roles roles = role.split(",") known_roles = role_list().keys() valid_roles = [r for r in roles if r in known_roles] log.debug( "rbac.role_rm - roles=%s, known_roles=%s, valid_roles=%s", roles, known_roles, valid_roles, ) ## update user roles if len(valid_roles) > 0: res = __salt__["cmd.run_all"]( 'usermod -R "{roles}" {login}'.format( login=user, roles=",".join([r for r in role_get(user) if r not in valid_roles]), ) ) if res["retcode"] > 0: ret["Error"] = { "retcode": res["retcode"], "message": res["stderr"] if "stderr" in res else res["stdout"], } return ret ## update return value active_roles = role_get(user) for r in roles: if r not in valid_roles: ret[r] = "Unknown" elif r in active_roles: ret[r] = "Failed" else: ret[r] = "Remove" return ret def auth_list(): """ List all available authorization CLI Example: .. code-block:: bash salt '*' rbac.auth_list """ auths = {} ## read auth_attr file (name:res1:res2:short_desc:long_desc:attr) with salt.utils.files.fopen("/etc/security/auth_attr", "r") as auth_attr: for auth in auth_attr: auth = salt.utils.stringutils.to_unicode(auth) auth = auth.split(":") # skip comments and non complaint lines if len(auth) != 6: continue # add auth info to dict if auth[0][-1:] == ".": auth[0] = "{}*".format(auth[0]) auths[auth[0]] = auth[3] return auths def auth_get(user, computed=True): """ List authorization for user user : string username computed : boolean merge results from `auths` command into data from user_attr CLI Example: .. code-block:: bash salt '*' rbac.auth_get leo """ user_auths = [] ## read user_attr file (user:qualifier:res1:res2:attr) with salt.utils.files.fopen("/etc/user_attr", "r") as user_attr: for auth in user_attr: auth = salt.utils.stringutils.to_unicode(auth) auth = auth.strip().split(":") # skip comments and non complaint lines if len(auth) != 5: continue # skip other users if auth[0] != user: continue # parse attr attrs = {} for attr in auth[4].strip().split(";"): attr_key, attr_val = attr.strip().split("=") if attr_key in ["auths", "profiles", "roles"]: attrs[attr_key] = attr_val.strip().split(",") else: attrs[attr_key] = attr_val if "auths" in attrs: user_auths.extend(attrs["auths"]) ## also parse auths command if computed: res = __salt__["cmd.run_all"]("auths {}".format(user)) if res["retcode"] == 0: for auth in res["stdout"].splitlines(): if "," in auth: user_auths.extend(auth.strip().split(",")) else: user_auths.append(auth.strip()) return list(set(user_auths)) def auth_add(user, auth): """ Add authorization to user user : string username auth : string authorization name CLI Example: .. code-block:: bash salt '*' rbac.auth_add martine solaris.zone.manage salt '*' rbac.auth_add martine solaris.zone.manage,solaris.mail.mailq """ ret = {} ## validate auths auths = auth.split(",") known_auths = auth_list().keys() valid_auths = [r for r in auths if r in known_auths] log.debug( "rbac.auth_add - auths=%s, known_auths=%s, valid_auths=%s", auths, known_auths, valid_auths, ) ## update user auths if len(valid_auths) > 0: res = __salt__["cmd.run_all"]( 'usermod -A "{auths}" {login}'.format( login=user, auths=",".join(set(auth_get(user, False) + valid_auths)), ) ) if res["retcode"] > 0: ret["Error"] = { "retcode": res["retcode"], "message": res["stderr"] if "stderr" in res else res["stdout"], } return ret ## update return value active_auths = auth_get(user, False) for a in auths: if a not in valid_auths: ret[a] = "Unknown" elif a in active_auths: ret[a] = "Added" else: ret[a] = "Failed" return ret def auth_rm(user, auth): """ Remove authorization from user user : string username auth : string authorization name CLI Example: .. code-block:: bash salt '*' rbac.auth_rm jorge solaris.zone.manage salt '*' rbac.auth_rm jorge solaris.zone.manage,solaris.mail.mailq """ ret = {} ## validate auths auths = auth.split(",") known_auths = auth_list().keys() valid_auths = [a for a in auths if a in known_auths] log.debug( "rbac.auth_rm - auths=%s, known_auths=%s, valid_auths=%s", auths, known_auths, valid_auths, ) ## update user auths if len(valid_auths) > 0: res = __salt__["cmd.run_all"]( 'usermod -A "{auths}" {login}'.format( login=user, auths=",".join( [a for a in auth_get(user, False) if a not in valid_auths] ), ) ) if res["retcode"] > 0: ret["Error"] = { "retcode": res["retcode"], "message": res["stderr"] if "stderr" in res else res["stdout"], } return ret ## update return value active_auths = auth_get(user, False) for a in auths: if a not in valid_auths: ret[a] = "Unknown" elif a in active_auths: ret[a] = "Failed" else: ret[a] = "Remove" return ret # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/rbac_solaris.py
0.555435
0.157234
rbac_solaris.py
pypi
import hashlib import logging import os.path import random import signal import salt.utils.path log = logging.getLogger(__name__) def __virtual__(): """ Only load the module if znc is installed """ if salt.utils.path.which("znc"): return "znc" return (False, "Module znc: znc binary not found") def _makepass(password, hasher="sha256"): """ Create a znc compatible hashed password """ # Setup the hasher if hasher == "sha256": h = hashlib.sha256(password) elif hasher == "md5": h = hashlib.md5(password) else: return NotImplemented c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!?.,:;/*-+_()" r = { "Method": h.name, "Salt": "".join(random.SystemRandom().choice(c) for x in range(20)), } # Salt the password hash h.update(r["Salt"]) r["Hash"] = h.hexdigest() return r def buildmod(*modules): """ Build module using znc-buildmod CLI Example: .. code-block:: bash salt '*' znc.buildmod module.cpp [...] """ # Check if module files are missing missing = [module for module in modules if not os.path.exists(module)] if missing: return "Error: The file ({}) does not exist.".format(", ".join(missing)) cmd = ["znc-buildmod"] cmd.extend(modules) out = __salt__["cmd.run"](cmd, python_shell=False).splitlines() return out[-1] def dumpconf(): """ Write the active configuration state to config file CLI Example: .. code-block:: bash salt '*' znc.dumpconf """ return __salt__["ps.pkill"]("znc", signal=signal.SIGUSR1) def rehashconf(): """ Rehash the active configuration state from config file CLI Example: .. code-block:: bash salt '*' znc.rehashconf """ return __salt__["ps.pkill"]("znc", signal=signal.SIGHUP) def version(): """ Return server version from znc --version CLI Example: .. code-block:: bash salt '*' znc.version """ cmd = ["znc", "--version"] out = __salt__["cmd.run"](cmd, python_shell=False).splitlines() ret = out[0].split(" - ") return ret[0]
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/znc.py
0.541894
0.199756
znc.py
pypi
import copy import logging import os import salt.utils.data from salt.exceptions import SaltCloudConfigError try: import salt.cloud HAS_SALTCLOUD = True except ImportError: HAS_SALTCLOUD = False log = logging.getLogger(__name__) __func_alias__ = {"profile_": "profile"} def __virtual__(): """ Only work on POSIX-like systems """ if HAS_SALTCLOUD: return True return ( False, "The cloud execution module cannot be loaded: only available on non-Windows" " systems.", ) def _get_client(): """ Return a cloud client """ client = salt.cloud.CloudClient( os.path.join(os.path.dirname(__opts__["conf_file"]), "cloud"), pillars=copy.deepcopy(__pillar__.get("cloud", {})), ) return client def list_sizes(provider="all"): """ List cloud provider sizes for the given providers CLI Example: .. code-block:: bash salt minionname cloud.list_sizes my-gce-config """ client = _get_client() sizes = client.list_sizes(provider) return sizes def list_images(provider="all"): """ List cloud provider images for the given providers CLI Example: .. code-block:: bash salt minionname cloud.list_images my-gce-config """ client = _get_client() images = client.list_images(provider) return images def list_locations(provider="all"): """ List cloud provider locations for the given providers CLI Example: .. code-block:: bash salt minionname cloud.list_locations my-gce-config """ client = _get_client() locations = client.list_locations(provider) return locations def query(query_type="list_nodes"): """ List cloud provider data for all providers CLI Examples: .. code-block:: bash salt minionname cloud.query salt minionname cloud.query list_nodes_full salt minionname cloud.query list_nodes_select """ client = _get_client() info = client.query(query_type) return info def full_query(query_type="list_nodes_full"): """ List all available cloud provider data CLI Example: .. code-block:: bash salt minionname cloud.full_query """ return query(query_type=query_type) def select_query(query_type="list_nodes_select"): """ List selected nodes CLI Example: .. code-block:: bash salt minionname cloud.select_query """ return query(query_type=query_type) def has_instance(name, provider=None): """ Return true if the instance is found on a provider CLI Example: .. code-block:: bash salt minionname cloud.has_instance myinstance """ data = get_instance(name, provider) if data is None: return False return True def get_instance(name, provider=None): """ Return details on an instance. Similar to the cloud action show_instance but returns only the instance details. CLI Example: .. code-block:: bash salt minionname cloud.get_instance myinstance SLS Example: .. code-block:: bash {{ salt['cloud.get_instance']('myinstance')['mac_address'] }} """ data = action(fun="show_instance", names=[name], provider=provider) info = salt.utils.data.simple_types_filter(data) try: # get the first: [alias][driver][vm_name] info = next(iter(next(iter(next(iter(info.values())).values())).values())) except AttributeError: return None return info def profile_(profile, names, vm_overrides=None, opts=None, **kwargs): """ Spin up an instance using Salt Cloud CLI Example: .. code-block:: bash salt minionname cloud.profile my-gce-config myinstance """ client = _get_client() if isinstance(opts, dict): client.opts.update(opts) info = client.profile(profile, names, vm_overrides=vm_overrides, **kwargs) return info def map_run(path=None, **kwargs): """ Execute a salt cloud map file Cloud Map data can be retrieved from several sources: - a local file (provide the path to the file to the 'path' argument) - a JSON-formatted map directly (provide the appropriately formatted to using the 'map_data' argument) - the Salt Pillar (provide the map name of under 'pillar:cloud:maps' to the 'map_pillar' argument) .. note:: Only one of these sources can be read at a time. The options are listed in their order of precedence. CLI Examples: .. code-block:: bash salt minionname cloud.map_run /path/to/cloud.map salt minionname cloud.map_run path=/path/to/cloud.map salt minionname cloud.map_run map_pillar='<map_pillar>' .. versionchanged:: 2018.3.1 salt minionname cloud.map_run map_data='<actual map data>' """ client = _get_client() info = client.map_run(path, **kwargs) return info def destroy(names): """ Destroy the named VM(s) CLI Example: .. code-block:: bash salt minionname cloud.destroy myinstance """ client = _get_client() info = client.destroy(names) return info def action(fun=None, cloudmap=None, names=None, provider=None, instance=None, **kwargs): """ Execute a single action on the given provider/instance CLI Example: .. code-block:: bash salt minionname cloud.action start instance=myinstance salt minionname cloud.action stop instance=myinstance salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f """ client = _get_client() try: info = client.action(fun, cloudmap, names, provider, instance, kwargs) except SaltCloudConfigError as err: log.error(err) return None return info def create(provider, names, opts=None, **kwargs): """ Create an instance using Salt Cloud CLI Example: .. code-block:: bash salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True """ client = _get_client() if isinstance(opts, dict): client.opts.update(opts) info = client.create(provider, names, **kwargs) return info def volume_list(provider): """ List block storage volumes CLI Example: .. code-block:: bash salt minionname cloud.volume_list my-nova """ client = _get_client() info = client.extra_action(action="volume_list", provider=provider, names="name") return info["name"] def volume_delete(provider, names, **kwargs): """ Delete volume CLI Example: .. code-block:: bash salt minionname cloud.volume_delete my-nova myblock """ client = _get_client() info = client.extra_action( provider=provider, names=names, action="volume_delete", **kwargs ) return info def volume_create(provider, names, **kwargs): """ Create volume CLI Example: .. code-block:: bash salt minionname cloud.volume_create my-nova myblock size=100 voltype=SSD """ client = _get_client() info = client.extra_action( action="volume_create", names=names, provider=provider, **kwargs ) return info def volume_attach(provider, names, **kwargs): """ Attach volume to a server CLI Example: .. code-block:: bash salt minionname cloud.volume_attach my-nova myblock server_name=myserver device='/dev/xvdf' """ client = _get_client() info = client.extra_action( provider=provider, names=names, action="volume_attach", **kwargs ) return info def volume_detach(provider, names, **kwargs): """ Detach volume from a server CLI Example: .. code-block:: bash salt minionname cloud.volume_detach my-nova myblock server_name=myserver """ client = _get_client() info = client.extra_action( provider=provider, names=names, action="volume_detach", **kwargs ) return info def network_list(provider): """ List private networks CLI Example: .. code-block:: bash salt minionname cloud.network_list my-nova """ client = _get_client() return client.extra_action(action="network_list", provider=provider, names="names") def network_create(provider, names, **kwargs): """ Create private network CLI Example: .. code-block:: bash salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24' """ client = _get_client() return client.extra_action( provider=provider, names=names, action="network_create", **kwargs ) def virtual_interface_list(provider, names, **kwargs): """ List virtual interfaces on a server CLI Example: .. code-block:: bash salt minionname cloud.virtual_interface_list my-nova names=['salt-master'] """ client = _get_client() return client.extra_action( provider=provider, names=names, action="virtual_interface_list", **kwargs ) def virtual_interface_create(provider, names, **kwargs): """ Attach private interfaces to a server CLI Example: .. code-block:: bash salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt' """ client = _get_client() return client.extra_action( provider=provider, names=names, action="virtual_interface_create", **kwargs )
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/cloud.py
0.63307
0.179908
cloud.py
pypi
import copy import logging import os from collections.abc import Mapping import salt.pillar import salt.utils.crypt import salt.utils.data import salt.utils.dictupdate import salt.utils.functools import salt.utils.odict import salt.utils.yaml from salt.defaults import DEFAULT_TARGET_DELIM, NOT_SET from salt.exceptions import CommandExecutionError __proxyenabled__ = ["*"] log = logging.getLogger(__name__) def get( key, default=NOT_SET, merge=False, merge_nested_lists=None, delimiter=DEFAULT_TARGET_DELIM, pillarenv=None, saltenv=None, ): """ .. versionadded:: 0.14 Attempt to retrieve the named value from :ref:`in-memory pillar data <pillar-in-memory>`. If the pillar key is not present in the in-memory pillar, then the value specified in the ``default`` option (described below) will be returned. If the merge parameter is set to ``True``, the default will be recursively merged into the returned pillar data. The value can also represent a value in a nested dict using a ":" delimiter for the dict. This means that if a dict in pillar looks like this:: {'pkg': {'apache': 'httpd'}} To retrieve the value associated with the ``apache`` key in the ``pkg`` dict this key can be passed as:: pkg:apache key The pillar key to get value from default The value specified by this option will be returned if the desired pillar key does not exist. If a default value is not specified, then it will be an empty string, unless :conf_minion:`pillar_raise_on_missing` is set to ``True``, in which case an error will be raised. merge : ``False`` If ``True``, the retrieved values will be merged into the passed default. When the default and the retrieved value are both dictionaries, the dictionaries will be recursively merged. .. versionadded:: 2014.7.0 .. versionchanged:: 2016.3.7,2016.11.4,2017.7.0 If the default and the retrieved value are not of the same type, then merging will be skipped and the retrieved value will be returned. Earlier releases raised an error in these cases. merge_nested_lists If set to ``False``, lists nested within the retrieved pillar dictionary will *overwrite* lists in ``default``. If set to ``True``, nested lists will be *merged* into lists in ``default``. If unspecified (the default), this option is inherited from the :conf_minion:`pillar_merge_lists` minion config option. .. note:: This option is ignored when ``merge`` is set to ``False``. .. versionadded:: 2016.11.6 delimiter Specify an alternate delimiter to use when traversing a nested dict. This is useful for when the desired key contains a colon. See CLI example below for usage. .. versionadded:: 2014.7.0 pillarenv If specified, this function will query the master to generate fresh pillar data on the fly, specifically from the requested pillar environment. Note that this can produce different pillar data than executing this function without an environment, as its normal behavior is just to return a value from minion's pillar data in memory (which can be sourced from more than one pillar environment). Using this argument will not affect the pillar data in memory. It will however be slightly slower and use more resources on the master due to the need for the master to generate and send the minion fresh pillar data. This tradeoff in performance however allows for the use case where pillar data is desired only from a single environment. .. versionadded:: 2017.7.0 saltenv Included only for compatibility with :conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt '*' pillar.get pkg:apache salt '*' pillar.get abc::def|ghi delimiter='|' """ if default == NOT_SET: default = KeyError if not __opts__.get("pillar_raise_on_missing"): if default is KeyError: default = "" opt_merge_lists = ( __opts__.get("pillar_merge_lists", False) if merge_nested_lists is None else merge_nested_lists ) pillar_dict = ( __pillar__ if all(x is None for x in (saltenv, pillarenv)) else items(saltenv=saltenv, pillarenv=pillarenv) ) if merge: if isinstance(default, dict): ret = salt.utils.data.traverse_dict_and_list( pillar_dict, key, {}, delimiter ) if isinstance(ret, Mapping): default = copy.deepcopy(default) return salt.utils.dictupdate.update( default, ret, merge_lists=opt_merge_lists ) else: log.error( "pillar.get: Default (%s) is a dict, but the returned " "pillar value (%s) is of type '%s'. Merge will be " "skipped.", default, ret, type(ret).__name__, ) elif isinstance(default, list): ret = salt.utils.data.traverse_dict_and_list( pillar_dict, key, [], delimiter ) if isinstance(ret, list): default = copy.deepcopy(default) default.extend([x for x in ret if x not in default]) return default else: log.error( "pillar.get: Default (%s) is a list, but the returned " "pillar value (%s) is of type '%s'. Merge will be " "skipped.", default, ret, type(ret).__name__, ) else: log.error( "pillar.get: Default (%s) is of type '%s', must be a dict " "or list to merge. Merge will be skipped.", default, type(default).__name__, ) ret = salt.utils.data.traverse_dict_and_list(pillar_dict, key, default, delimiter) if ret is KeyError: raise KeyError("Pillar key not found: {}".format(key)) return ret def items(*args, **kwargs): """ Calls the master for a fresh pillar and generates the pillar data on the fly Contrast with :py:func:`raw` which returns the pillar data that is currently loaded into the minion. pillar If specified, allows for a dictionary of pillar data to be made available to pillar and ext_pillar rendering. these pillar variables will also override any variables of the same name in pillar or ext_pillar. .. versionadded:: 2015.5.0 pillar_enc If specified, the data passed in the ``pillar`` argument will be passed through this renderer to decrypt it. .. note:: This will decrypt on the minion side, so the specified renderer must be set up on the minion for this to work. Alternatively, pillar data can be decrypted master-side. For more information, see the :ref:`Pillar Encryption <pillar-encryption>` documentation. Pillar data that is decrypted master-side, is not decrypted until the end of pillar compilation though, so minion-side decryption will be necessary if the encrypted pillar data must be made available in an decrypted state pillar/ext_pillar rendering. .. versionadded:: 2017.7.0 pillarenv Pass a specific pillar environment from which to compile pillar data. If not specified, then the minion's :conf_minion:`pillarenv` option is not used, and if that also is not specified then all configured pillar environments will be merged into a single pillar dictionary and returned. .. versionadded:: 2016.11.2 saltenv Included only for compatibility with :conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored. CLI Example: .. code-block:: bash salt '*' pillar.items """ # Preserve backwards compatibility if args: return item(*args) pillarenv = kwargs.get("pillarenv") if pillarenv is None: if __opts__.get("pillarenv_from_saltenv", False): pillarenv = kwargs.get("saltenv") or __opts__["saltenv"] else: pillarenv = __opts__["pillarenv"] pillar_override = kwargs.get("pillar") pillar_enc = kwargs.get("pillar_enc") if pillar_override and pillar_enc: try: pillar_override = salt.utils.crypt.decrypt( pillar_override, pillar_enc, translate_newlines=True, opts=__opts__, valid_rend=__opts__["decrypt_pillar_renderers"], ) except Exception as exc: # pylint: disable=broad-except raise CommandExecutionError( "Failed to decrypt pillar override: {}".format(exc) ) pillar = salt.pillar.get_pillar( __opts__, dict(__grains__), __opts__["id"], pillar_override=pillar_override, pillarenv=pillarenv, ) return pillar.compile_pillar() # Allow pillar.data to also be used to return pillar data data = salt.utils.functools.alias_function(items, "data") def _obfuscate_inner(var): """ Recursive obfuscation of collection types. Leaf or unknown Python types get replaced by the type name Known collection types trigger recursion. In the special case of mapping types, keys are not obfuscated """ if isinstance(var, (dict, salt.utils.odict.OrderedDict)): return var.__class__((key, _obfuscate_inner(val)) for key, val in var.items()) elif isinstance(var, (list, set, tuple)): return type(var)(_obfuscate_inner(v) for v in var) else: return "<{}>".format(var.__class__.__name__) def obfuscate(*args): """ .. versionadded:: 2015.8.0 Same as :py:func:`items`, but replace pillar values with a simple type indication. This is useful to avoid displaying sensitive information on console or flooding the console with long output, such as certificates. For many debug or control purposes, the stakes lie more in dispatching than in actual values. In case the value is itself a collection type, obfuscation occurs within the value. For mapping types, keys are not obfuscated. Here are some examples: * ``'secret password'`` becomes ``'<str>'`` * ``['secret', 1]`` becomes ``['<str>', '<int>']`` * ``{'login': 'somelogin', 'pwd': 'secret'}`` becomes ``{'login': '<str>', 'pwd': '<str>'}`` CLI Examples: .. code-block:: bash salt '*' pillar.obfuscate """ return _obfuscate_inner(items(*args)) # naming chosen for consistency with grains.ls, although it breaks the short # identifier rule. def ls(*args): """ .. versionadded:: 2015.8.0 Calls the master for a fresh pillar, generates the pillar data on the fly (same as :py:func:`items`), but only shows the available main keys. CLI Examples: .. code-block:: bash salt '*' pillar.ls """ return list(items(*args)) def item(*args, **kwargs): """ .. versionadded:: 0.16.2 Return one or more pillar entries from the :ref:`in-memory pillar data <pillar-in-memory>`. delimiter Delimiter used to traverse nested dictionaries. .. note:: This is different from :py:func:`pillar.get <salt.modules.pillar.get>` in that no default value can be specified. :py:func:`pillar.get <salt.modules.pillar.get>` should probably still be used in most cases to retrieve nested pillar values, as it is a bit more flexible. One reason to use this function instead of :py:func:`pillar.get <salt.modules.pillar.get>` however is when it is desirable to retrieve the values of more than one key, since :py:func:`pillar.get <salt.modules.pillar.get>` can only retrieve one key at a time. .. versionadded:: 2015.8.0 pillarenv If specified, this function will query the master to generate fresh pillar data on the fly, specifically from the requested pillar environment. Note that this can produce different pillar data than executing this function without an environment, as its normal behavior is just to return a value from minion's pillar data in memory (which can be sourced from more than one pillar environment). Using this argument will not affect the pillar data in memory. It will however be slightly slower and use more resources on the master due to the need for the master to generate and send the minion fresh pillar data. This tradeoff in performance however allows for the use case where pillar data is desired only from a single environment. .. versionadded:: 2017.7.6,2018.3.1 saltenv Included only for compatibility with :conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored. .. versionadded:: 2017.7.6,2018.3.1 CLI Examples: .. code-block:: bash salt '*' pillar.item foo salt '*' pillar.item foo:bar salt '*' pillar.item foo bar baz """ ret = {} default = kwargs.get("default", "") delimiter = kwargs.get("delimiter", DEFAULT_TARGET_DELIM) pillarenv = kwargs.get("pillarenv", None) saltenv = kwargs.get("saltenv", None) pillar_dict = ( __pillar__ if all(x is None for x in (saltenv, pillarenv)) else items(saltenv=saltenv, pillarenv=pillarenv) ) try: for arg in args: ret[arg] = salt.utils.data.traverse_dict_and_list( pillar_dict, arg, default, delimiter ) except KeyError: pass return ret def raw(key=None): """ Return the raw pillar data that is currently loaded into the minion. Contrast with :py:func:`items` which calls the master to fetch the most up-to-date Pillar. CLI Example: .. code-block:: bash salt '*' pillar.raw With the optional key argument, you can select a subtree of the pillar raw data.:: salt '*' pillar.raw key='roles' """ if key: ret = __pillar__.get(key, {}) else: ret = dict(__pillar__) return ret def ext(external, pillar=None): ''' .. versionchanged:: 2016.3.6,2016.11.3,2017.7.0 The supported ext_pillar types are now tunable using the :conf_master:`on_demand_ext_pillar` config option. Earlier releases used a hard-coded default. Generate the pillar and apply an explicit external pillar external A single ext_pillar to add to the ext_pillar configuration. This must be passed as a single section from the ext_pillar configuration (see CLI examples below). For more complicated ``ext_pillar`` configurations, it can be helpful to use the Python shell to load YAML configuration into a dictionary, and figure out .. code-block:: python >>> import salt.utils.yaml >>> ext_pillar = salt.utils.yaml.safe_load(""" ... ext_pillar: ... - git: ... - issue38440 https://github.com/terminalmage/git_pillar: ... - env: base ... """) >>> ext_pillar {'ext_pillar': [{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}]} >>> ext_pillar['ext_pillar'][0] {'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]} In the above example, the value to pass would be ``{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}``. Note that this would need to be quoted when passing on the CLI (as in the CLI examples below). pillar : None If specified, allows for a dictionary of pillar data to be made available to pillar and ext_pillar rendering. These pillar variables will also override any variables of the same name in pillar or ext_pillar. .. versionadded:: 2015.5.0 CLI Examples: .. code-block:: bash salt '*' pillar.ext '{libvirt: _}' salt '*' pillar.ext "{'git': ['master https://github.com/myuser/myrepo']}" salt '*' pillar.ext "{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}" ''' if isinstance(external, str): external = salt.utils.yaml.safe_load(external) pillar_obj = salt.pillar.get_pillar( __opts__, __grains__.value(), __opts__["id"], __opts__["saltenv"], ext=external, pillar_override=pillar, ) ret = pillar_obj.compile_pillar() return ret def keys(key, delimiter=DEFAULT_TARGET_DELIM): """ .. versionadded:: 2015.8.0 Attempt to retrieve a list of keys from the named value from the pillar. The value can also represent a value in a nested dict using a ":" delimiter for the dict, similar to how pillar.get works. delimiter Specify an alternate delimiter to use when traversing a nested dict CLI Example: .. code-block:: bash salt '*' pillar.keys web:sites """ ret = salt.utils.data.traverse_dict_and_list(__pillar__, key, KeyError, delimiter) if ret is KeyError: raise KeyError("Pillar key not found: {}".format(key)) if not isinstance(ret, dict): raise ValueError("Pillar value in key {} is not a dict".format(key)) return list(ret) def file_exists(path, saltenv=None): """ .. versionadded:: 2016.3.0 This is a master-only function. Calling from the minion is not supported. Use the given path and search relative to the pillar environments to see if a file exists at that path. If the ``saltenv`` argument is given, restrict search to that environment only. Will only work with ``pillar_roots``, not external pillars. Returns True if the file is found, and False otherwise. path The path to the file in question. Will be treated as a relative path saltenv Optional argument to restrict the search to a specific saltenv CLI Example: .. code-block:: bash salt '*' pillar.file_exists foo/bar.sls """ pillar_roots = __opts__.get("pillar_roots") if not pillar_roots: raise CommandExecutionError( "No pillar_roots found. Are you running this on the master?" ) if saltenv: if saltenv in pillar_roots: pillar_roots = {saltenv: pillar_roots[saltenv]} else: return False for env in pillar_roots: for pillar_dir in pillar_roots[env]: full_path = os.path.join(pillar_dir, path) if __salt__["file.file_exists"](full_path): return True return False # Provide a jinja function call compatible get aliased as fetch fetch = get def filter_by(lookup_dict, pillar, merge=None, default="default", base=None): """ .. versionadded:: 2017.7.0 Look up the given pillar in a given dictionary and return the result :param lookup_dict: A dictionary, keyed by a pillar, containing a value or values relevant to systems matching that pillar. For example, a key could be a pillar for a role and the value could the name of a package on that particular OS. The dictionary key can be a globbing pattern. The function will return the corresponding ``lookup_dict`` value where the pillar value matches the pattern. For example: .. code-block:: bash # this will render 'got some salt' if ``role`` begins with 'salt' salt '*' pillar.filter_by '{salt*: got some salt, default: salt is not here}' role :param pillar: The name of a pillar to match with the system's pillar. For example, the value of the "role" pillar could be used to pull values from the ``lookup_dict`` dictionary. The pillar value can be a list. The function will return the ``lookup_dict`` value for a first found item in the list matching one of the ``lookup_dict`` keys. :param merge: A dictionary to merge with the results of the pillar selection from ``lookup_dict``. This allows another dictionary to override the values in the ``lookup_dict``. :param default: default lookup_dict's key used if the pillar does not exist or if the pillar value has no match on lookup_dict. If unspecified the value is "default". :param base: A lookup_dict key to use for a base dictionary. The pillar-selected ``lookup_dict`` is merged over this and then finally the ``merge`` dictionary is merged. This allows common values for each case to be collected in the base and overridden by the pillar selection dictionary and the merge dictionary. Default is unset. CLI Example: .. code-block:: bash salt '*' pillar.filter_by '{web: Serve it up, db: I query, default: x_x}' role """ return salt.utils.data.filter_by( lookup_dict=lookup_dict, lookup=pillar, traverse=__pillar__, merge=merge, default=default, base=base, )
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/pillar.py
0.718496
0.285752
pillar.py
pypi
import logging import salt.utils.platform log = logging.getLogger(__name__) def __virtual__(): """ Only work on POSIX-like systems """ if salt.utils.platform.is_windows(): return ( False, "The locate execution module cannot be loaded: only available on " "non-Windows systems.", ) return True def version(): """ Returns the version of locate CLI Example: .. code-block:: bash salt '*' locate.version """ cmd = "locate -V" out = __salt__["cmd.run"](cmd).splitlines() return out def stats(): """ Returns statistics about the locate database CLI Example: .. code-block:: bash salt '*' locate.stats """ ret = {} cmd = "locate -S" out = __salt__["cmd.run"](cmd).splitlines() for line in out: comps = line.strip().split() if line.startswith("Database"): ret["database"] = comps[1].replace(":", "") continue ret[" ".join(comps[1:])] = comps[0] return ret def updatedb(): """ Updates the locate database CLI Example: .. code-block:: bash salt '*' locate.updatedb """ cmd = "updatedb" out = __salt__["cmd.run"](cmd).splitlines() return out def locate(pattern, database="", limit=0, **kwargs): """ Performs a file lookup. Valid options (and their defaults) are:: basename=False count=False existing=False follow=True ignore=False nofollow=False wholename=True regex=False database=<locate's default database> limit=<integer, not set by default> See the manpage for ``locate(1)`` for further explanation of these options. CLI Example: .. code-block:: bash salt '*' locate.locate """ options = "" toggles = { "basename": "b", "count": "c", "existing": "e", "follow": "L", "ignore": "i", "nofollow": "P", "wholename": "w", } for option in kwargs: if bool(kwargs[option]) is True and option in toggles: options += toggles[option] if options: options = "-{}".format(options) if database: options += " -d {}".format(database) if limit > 0: options += " -l {}".format(limit) if "regex" in kwargs and bool(kwargs["regex"]) is True: options += " --regex" cmd = "locate {} {}".format(options, pattern) out = __salt__["cmd.run"](cmd, python_shell=False).splitlines() return out
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/locate.py
0.629205
0.21162
locate.py
pypi
import logging import os import salt.utils.files import salt.utils.platform import salt.utils.stringutils from salt.exceptions import SaltInvocationError _LOG = logging.getLogger(__name__) _DEFAULT_CONF = "/etc/logrotate.conf" # Define a function alias in order not to shadow built-in's __func_alias__ = {"set_": "set"} def __virtual__(): """ Only work on POSIX-like systems """ if salt.utils.platform.is_windows(): return ( False, "The logrotate execution module cannot be loaded: only available " "on non-Windows systems.", ) return True def _convert_if_int(value): """ Convert to an int if necessary. :param str value: The value to check/convert. :return: The converted or passed value. :rtype: bool|int|str """ try: value = int(str(value)) except ValueError: pass return value def _parse_conf(conf_file=_DEFAULT_CONF): """ Parse a logrotate configuration file. Includes will also be parsed, and their configuration will be stored in the return dict, as if they were part of the main config file. A dict of which configs came from which includes will be stored in the 'include files' dict inside the return dict, for later reference by the user or module. """ ret = {} mode = "single" multi_names = [] multi = {} prev_comps = None with salt.utils.files.fopen(conf_file, "r") as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line).strip() if not line: continue if line.startswith("#"): continue comps = line.split() if "{" in line and "}" not in line: mode = "multi" if len(comps) == 1 and prev_comps: multi_names = prev_comps else: multi_names = comps multi_names.pop() continue if "}" in line: mode = "single" for multi_name in multi_names: ret[multi_name] = multi multi_names = [] multi = {} continue if mode == "single": key = ret else: key = multi if comps[0] == "include": if "include files" not in ret: ret["include files"] = {} for include in os.listdir(comps[1]): if include not in ret["include files"]: ret["include files"][include] = [] include_path = os.path.join(comps[1], include) include_conf = _parse_conf(include_path) for file_key in include_conf: ret[file_key] = include_conf[file_key] ret["include files"][include].append(file_key) prev_comps = comps if len(comps) > 2: key[comps[0]] = " ".join(comps[1:]) elif len(comps) > 1: key[comps[0]] = _convert_if_int(comps[1]) else: key[comps[0]] = True return ret def show_conf(conf_file=_DEFAULT_CONF): """ Show parsed configuration :param str conf_file: The logrotate configuration file. :return: The parsed configuration. :rtype: dict CLI Example: .. code-block:: bash salt '*' logrotate.show_conf """ return _parse_conf(conf_file) def get(key, value=None, conf_file=_DEFAULT_CONF): """ Get the value for a specific configuration line. :param str key: The command or stanza block to configure. :param str value: The command value or command of the block specified by the key parameter. :param str conf_file: The logrotate configuration file. :return: The value for a specific configuration line. :rtype: bool|int|str CLI Example: .. code-block:: bash salt '*' logrotate.get rotate salt '*' logrotate.get /var/log/wtmp rotate /etc/logrotate.conf """ current_conf = _parse_conf(conf_file) stanza = current_conf.get(key, False) if value: if stanza: return stanza.get(value, False) _LOG.warning("Block '%s' not present or empty.", key) return stanza def set_(key, value, setting=None, conf_file=_DEFAULT_CONF): """ Set a new value for a specific configuration line. :param str key: The command or block to configure. :param str value: The command value or command of the block specified by the key parameter. :param str setting: The command value for the command specified by the value parameter. :param str conf_file: The logrotate configuration file. :return: A boolean representing whether all changes succeeded. :rtype: bool CLI Example: .. code-block:: bash salt '*' logrotate.set rotate 2 Can also be used to set a single value inside a multiline configuration block. For instance, to change rotate in the following block: .. code-block:: text /var/log/wtmp { monthly create 0664 root root rotate 1 } Use the following command: .. code-block:: bash salt '*' logrotate.set /var/log/wtmp rotate 2 This module also has the ability to scan files inside an include directory, and make changes in the appropriate file. """ conf = _parse_conf(conf_file) for include in conf["include files"]: if key in conf["include files"][include]: conf_file = os.path.join(conf["include"], include) new_line = "" kwargs = { "flags": 8, "backup": False, "path": conf_file, "pattern": "^{}.*".format(key), "show_changes": False, } if setting is None: current_value = conf.get(key, False) if isinstance(current_value, dict): raise SaltInvocationError( "Error: {} includes a dict, and a specific setting inside the " "dict was not declared".format(key) ) if value == current_value: _LOG.debug("Command '%s' already has: %s", key, value) return True # This is the new config line that will be set if value is True: new_line = key elif value: new_line = "{} {}".format(key, value) kwargs.update({"prepend_if_not_found": True}) else: stanza = conf.get(key, dict()) if stanza and not isinstance(stanza, dict): error_msg = ( "Error: A setting for a dict was declared, but the " "configuration line given is not a dict" ) raise SaltInvocationError(error_msg) if setting == stanza.get(value, False): _LOG.debug("Command '%s' already has: %s", value, setting) return True # We're going to be rewriting an entire stanza if setting: stanza[value] = setting else: del stanza[value] new_line = _dict_to_stanza(key, stanza) kwargs.update( { "pattern": "^{0}.*?{{.*?}}".format(key), "flags": 24, "append_if_not_found": True, } ) kwargs.update({"repl": new_line}) _LOG.debug("Setting file '%s' line: %s", conf_file, new_line) return __salt__["file.replace"](**kwargs) def _dict_to_stanza(key, stanza): """ Convert a dict to a multi-line stanza """ ret = "" for skey in stanza: if stanza[skey] is True: stanza[skey] = "" ret += " {} {}\n".format(skey, stanza[skey]) return "{0} {{\n{1}}}".format(key, ret)
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/logrotate.py
0.592902
0.209126
logrotate.py
pypi
import salt.utils.platform __proxyenabled__ = ["cisconso"] __virtualname__ = "cisconso" def __virtual__(): if salt.utils.platform.is_proxy(): return __virtualname__ return ( False, "The cisconso execution module failed to load: " "only available on proxy minions.", ) def info(): """ Return system information for grains of the NSO proxy minion .. code-block:: bash salt '*' cisconso.info """ return _proxy_cmd("info") def get_data(datastore, path): """ Get the configuration of the device tree at the given path :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param path: The device path to set the value at, a list of element names in order, / separated :type path: ``list``, ``str`` OR ``tuple`` :return: The network configuration at that tree :rtype: ``dict`` .. code-block:: bash salt cisco-nso cisconso.get_data running 'devices/ex0' """ if isinstance(path, str): path = "/".split(path) return _proxy_cmd("get_data", datastore, path) def set_data_value(datastore, path, data): """ Set a data entry in a datastore :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param path: The device path to set the value at, a list of element names in order, / separated :type path: ``list``, ``str`` OR ``tuple`` :param data: The new value at the given path :type data: ``dict`` :rtype: ``bool`` :return: ``True`` if successful, otherwise error. .. code-block:: bash salt cisco-nso cisconso.set_data_value running 'devices/ex0/routes' 10.0.0.20/24 """ if isinstance(path, str): path = "/".split(path) return _proxy_cmd("set_data_value", datastore, path, data) def get_rollbacks(): """ Get a list of stored configuration rollbacks .. code-block:: bash salt cisco-nso cisconso.get_rollbacks """ return _proxy_cmd("get_rollbacks") def get_rollback(name): """ Get the backup of stored a configuration rollback :param name: Typically an ID of the backup :type name: ``str`` :rtype: ``str`` :return: the contents of the rollback snapshot .. code-block:: bash salt cisco-nso cisconso.get_rollback 52 """ return _proxy_cmd("get_rollback", name) def apply_rollback(datastore, name): """ Apply a system rollback :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param name: an ID of the rollback to restore :type name: ``str`` .. code-block:: bash salt cisco-nso cisconso.apply_rollback 52 """ return _proxy_cmd("apply_rollback", datastore, name) def _proxy_cmd(command, *args, **kwargs): """ run commands from __proxy__ :mod:`salt.proxy.cisconso<salt.proxy.cisconso>` command function from `salt.proxy.cisconso` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function """ proxy_prefix = __opts__["proxy"]["proxytype"] proxy_cmd = ".".join([proxy_prefix, command]) if proxy_cmd not in __proxy__: return False for k in kwargs: if k.startswith("__pub_"): kwargs.pop(k) return __proxy__[proxy_cmd](*args, **kwargs)
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/cisconso.py
0.734215
0.378459
cisconso.py
pypi
import logging import salt.utils.platform import salt.utils.win_functions import salt.utils.winapi try: import win32api import win32com.client import pywintypes HAS_DEPENDENCIES = True except ImportError: HAS_DEPENDENCIES = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = "group" def __virtual__(): """ Set the group module if the kernel is Windows """ if not salt.utils.platform.is_windows(): return False, "win_groupadd: only works on Windows systems" if not HAS_DEPENDENCIES: return False, "win_groupadd: missing dependencies" return __virtualname__ def _get_computer_object(): """ A helper function to get the object for the local machine Returns: object: Returns the computer object for the local machine """ with salt.utils.winapi.Com(): nt = win32com.client.Dispatch("AdsNameSpaces") return nt.GetObject("", "WinNT://.,computer") def _get_group_object(name): """ A helper function to get a specified group object Args: name (str): The name of the object Returns: object: The specified group object """ with salt.utils.winapi.Com(): nt = win32com.client.Dispatch("AdsNameSpaces") return nt.GetObject("", "WinNT://./" + name + ",group") def _get_all_groups(): """ A helper function that gets a list of group objects for all groups on the machine Returns: iter: A list of objects for all groups on the machine """ with salt.utils.winapi.Com(): nt = win32com.client.Dispatch("AdsNameSpaces") results = nt.GetObject("", "WinNT://.") results.Filter = ["group"] return results def _get_username(member): """ Resolve the username from the member object returned from a group query Returns: str: The username converted to domain\\username format """ return member.ADSPath.replace("WinNT://", "").replace("/", "\\") def add(name, **kwargs): """ Add the specified group Args: name (str): The name of the group to add Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' group.add foo """ if not info(name): comp_obj = _get_computer_object() try: new_group = comp_obj.Create("group", name) new_group.SetInfo() log.info("Successfully created group %s", name) except pywintypes.com_error as exc: log.error( "Failed to create group %s. %s", name, win32api.FormatMessage(exc.excepinfo[5]), ) return False else: log.warning("The group %s already exists.", name) return False return True def delete(name, **kwargs): """ Remove the named group Args: name (str): The name of the group to remove Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' group.delete foo """ if info(name): comp_obj = _get_computer_object() try: comp_obj.Delete("group", name) log.info("Successfully removed group %s", name) except pywintypes.com_error as exc: log.error( "Failed to remove group %s. %s", name, win32api.FormatMessage(exc.excepinfo[5]), ) return False else: log.warning("The group %s does not exists.", name) return False return True def info(name): """ Return information about a group Args: name (str): The name of the group for which to get information Returns: dict: A dictionary of information about the group CLI Example: .. code-block:: bash salt '*' group.info foo """ try: groupObj = _get_group_object(name) gr_name = groupObj.Name gr_mem = [_get_username(x) for x in groupObj.members()] except pywintypes.com_error as exc: log.debug( "Failed to access group %s. %s", name, win32api.FormatMessage(exc.excepinfo[5]), ) return False if not gr_name: return False return {"name": gr_name, "passwd": None, "gid": None, "members": gr_mem} def getent(refresh=False): """ Return info on all groups Args: refresh (bool): Refresh the info for all groups in ``__context__``. If False only the groups in ``__context__`` will be returned. If True the ``__context__`` will be refreshed with current data and returned. Default is False Returns: A list of groups and their information CLI Example: .. code-block:: bash salt '*' group.getent """ if "group.getent" in __context__ and not refresh: return __context__["group.getent"] ret = [] results = _get_all_groups() for result in results: group = { "gid": __salt__["file.group_to_gid"](result.Name), "members": [_get_username(x) for x in result.members()], "name": result.Name, "passwd": "x", } ret.append(group) __context__["group.getent"] = ret return ret def adduser(name, username, **kwargs): """ Add a user to a group Args: name (str): The name of the group to modify username (str): The name of the user to add to the group Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' group.adduser foo username """ try: group_obj = _get_group_object(name) except pywintypes.com_error as exc: log.error( "Failed to access group %s. %s", name, win32api.FormatMessage(exc.excepinfo[5]), ) return False existing_members = [_get_username(x) for x in group_obj.members()] username = salt.utils.win_functions.get_sam_name(username) try: if username not in existing_members: group_obj.Add("WinNT://" + username.replace("\\", "/")) log.info("Added user %s", username) else: log.warning("User %s is already a member of %s", username, name) return False except pywintypes.com_error as exc: log.error("Failed to add %s to group %s. %s", username, name, exc.excepinfo[2]) return False return True def deluser(name, username, **kwargs): """ Remove a user from a group Args: name (str): The name of the group to modify username (str): The name of the user to remove from the group Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' group.deluser foo username """ try: group_obj = _get_group_object(name) except pywintypes.com_error as exc: log.error( "Failed to access group %s. %s", name, win32api.FormatMessage(exc.excepinfo[5]), ) return False existing_members = [_get_username(x) for x in group_obj.members()] try: if salt.utils.win_functions.get_sam_name(username) in existing_members: group_obj.Remove("WinNT://" + username.replace("\\", "/")) log.info("Removed user %s", username) else: log.warning("User %s is not a member of %s", username, name) return False except pywintypes.com_error as exc: log.error( "Failed to remove %s from group %s. %s", username, name, win32api.FormatMessage(exc.excepinfo[5]), ) return False return True def members(name, members_list, **kwargs): """ Ensure a group contains only the members in the list Args: name (str): The name of the group to modify members_list (str): A single user or a comma separated list of users. The group will contain only the users specified in this list. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' group.members foo 'user1,user2,user3' """ members_list = [ salt.utils.win_functions.get_sam_name(m) for m in members_list.split(",") ] if not isinstance(members_list, list): log.debug("member_list is not a list") return False try: obj_group = _get_group_object(name) except pywintypes.com_error as exc: # Group probably doesn't exist, but we'll log the error log.error( "Failed to access group %s. %s", name, win32api.FormatMessage(exc.excepinfo[5]), ) return False existing_members = [_get_username(x) for x in obj_group.members()] existing_members.sort() members_list.sort() if existing_members == members_list: log.info("%s membership is correct", name) return True # add users success = True for member in members_list: if member not in existing_members: try: obj_group.Add("WinNT://" + member.replace("\\", "/")) log.info("User added: %s", member) except pywintypes.com_error as exc: log.error( "Failed to add %s to %s. %s", member, name, win32api.FormatMessage(exc.excepinfo[5]), ) success = False # remove users not in members_list for member in existing_members: if member not in members_list: try: obj_group.Remove("WinNT://" + member.replace("\\", "/")) log.info("User removed: %s", member) except pywintypes.com_error as exc: log.error( "Failed to remove %s from %s. %s", member, name, win32api.FormatMessage(exc.excepinfo[5]), ) success = False return success def list_groups(refresh=False): """ Return a list of groups Args: refresh (bool): Refresh the info for all groups in ``__context__``. If False only the groups in ``__context__`` will be returned. If True, the ``__context__`` will be refreshed with current data and returned. Default is False Returns: list: A list of groups on the machine CLI Example: .. code-block:: bash salt '*' group.list_groups """ if "group.list_groups" in __context__ and not refresh: return __context__["group.list_groups"] results = _get_all_groups() ret = [] for result in results: ret.append(result.Name) __context__["group.list_groups"] = ret return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/win_groupadd.py
0.678753
0.159708
win_groupadd.py
pypi
import fnmatch import os import re __func_alias__ = {"reload_": "reload"} _GRAINMAP = {"Arch": "/etc/rc.d", "Arch ARM": "/etc/rc.d"} def __virtual__(): """ Only work on systems which exclusively use sysvinit """ # Disable on these platforms, specific service modules exist: disable = { "RedHat", "CentOS", "Amazon", "ScientificLinux", "CloudLinux", "Fedora", "Gentoo", "Ubuntu", "Debian", "Devuan", "ALT", "OEL", "Linaro", "elementary OS", "McAfee OS Server", "Raspbian", "SUSE", "Slackware", } if __grains__.get("os") in disable: return (False, "Your OS is on the disabled list") # Disable on all non-Linux OSes as well if __grains__["kernel"] != "Linux": return (False, "Non Linux OSes are not supported") init_grain = __grains__.get("init") if init_grain not in (None, "sysvinit", "unknown"): return (False, "Minion is running {}".format(init_grain)) elif __utils__["systemd.booted"](__context__): # Should have been caught by init grain check, but check just in case return (False, "Minion is running systemd") return "service" def run(name, action): """ Run the specified service with an action. .. versionadded:: 2015.8.1 name Service name. action Action name (like start, stop, reload, restart). CLI Example: .. code-block:: bash salt '*' service.run apache2 reload salt '*' service.run postgresql initdb """ cmd = ( os.path.join(_GRAINMAP.get(__grains__.get("os"), "/etc/init.d"), name) + " " + action ) return not __salt__["cmd.retcode"](cmd, python_shell=False) def start(name): """ Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> """ return run(name, "start") def stop(name): """ Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> """ return run(name, "stop") def restart(name): """ Restart the specified service CLI Example: .. code-block:: bash salt '*' service.restart <service name> """ return run(name, "restart") def status(name, sig=None): """ Return the status for a service. If the name contains globbing, a dict mapping service name to PID or empty string is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Signature to use to find the service via ps Returns: string: PID if running, empty otherwise dict: Maps service name to PID if running, empty string otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature] """ if sig: return __salt__["status.pid"](sig) contains_globbing = bool(re.search(r"\*|\?|\[.+\]", name)) if contains_globbing: services = fnmatch.filter(get_all(), name) else: services = [name] results = {} for service in services: results[service] = __salt__["status.pid"](service) if contains_globbing: return results return results[name] def reload_(name): """ Refreshes config files by calling service reload. Does not perform a full restart. CLI Example: .. code-block:: bash salt '*' service.reload <service name> """ return run(name, "reload") def available(name): """ Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd """ return name in get_all() def missing(name): """ The inverse of service.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd """ return name not in get_all() def get_all(): """ Return a list of all available services CLI Example: .. code-block:: bash salt '*' service.get_all """ if not os.path.isdir(_GRAINMAP.get(__grains__.get("os"), "/etc/init.d")): return [] return sorted(os.listdir(_GRAINMAP.get(__grains__.get("os"), "/etc/init.d")))
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/linux_service.py
0.546496
0.164416
linux_service.py
pypi
import logging import salt.utils.args import salt.utils.mac_utils from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) __virtualname__ = "xattr" __func_alias__ = { "list_": "list", } def __virtual__(): """ Only work on Mac OS """ if __grains__["os"] in ["MacOS", "Darwin"]: return __virtualname__ return (False, "Only available on Mac OS systems") def list_(path, **kwargs): """ List all of the extended attributes on the given file/directory :param str path: The file(s) to get attributes from :param bool hex: Return the values with forced hexadecimal values :return: A dictionary containing extended attributes and values for the given file :rtype: dict :raises: CommandExecutionError on file not found or any other unknown error CLI Example: .. code-block:: bash salt '*' xattr.list /path/to/file salt '*' xattr.list /path/to/file hex=True """ kwargs = salt.utils.args.clean_kwargs(**kwargs) hex_ = kwargs.pop("hex", False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) cmd = ["xattr", path] try: ret = salt.utils.mac_utils.execute_return_result(cmd) except CommandExecutionError as exc: if "No such file" in exc.strerror: raise CommandExecutionError("File not found: {}".format(path)) raise CommandExecutionError("Unknown Error: {}".format(exc.strerror)) if not ret: return {} attrs_ids = ret.split("\n") attrs = {} for id_ in attrs_ids: attrs[id_] = read(path, id_, **{"hex": hex_}) return attrs def read(path, attribute, **kwargs): """ Read the given attributes on the given file/directory :param str path: The file to get attributes from :param str attribute: The attribute to read :param bool hex: Return the values with forced hexadecimal values :return: A string containing the value of the named attribute :rtype: str :raises: CommandExecutionError on file not found, attribute not found, and any other unknown error CLI Example: .. code-block:: bash salt '*' xattr.read /path/to/file com.test.attr salt '*' xattr.read /path/to/file com.test.attr hex=True """ kwargs = salt.utils.args.clean_kwargs(**kwargs) hex_ = kwargs.pop("hex", False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) cmd = ["xattr", "-p"] if hex_: cmd.append("-x") cmd.extend([attribute, path]) try: ret = salt.utils.mac_utils.execute_return_result(cmd) except CommandExecutionError as exc: if "No such file" in exc.strerror: raise CommandExecutionError("File not found: {}".format(path)) if "No such xattr" in exc.strerror: raise CommandExecutionError("Attribute not found: {}".format(attribute)) raise CommandExecutionError("Unknown Error: {}".format(exc.strerror)) return ret def write(path, attribute, value, **kwargs): """ Causes the given attribute name to be assigned the given value :param str path: The file(s) to get attributes from :param str attribute: The attribute name to be written to the file/directory :param str value: The value to assign to the given attribute :param bool hex: Set the values with forced hexadecimal values :return: True if successful, otherwise False :rtype: bool :raises: CommandExecutionError on file not found or any other unknown error CLI Example: .. code-block:: bash salt '*' xattr.write /path/to/file "com.test.attr" "value" """ kwargs = salt.utils.args.clean_kwargs(**kwargs) hex_ = kwargs.pop("hex", False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) cmd = ["xattr", "-w"] if hex_: cmd.append("-x") cmd.extend([attribute, value, path]) try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: if "No such file" in exc.strerror: raise CommandExecutionError("File not found: {}".format(path)) raise CommandExecutionError("Unknown Error: {}".format(exc.strerror)) return read(path, attribute, **{"hex": hex_}) == value def delete(path, attribute): """ Removes the given attribute from the file :param str path: The file(s) to get attributes from :param str attribute: The attribute name to be deleted from the file/directory :return: True if successful, otherwise False :rtype: bool :raises: CommandExecutionError on file not found, attribute not found, and any other unknown error CLI Example: .. code-block:: bash salt '*' xattr.delete /path/to/file "com.test.attr" """ cmd = 'xattr -d "{}" "{}"'.format(attribute, path) try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: if "No such file" in exc.strerror: raise CommandExecutionError("File not found: {}".format(path)) if "No such xattr" in exc.strerror: raise CommandExecutionError("Attribute not found: {}".format(attribute)) raise CommandExecutionError("Unknown Error: {}".format(exc.strerror)) return attribute not in list_(path) def clear(path): """ Causes the all attributes on the file/directory to be removed :param str path: The file(s) to get attributes from :return: True if successful, otherwise False :raises: CommandExecutionError on file not found or any other unknown error CLI Example: .. code-block:: bash salt '*' xattr.delete /path/to/file "com.test.attr" """ cmd = 'xattr -c "{}"'.format(path) try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: if "No such file" in exc.strerror: raise CommandExecutionError("File not found: {}".format(path)) raise CommandExecutionError("Unknown Error: {}".format(exc.strerror)) return list_(path) == {}
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/mac_xattr.py
0.708515
0.187411
mac_xattr.py
pypi
import logging import xml.etree.ElementTree as ET import salt.utils.http import salt.utils.yaml log = logging.getLogger(__name__) def __virtual__(): """ Only load the module if apache is installed """ if _apikey(): return True return ( False, 'The API key was not specified. Please specify it using the "apikey" config.', ) def _apikey(): """ Get the API key """ return __opts__.get("bamboohr", {}).get("apikey", None) def list_employees(order_by="id"): """ Show all employees for this company. CLI Example: .. code-block:: bash salt myminion bamboohr.list_employees By default, the return data will be keyed by ID. However, it can be ordered by any other field. Keep in mind that if the field that is chosen contains duplicate values (i.e., location is used, for a company which only has one location), then each duplicate value will be overwritten by the previous. Therefore, it is advisable to only sort by fields that are guaranteed to be unique. CLI Examples: .. code-block:: bash salt myminion bamboohr.list_employees order_by=id salt myminion bamboohr.list_employees order_by=displayName salt myminion bamboohr.list_employees order_by=workEmail """ ret = {} status, result = _query(action="employees", command="directory") root = ET.fromstring(result) for cat in root: if cat.tag != "employees": continue for item in cat: emp_id = next(iter(item.values())) emp_ret = {"id": emp_id} for details in item: emp_ret[next(iter(details.values()))] = details.text ret[emp_ret[order_by]] = emp_ret return ret def show_employee(emp_id, fields=None): """ Show all employees for this company. CLI Example: .. code-block:: bash salt myminion bamboohr.show_employee 1138 By default, the fields normally returned from bamboohr.list_employees are returned. These fields are: - canUploadPhoto - department - displayName - firstName - id - jobTitle - lastName - location - mobilePhone - nickname - photoUploaded - photoUrl - workEmail - workPhone - workPhoneExtension If needed, a different set of fields may be specified, separated by commas: CLI Example: .. code-block:: bash salt myminion bamboohr.show_employee 1138 displayName,dateOfBirth A list of available fields can be found at http://www.bamboohr.com/api/documentation/employees.php """ ret = {} if fields is None: fields = ",".join( ( "canUploadPhoto", "department", "displayName", "firstName", "id", "jobTitle", "lastName", "location", "mobilePhone", "nickname", "photoUploaded", "photoUrl", "workEmail", "workPhone", "workPhoneExtension", ) ) status, result = _query(action="employees", command=emp_id, args={"fields": fields}) root = ET.fromstring(result) ret = {"id": emp_id} for item in root: ret[next(iter(item.values()))] = item.text return ret def update_employee(emp_id, key=None, value=None, items=None): """ Update one or more items for this employee. Specifying an empty value will clear it for that employee. CLI Examples: .. code-block:: bash salt myminion bamboohr.update_employee 1138 nickname Curly salt myminion bamboohr.update_employee 1138 nickname '' salt myminion bamboohr.update_employee 1138 items='{"nickname": "Curly"} salt myminion bamboohr.update_employee 1138 items='{"nickname": ""} """ if items is None: if key is None or value is None: return {"Error": "At least one key/value pair is required"} items = {key: value} elif isinstance(items, str): items = salt.utils.yaml.safe_load(items) xml_items = "" for pair in items: xml_items += '<field id="{}">{}</field>'.format(pair, items[pair]) xml_items = "<employee>{}</employee>".format(xml_items) status, result = _query( action="employees", command=emp_id, data=xml_items, method="POST", ) return show_employee(emp_id, ",".join(items.keys())) def list_users(order_by="id"): """ Show all users for this company. CLI Example: .. code-block:: bash salt myminion bamboohr.list_users By default, the return data will be keyed by ID. However, it can be ordered by any other field. Keep in mind that if the field that is chosen contains duplicate values (i.e., location is used, for a company which only has one location), then each duplicate value will be overwritten by the previous. Therefore, it is advisable to only sort by fields that are guaranteed to be unique. CLI Examples: .. code-block:: bash salt myminion bamboohr.list_users order_by=id salt myminion bamboohr.list_users order_by=email """ ret = {} status, result = _query(action="meta", command="users") root = ET.fromstring(result) for user in root: user_id = None user_ret = {} for item in user.items(): user_ret[item[0]] = item[1] if item[0] == "id": user_id = item[1] for item in user: user_ret[item.tag] = item.text ret[user_ret[order_by]] = user_ret return ret def list_meta_fields(): """ Show all meta data fields for this company. CLI Example: .. code-block:: bash salt myminion bamboohr.list_meta_fields """ ret = {} status, result = _query(action="meta", command="fields") root = ET.fromstring(result) for field in root: field_id = None field_ret = {"name": field.text} for item in field.items(): field_ret[item[0]] = item[1] if item[0] == "id": field_id = item[1] ret[field_id] = field_ret return ret def _query(action=None, command=None, args=None, method="GET", data=None): """ Make a web call to BambooHR The password can be any random text, so we chose Salty text. """ subdomain = __opts__.get("bamboohr", {}).get("subdomain", None) path = "https://api.bamboohr.com/api/gateway.php/{}/v1/".format(subdomain) if action: path += action if command: path += "/{}".format(command) log.debug("BambooHR URL: %s", path) if not isinstance(args, dict): args = {} return_content = None result = salt.utils.http.query( path, method, username=_apikey(), password="saltypork", params=args, data=data, decode=False, text=True, status=True, opts=__opts__, ) log.debug("BambooHR Response Status Code: %s", result["status"]) return [result["status"], result["text"]]
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/bamboohr.py
0.52342
0.19112
bamboohr.py
pypi
import logging import os.path import salt.utils.path # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = "lvm" def __virtual__(): """ Only load the module if lvm is installed """ if salt.utils.path.which("lvm"): return __virtualname__ return ( False, "The linux_lvm execution module cannot be loaded: the lvm binary is not in the" " path.", ) def version(): """ Return LVM version from lvm version CLI Example: .. code-block:: bash salt '*' lvm.version """ cmd = "lvm version" out = __salt__["cmd.run"](cmd).splitlines() ret = out[0].split(": ") return ret[1].strip() def fullversion(): """ Return all version info from lvm version CLI Example: .. code-block:: bash salt '*' lvm.fullversion """ ret = {} cmd = "lvm version" out = __salt__["cmd.run"](cmd).splitlines() for line in out: comps = line.split(":") ret[comps[0].strip()] = comps[1].strip() return ret def pvdisplay(pvname="", real=False, quiet=False): """ Return information about the physical volume(s) pvname physical device name real dereference any symlinks and report the real device .. versionadded:: 2015.8.7 quiet if the physical volume is not present, do not show any error CLI Examples: .. code-block:: bash salt '*' lvm.pvdisplay salt '*' lvm.pvdisplay /dev/md0 """ ret = {} cmd = ["pvdisplay", "-c"] if pvname: cmd.append(pvname) cmd_ret = __salt__["cmd.run_all"](cmd, python_shell=False, ignore_retcode=quiet) if cmd_ret["retcode"] != 0: return {} out = cmd_ret["stdout"].splitlines() for line in out: if "is a new physical volume" not in line: comps = line.strip().split(":") if real: device = os.path.realpath(comps[0]) else: device = comps[0] ret[device] = { "Physical Volume Device": comps[0], "Volume Group Name": comps[1], "Physical Volume Size (kB)": comps[2], "Internal Physical Volume Number": comps[3], "Physical Volume Status": comps[4], "Physical Volume (not) Allocatable": comps[5], "Current Logical Volumes Here": comps[6], "Physical Extent Size (kB)": comps[7], "Total Physical Extents": comps[8], "Free Physical Extents": comps[9], "Allocated Physical Extents": comps[10], } if real: ret[device]["Real Physical Volume Device"] = device return ret def vgdisplay(vgname="", quiet=False): """ Return information about the volume group(s) vgname volume group name quiet if the volume group is not present, do not show any error CLI Examples: .. code-block:: bash salt '*' lvm.vgdisplay salt '*' lvm.vgdisplay nova-volumes """ ret = {} cmd = ["vgdisplay", "-c"] if vgname: cmd.append(vgname) cmd_ret = __salt__["cmd.run_all"](cmd, python_shell=False, ignore_retcode=quiet) if cmd_ret["retcode"] != 0: return {} out = cmd_ret["stdout"].splitlines() for line in out: comps = line.strip().split(":") ret[comps[0]] = { "Volume Group Name": comps[0], "Volume Group Access": comps[1], "Volume Group Status": comps[2], "Internal Volume Group Number": comps[3], "Maximum Logical Volumes": comps[4], "Current Logical Volumes": comps[5], "Open Logical Volumes": comps[6], "Maximum Logical Volume Size": comps[7], "Maximum Physical Volumes": comps[8], "Current Physical Volumes": comps[9], "Actual Physical Volumes": comps[10], "Volume Group Size (kB)": comps[11], "Physical Extent Size (kB)": comps[12], "Total Physical Extents": comps[13], "Allocated Physical Extents": comps[14], "Free Physical Extents": comps[15], "UUID": comps[16], } return ret def lvdisplay(lvname="", quiet=False): """ Return information about the logical volume(s) lvname logical device name quiet if the logical volume is not present, do not show any error CLI Examples: .. code-block:: bash salt '*' lvm.lvdisplay salt '*' lvm.lvdisplay /dev/vg_myserver/root """ ret = {} cmd = ["lvdisplay", "-c"] if lvname: cmd.append(lvname) cmd_ret = __salt__["cmd.run_all"](cmd, python_shell=False, ignore_retcode=quiet) if cmd_ret["retcode"] != 0: return {} out = cmd_ret["stdout"].splitlines() for line in out: comps = line.strip().split(":") ret[comps[0]] = { "Logical Volume Name": comps[0], "Volume Group Name": comps[1], "Logical Volume Access": comps[2], "Logical Volume Status": comps[3], "Internal Logical Volume Number": comps[4], "Open Logical Volumes": comps[5], "Logical Volume Size": comps[6], "Current Logical Extents Associated": comps[7], "Allocated Logical Extents": comps[8], "Allocation Policy": comps[9], "Read Ahead Sectors": comps[10], "Major Device Number": comps[11], "Minor Device Number": comps[12], } return ret def pvcreate(devices, override=True, force=True, **kwargs): """ Set a physical device to be used as an LVM physical volume override Skip devices, if they are already LVM physical volumes CLI Examples: .. code-block:: bash salt mymachine lvm.pvcreate /dev/sdb1,/dev/sdb2 salt mymachine lvm.pvcreate /dev/sdb1 dataalignmentoffset=7s """ if not devices: return "Error: at least one device is required" if isinstance(devices, str): devices = devices.split(",") cmd = ["pvcreate"] if force: cmd.append("--yes") else: cmd.append("-qq") for device in devices: if not os.path.exists(device): return "{} does not exist".format(device) if not pvdisplay(device, quiet=True): cmd.append(device) elif not override: return 'Device "{}" is already an LVM physical volume.'.format(device) if not cmd[2:]: # All specified devices are already LVM volumes return True valid = ( "metadatasize", "dataalignment", "dataalignmentoffset", "pvmetadatacopies", "metadatacopies", "metadataignore", "restorefile", "norestorefile", "labelsector", "setphysicalvolumesize", ) no_parameter = "norestorefile" for var in kwargs: if kwargs[var] and var in valid: cmd.extend(["--{}".format(var), kwargs[var]]) elif kwargs[var] and var in no_parameter: cmd.append("--{}".format(var)) out = __salt__["cmd.run_all"](cmd, python_shell=False) if out.get("retcode"): return out.get("stderr") # Verify pvcreate was successful for device in devices: if not pvdisplay(device): return 'Device "{}" was not affected.'.format(device) return True def pvremove(devices, override=True, force=True): """ Remove a physical device being used as an LVM physical volume override Skip devices, if they are already not used as LVM physical volumes CLI Examples: .. code-block:: bash salt mymachine lvm.pvremove /dev/sdb1,/dev/sdb2 """ if isinstance(devices, str): devices = devices.split(",") cmd = ["pvremove"] if force: cmd.append("--yes") else: cmd.append("-qq") for device in devices: if pvdisplay(device): cmd.append(device) elif not override: return "{} is not a physical volume".format(device) if not cmd[2:]: # Nothing to do return True out = __salt__["cmd.run_all"](cmd, python_shell=False) if out.get("retcode"): return out.get("stderr") # Verify pvremove was successful for device in devices: if pvdisplay(device, quiet=True): return 'Device "{}" was not affected.'.format(device) return True def vgcreate(vgname, devices, force=False, **kwargs): """ Create an LVM volume group CLI Examples: .. code-block:: bash salt mymachine lvm.vgcreate my_vg /dev/sdb1,/dev/sdb2 salt mymachine lvm.vgcreate my_vg /dev/sdb1 clustered=y """ if not vgname or not devices: return "Error: vgname and device(s) are both required" if isinstance(devices, str): devices = devices.split(",") cmd = ["vgcreate", vgname] for device in devices: cmd.append(device) if force: cmd.append("--yes") else: cmd.append("-qq") valid = ( "addtag", "alloc", "autobackup", "clustered", "maxlogicalvolumes", "maxphysicalvolumes", "metadatatype", "vgmetadatacopies", "metadatacopies", "physicalextentsize", "zero", ) for var in kwargs: if kwargs[var] and var in valid: cmd.append("--{}".format(var)) cmd.append(kwargs[var]) cmd_ret = __salt__["cmd.run_all"](cmd, python_shell=False) if cmd_ret.get("retcode"): out = cmd_ret.get("stderr").strip() else: out = 'Volume group "{}" successfully created'.format(vgname) vgdata = vgdisplay(vgname) vgdata["Output from vgcreate"] = out return vgdata def vgextend(vgname, devices, force=False): """ Add physical volumes to an LVM volume group CLI Examples: .. code-block:: bash salt mymachine lvm.vgextend my_vg /dev/sdb1,/dev/sdb2 salt mymachine lvm.vgextend my_vg /dev/sdb1 """ if not vgname or not devices: return "Error: vgname and device(s) are both required" if isinstance(devices, str): devices = devices.split(",") cmd = ["vgextend", vgname] if force: cmd.append("--yes") else: cmd.append("-qq") for device in devices: cmd.append(device) cmd_ret = __salt__["cmd.run_all"](cmd, python_shell=False) if cmd_ret.get("retcode"): out = cmd_ret.get("stderr").strip() else: out = 'Volume group "{}" successfully extended'.format(vgname) vgdata = {"Output from vgextend": out} return vgdata def lvcreate( lvname, vgname, size=None, extents=None, snapshot=None, pv=None, thinvolume=False, thinpool=False, force=False, **kwargs ): """ Create a new logical volume, with option for which physical volume to be used CLI Examples: .. code-block:: bash salt '*' lvm.lvcreate new_volume_name vg_name size=10G salt '*' lvm.lvcreate new_volume_name vg_name extents=100 pv=/dev/sdb salt '*' lvm.lvcreate new_snapshot vg_name snapshot=volume_name size=3G .. versionadded:: 0.12.0 Support for thin pools and thin volumes CLI Examples: .. code-block:: bash salt '*' lvm.lvcreate new_thinpool_name vg_name size=20G thinpool=True salt '*' lvm.lvcreate new_thinvolume_name vg_name/thinpool_name size=10G thinvolume=True """ if size and extents: return "Error: Please specify only one of size or extents" if thinvolume and thinpool: return "Error: Please set only one of thinvolume or thinpool to True" valid = ( "activate", "chunksize", "contiguous", "discards", "stripes", "stripesize", "minor", "persistent", "mirrors", "nosync", "noudevsync", "monitor", "ignoremonitoring", "permission", "poolmetadatasize", "readahead", "regionsize", "type", "virtualsize", "zero", ) no_parameter = ( "nosync", "noudevsync", "ignoremonitoring", "thin", ) extra_arguments = [] if kwargs: for k, v in kwargs.items(): if k in no_parameter: extra_arguments.append("--{}".format(k)) elif k in valid: extra_arguments.extend(["--{}".format(k), "{}".format(v)]) cmd = [salt.utils.path.which("lvcreate")] if thinvolume: cmd.extend(["--thin", "-n", lvname]) elif thinpool: cmd.extend(["--thinpool", lvname]) else: cmd.extend(["-n", lvname]) if snapshot: cmd.extend(["-s", "{}/{}".format(vgname, snapshot)]) else: cmd.append(vgname) if size and thinvolume: cmd.extend(["-V", "{}".format(size)]) elif extents and thinvolume: return "Error: Thin volume size cannot be specified as extents" elif size: cmd.extend(["-L", "{}".format(size)]) elif extents: cmd.extend(["-l", "{}".format(extents)]) else: return "Error: Either size or extents must be specified" if pv: cmd.append(pv) if extra_arguments: cmd.extend(extra_arguments) if force: cmd.append("--yes") else: cmd.append("-qq") cmd_ret = __salt__["cmd.run_all"](cmd, python_shell=False) if cmd_ret.get("retcode"): out = cmd_ret.get("stderr").strip() else: out = 'Logical volume "{}" created.'.format(lvname) lvdev = "/dev/{}/{}".format(vgname, lvname) lvdata = lvdisplay(lvdev) lvdata["Output from lvcreate"] = out return lvdata def vgremove(vgname, force=True): """ Remove an LVM volume group CLI Examples: .. code-block:: bash salt mymachine lvm.vgremove vgname salt mymachine lvm.vgremove vgname force=True """ cmd = ["vgremove", vgname] if force: cmd.append("--yes") else: cmd.append("-qq") cmd_ret = __salt__["cmd.run_all"](cmd, python_shell=False) if cmd_ret.get("retcode"): out = cmd_ret.get("stderr").strip() else: out = 'Volume group "{}" successfully removed'.format(vgname) return out def lvremove(lvname, vgname, force=True): """ Remove a given existing logical volume from a named existing volume group CLI Example: .. code-block:: bash salt '*' lvm.lvremove lvname vgname force=True """ cmd = ["lvremove", "{}/{}".format(vgname, lvname)] if force: cmd.append("--yes") else: cmd.append("-qq") cmd_ret = __salt__["cmd.run_all"](cmd, python_shell=False) if cmd_ret.get("retcode"): out = cmd_ret.get("stderr").strip() else: out = 'Logical volume "{}" successfully removed'.format(lvname) return out def lvresize(size=None, lvpath=None, extents=None, force=False, resizefs=False): """ Resize a logical volume to specific size. CLI Examples: .. code-block:: bash salt '*' lvm.lvresize +12M /dev/mapper/vg1-test salt '*' lvm.lvresize lvpath=/dev/mapper/vg1-test extents=+100%FREE """ if size and extents: log.error("Error: Please specify only one of size or extents") return {} cmd = ["lvresize"] if force: cmd.append("--force") else: cmd.append("-qq") if resizefs: cmd.append("--resizefs") if size: cmd.extend(["-L", "{}".format(size)]) elif extents: cmd.extend(["-l", "{}".format(extents)]) else: log.error("Error: Either size or extents must be specified") return {} cmd.append(lvpath) cmd_ret = __salt__["cmd.run_all"](cmd, python_shell=False) if cmd_ret.get("retcode"): out = cmd_ret.get("stderr").strip() else: out = 'Logical volume "{}" successfully resized.'.format(lvpath) return {"Output from lvresize": out} def lvextend(size=None, lvpath=None, extents=None, force=False, resizefs=False): """ Increase a logical volume to specific size. CLI Examples: .. code-block:: bash salt '*' lvm.lvextend +12M /dev/mapper/vg1-test salt '*' lvm.lvextend lvpath=/dev/mapper/vg1-test extents=+100%FREE """ if size and extents: log.error("Error: Please specify only one of size or extents") return {} cmd = ["lvextend"] if force: cmd.append("--yes") else: cmd.append("-qq") if resizefs: cmd.append("--resizefs") if size: cmd.extend(["-L", "{}".format(size)]) elif extents: cmd.extend(["-l", "{}".format(extents)]) else: log.error("Error: Either size or extents must be specified") return {} cmd.append(lvpath) cmd_ret = __salt__["cmd.run_all"](cmd, python_shell=False) if cmd_ret.get("retcode"): out = cmd_ret.get("stderr").strip() else: out = 'Logical volume "{}" successfully extended.'.format(lvpath) return {"Output from lvextend": out} def pvresize(devices, override=True, force=True): """ Resize a LVM physical volume to the physical device size override Skip devices, if they are already not used as LVM physical volumes CLI Examples: .. code-block:: bash salt mymachine lvm.pvresize /dev/sdb1,/dev/sdb2 """ if isinstance(devices, str): devices = devices.split(",") cmd = ["pvresize"] if force: cmd.append("--yes") else: cmd.append("-qq") for device in devices: if pvdisplay(device): cmd.append(device) elif not override: return "{} is not a physical volume".format(device) if not cmd[2:]: # Nothing to do return True out = __salt__["cmd.run_all"](cmd, python_shell=False) if out.get("retcode"): return out.get("stderr") return True
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/linux_lvm.py
0.618089
0.213152
linux_lvm.py
pypi
import os import re import salt.utils.files # Define the module's virtual name __virtualname__ = "kmod" _LOAD_MODULE = '{0}_load="YES"' _LOADER_CONF = "/boot/loader.conf" _MODULE_RE = '^{0}_load="YES"' _MODULES_RE = r'^(\w+)_load="YES"' def __virtual__(): """ Only runs on FreeBSD systems """ if __grains__["kernel"] == "FreeBSD": return __virtualname__ return ( False, "The freebsdkmod execution module cannot be loaded: only available on FreeBSD" " systems.", ) def _new_mods(pre_mods, post_mods): """ Return a list of the new modules, pass an kldstat dict before running modprobe and one after modprobe has run """ pre = set() post = set() for mod in pre_mods: pre.add(mod["module"]) for mod in post_mods: post.add(mod["module"]) return post - pre def _rm_mods(pre_mods, post_mods): """ Return a list of the new modules, pass an kldstat dict before running modprobe and one after modprobe has run """ pre = set() post = set() for mod in pre_mods: pre.add(mod["module"]) for mod in post_mods: post.add(mod["module"]) return pre - post def _get_module_name(line): match = re.search(_MODULES_RE, line) if match: return match.group(1) return None def _get_persistent_modules(): """ Returns a list of modules in loader.conf that load on boot. """ mods = set() with salt.utils.files.fopen(_LOADER_CONF, "r") as loader_conf: for line in loader_conf: line = salt.utils.stringutils.to_unicode(line) line = line.strip() mod_name = _get_module_name(line) if mod_name: mods.add(mod_name) return mods def _set_persistent_module(mod): """ Add a module to loader.conf to make it persistent. """ if not mod or mod in mod_list(True) or mod not in available(): return set() __salt__["file.append"](_LOADER_CONF, _LOAD_MODULE.format(mod)) return {mod} def _remove_persistent_module(mod, comment): """ Remove module from loader.conf. If comment is true only comment line where module is. """ if not mod or mod not in mod_list(True): return set() if comment: __salt__["file.comment"](_LOADER_CONF, _MODULE_RE.format(mod)) else: __salt__["file.sed"](_LOADER_CONF, _MODULE_RE.format(mod), "") return {mod} def available(): """ Return a list of all available kernel modules CLI Example: .. code-block:: bash salt '*' kmod.available """ ret = [] for path in __salt__["file.find"]("/boot/kernel", name="*.ko$"): bpath = os.path.basename(path) comps = bpath.split(".") if "ko" in comps: # This is a kernel module, return it without the .ko extension ret.append(".".join(comps[: comps.index("ko")])) return ret def check_available(mod): """ Check to see if the specified kernel module is available CLI Example: .. code-block:: bash salt '*' kmod.check_available vmm """ return mod in available() def lsmod(): """ Return a dict containing information about currently loaded modules CLI Example: .. code-block:: bash salt '*' kmod.lsmod """ ret = [] for line in __salt__["cmd.run"]("kldstat").splitlines(): comps = line.split() if not len(comps) > 2: continue if comps[0] == "Id": continue if comps[4] == "kernel": continue ret.append({"module": comps[4][:-3], "size": comps[3], "depcount": comps[1]}) return ret def mod_list(only_persist=False): """ Return a list of the loaded module names CLI Example: .. code-block:: bash salt '*' kmod.mod_list """ mods = set() if only_persist: if not _get_persistent_modules(): return mods for mod in _get_persistent_modules(): mods.add(mod) else: for mod in lsmod(): mods.add(mod["module"]) return sorted(list(mods)) def load(mod, persist=False): """ Load the specified kernel module mod Name of the module to add persist Write the module to sysrc kld_modules to make it load on system reboot CLI Example: .. code-block:: bash salt '*' kmod.load bhyve """ pre_mods = lsmod() response = __salt__["cmd.run_all"]("kldload {}".format(mod), python_shell=False) if response["retcode"] == 0: post_mods = lsmod() mods = _new_mods(pre_mods, post_mods) persist_mods = set() if persist: persist_mods = _set_persistent_module(mod) return sorted(list(mods | persist_mods)) elif "module already loaded or in kernel" in response["stderr"]: if persist and mod not in _get_persistent_modules(): persist_mods = _set_persistent_module(mod) return sorted(list(persist_mods)) else: # It's compiled into the kernel return [None] else: return "Module {} not found".format(mod) def is_loaded(mod): """ Check to see if the specified kernel module is loaded CLI Example: .. code-block:: bash salt '*' kmod.is_loaded vmm """ return mod in mod_list() def remove(mod, persist=False, comment=True): """ Remove the specified kernel module mod Name of module to remove persist Also remove module from /boot/loader.conf comment If persist is set don't remove line from /boot/loader.conf but only comment it CLI Example: .. code-block:: bash salt '*' kmod.remove vmm """ pre_mods = lsmod() res = __salt__["cmd.run_all"]("kldunload {}".format(mod), python_shell=False) if res["retcode"] == 0: post_mods = lsmod() mods = _rm_mods(pre_mods, post_mods) persist_mods = set() if persist: persist_mods = _remove_persistent_module(mod, comment) return sorted(list(mods | persist_mods)) else: return "Error removing module {}: {}".format(mod, res["stderr"])
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/freebsdkmod.py
0.493897
0.153074
freebsdkmod.py
pypi
import salt.utils.platform from salt.exceptions import CommandExecutionError # Define the module's virtual name __virtualname__ = "desktop" def __virtual__(): """ Only load on Mac systems """ if salt.utils.platform.is_darwin(): return __virtualname__ return False, "Cannot load macOS desktop module: This is not a macOS host." def get_output_volume(): """ Get the output volume (range 0 to 100) CLI Example: .. code-block:: bash salt '*' desktop.get_output_volume """ cmd = 'osascript -e "get output volume of (get volume settings)"' call = __salt__["cmd.run_all"](cmd, output_loglevel="debug", python_shell=False) _check_cmd(call) return call.get("stdout") def set_output_volume(volume): """ Set the volume of sound. volume The level of volume. Can range from 0 to 100. CLI Example: .. code-block:: bash salt '*' desktop.set_output_volume <volume> """ cmd = 'osascript -e "set volume output volume {}"'.format(volume) call = __salt__["cmd.run_all"](cmd, output_loglevel="debug", python_shell=False) _check_cmd(call) return get_output_volume() def screensaver(): """ Launch the screensaver. CLI Example: .. code-block:: bash salt '*' desktop.screensaver """ cmd = "open /System/Library/Frameworks/ScreenSaver.framework/Versions/A/Resources/ScreenSaverEngine.app" call = __salt__["cmd.run_all"](cmd, output_loglevel="debug", python_shell=False) _check_cmd(call) return True def lock(): """ Lock the desktop session CLI Example: .. code-block:: bash salt '*' desktop.lock """ cmd = ( "/System/Library/CoreServices/Menu\\" " Extras/User.menu/Contents/Resources/CGSession -suspend" ) call = __salt__["cmd.run_all"](cmd, output_loglevel="debug", python_shell=False) _check_cmd(call) return True def say(*words): """ Say some words. words The words to execute the say command with. CLI Example: .. code-block:: bash salt '*' desktop.say <word0> <word1> ... <wordN> """ cmd = "say {}".format(" ".join(words)) call = __salt__["cmd.run_all"](cmd, output_loglevel="debug", python_shell=False) _check_cmd(call) return True def _check_cmd(call): """ Check the output of the cmd.run_all function call. """ if call["retcode"] != 0: comment = "" std_err = call.get("stderr") std_out = call.get("stdout") if std_err: comment += std_err if std_out: comment += std_out raise CommandExecutionError("Error running command: {}".format(comment)) return call
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/mac_desktop.py
0.577019
0.155495
mac_desktop.py
pypi
import logging import salt.utils.path log = logging.getLogger(__name__) def __virtual__(): """ Only load the module if Open vSwitch is installed """ if salt.utils.path.which("ovs-vsctl"): return "openvswitch" return (False, "Missing dependency: ovs-vsctl") def _param_may_exist(may_exist): """ Returns --may-exist parameter for Open vSwitch command. Args: may_exist: Boolean whether to use this parameter. Returns: String '--may-exist ' or empty string. """ if may_exist: return "--may-exist " else: return "" def _param_if_exists(if_exists): """ Returns --if-exist parameter for Open vSwitch command. Args: if_exists: Boolean whether to use this parameter. Returns: String '--if-exist ' or empty string. """ if if_exists: return "--if-exists " else: return "" def _retcode_to_bool(retcode): """ Evaulates Open vSwitch command`s retcode value. Args: retcode: Value of retcode field from response, should be 0, 1 or 2. Returns: True on 0, else False """ if retcode == 0: return True else: return False def _stdout_list_split(retcode, stdout="", splitstring="\n"): """ Evaulates Open vSwitch command`s retcode value. Args: retcode: Value of retcode field from response, should be 0, 1 or 2. stdout: Value of stdout filed from response. splitstring: String used to split the stdout default new line. Returns: List or False. """ if retcode == 0: ret = stdout.split(splitstring) return ret else: return False def bridge_list(): """ Lists all existing real and fake bridges. Returns: List of bridges (or empty list), False on failure. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.bridge_list """ cmd = "ovs-vsctl list-br" result = __salt__["cmd.run_all"](cmd) retcode = result["retcode"] stdout = result["stdout"] return _stdout_list_split(retcode, stdout) def bridge_exists(br): """ Tests whether bridge exists as a real or fake bridge. Returns: True if Bridge exists, else False. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.bridge_exists br0 """ cmd = "ovs-vsctl br-exists {}".format(br) result = __salt__["cmd.run_all"](cmd) retcode = result["retcode"] return _retcode_to_bool(retcode) def bridge_create(br, may_exist=True): """ Creates a new bridge. Args: br: A string - bridge name may_exist: Bool, if False - attempting to create a bridge that exists returns False. Returns: True on success, else False. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.bridge_create br0 """ param_may_exist = _param_may_exist(may_exist) cmd = "ovs-vsctl {1}add-br {0}".format(br, param_may_exist) result = __salt__["cmd.run_all"](cmd) return _retcode_to_bool(result["retcode"]) def bridge_delete(br, if_exists=True): """ Deletes bridge and all of its ports. Args: br: A string - bridge name if_exists: Bool, if False - attempting to delete a bridge that does not exist returns False. Returns: True on success, else False. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.bridge_delete br0 """ param_if_exists = _param_if_exists(if_exists) cmd = "ovs-vsctl {1}del-br {0}".format(br, param_if_exists) result = __salt__["cmd.run_all"](cmd) retcode = result["retcode"] return _retcode_to_bool(retcode) def port_add(br, port, may_exist=False, internal=False): """ Creates on bridge a new port named port. Returns: True on success, else False. Args: br: A string - bridge name port: A string - port name may_exist: Bool, if False - attempting to create a port that exists returns False. internal: A boolean to create an internal interface if one does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.port_add br0 8080 """ param_may_exist = _param_may_exist(may_exist) cmd = "ovs-vsctl {2}add-port {0} {1}".format(br, port, param_may_exist) if internal: cmd += " -- set interface {} type=internal".format(port) result = __salt__["cmd.run_all"](cmd) retcode = result["retcode"] return _retcode_to_bool(retcode) def port_remove(br, port, if_exists=True): """ Deletes port. Args: br: A string - bridge name (If bridge is None, port is removed from whatever bridge contains it) port: A string - port name. if_exists: Bool, if False - attempting to delete a por that does not exist returns False. (Default True) Returns: True on success, else False. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.port_remove br0 8080 """ param_if_exists = _param_if_exists(if_exists) if port and not br: cmd = "ovs-vsctl {1}del-port {0}".format(port, param_if_exists) else: cmd = "ovs-vsctl {2}del-port {0} {1}".format(br, port, param_if_exists) result = __salt__["cmd.run_all"](cmd) retcode = result["retcode"] return _retcode_to_bool(retcode) def port_list(br): """ Lists all of the ports within bridge. Args: br: A string - bridge name. Returns: List of bridges (or empty list), False on failure. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.port_list br0 """ cmd = "ovs-vsctl list-ports {}".format(br) result = __salt__["cmd.run_all"](cmd) retcode = result["retcode"] stdout = result["stdout"] return _stdout_list_split(retcode, stdout) def port_get_tag(port): """ Lists tags of the port. Args: port: A string - port name. Returns: List of tags (or empty list), False on failure. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.port_get_tag tap0 """ cmd = "ovs-vsctl get port {} tag".format(port) result = __salt__["cmd.run_all"](cmd) retcode = result["retcode"] stdout = result["stdout"] return _stdout_list_split(retcode, stdout) def interface_get_options(port): """ Port's interface's optional parameters. Args: port: A string - port name. Returns: String containing optional parameters of port's interface, False on failure. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.interface_get_options tap0 """ cmd = "ovs-vsctl get interface {} options".format(port) result = __salt__["cmd.run_all"](cmd) retcode = result["retcode"] stdout = result["stdout"] return _stdout_list_split(retcode, stdout) def interface_get_type(port): """ Type of port's interface. Args: port: A string - port name. Returns: String - type of interface or empty string, False on failure. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.interface_get_type tap0 """ cmd = "ovs-vsctl get interface {} type".format(port) result = __salt__["cmd.run_all"](cmd) retcode = result["retcode"] stdout = result["stdout"] return _stdout_list_split(retcode, stdout) def port_create_vlan(br, port, id, internal=False): """ Isolate VM traffic using VLANs. Args: br: A string - bridge name. port: A string - port name. id: An integer in the valid range 0 to 4095 (inclusive), name of VLAN. internal: A boolean to create an internal interface if one does not exist. Returns: True on success, else False. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.port_create_vlan br0 tap0 100 """ interfaces = __salt__["network.interfaces"]() if not 0 <= id <= 4095: return False elif not bridge_exists(br): return False elif not internal and port not in interfaces: return False elif port in port_list(br): cmd = "ovs-vsctl set port {} tag={}".format(port, id) if internal: cmd += " -- set interface {} type=internal".format(port) result = __salt__["cmd.run_all"](cmd) return _retcode_to_bool(result["retcode"]) else: cmd = "ovs-vsctl add-port {} {} tag={}".format(br, port, id) if internal: cmd += " -- set interface {} type=internal".format(port) result = __salt__["cmd.run_all"](cmd) return _retcode_to_bool(result["retcode"]) def port_create_gre(br, port, id, remote): """ Generic Routing Encapsulation - creates GRE tunnel between endpoints. Args: br: A string - bridge name. port: A string - port name. id: An integer - unsigned 32-bit number, tunnel's key. remote: A string - remote endpoint's IP address. Returns: True on success, else False. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.port_create_gre br0 gre1 5001 192.168.1.10 """ if not 0 <= id < 2 ** 32: return False elif not __salt__["dig.check_ip"](remote): return False elif not bridge_exists(br): return False elif port in port_list(br): cmd = "ovs-vsctl set interface {} type=gre options:remote_ip={} options:key={}".format( port, remote, id ) result = __salt__["cmd.run_all"](cmd) return _retcode_to_bool(result["retcode"]) else: cmd = ( "ovs-vsctl add-port {0} {1} -- set interface {1} type=gre" " options:remote_ip={2} options:key={3}".format(br, port, remote, id) ) result = __salt__["cmd.run_all"](cmd) return _retcode_to_bool(result["retcode"]) def port_create_vxlan(br, port, id, remote, dst_port=None): """ Virtual eXtensible Local Area Network - creates VXLAN tunnel between endpoints. Args: br: A string - bridge name. port: A string - port name. id: An integer - unsigned 64-bit number, tunnel's key. remote: A string - remote endpoint's IP address. dst_port: An integer - port to use when creating tunnelport in the switch. Returns: True on success, else False. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.port_create_vxlan br0 vx1 5001 192.168.1.10 8472 """ dst_port = " options:dst_port=" + str(dst_port) if 0 < dst_port <= 65535 else "" if not 0 <= id < 2 ** 64: return False elif not __salt__["dig.check_ip"](remote): return False elif not bridge_exists(br): return False elif port in port_list(br): cmd = ( "ovs-vsctl set interface {} type=vxlan options:remote_ip={} " "options:key={}{}".format(port, remote, id, dst_port) ) result = __salt__["cmd.run_all"](cmd) return _retcode_to_bool(result["retcode"]) else: cmd = ( "ovs-vsctl add-port {0} {1} -- set interface {1} type=vxlan" " options:remote_ip={2} options:key={3}{4}".format( br, port, remote, id, dst_port ) ) result = __salt__["cmd.run_all"](cmd) return _retcode_to_bool(result["retcode"])
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/openvswitch.py
0.788705
0.207215
openvswitch.py
pypi
import logging import re import salt.utils.path from salt.exceptions import CommandExecutionError, SaltInvocationError log = logging.getLogger(__name__) def __virtual__(): """ Only works on OpenBSD and FreeBSD for now; other systems with pf (macOS, FreeBSD, etc) need to be tested before enabling them. """ tested_oses = ["FreeBSD", "OpenBSD"] if __grains__["os"] in tested_oses and salt.utils.path.which("pfctl"): return True return ( False, "The pf execution module cannot be loaded: either the OS ({}) is not " "tested or the pfctl binary was not found".format(__grains__["os"]), ) def enable(): """ Enable the Packet Filter. CLI Example: .. code-block:: bash salt '*' pf.enable """ ret = {} result = __salt__["cmd.run_all"]( "pfctl -e", output_loglevel="trace", python_shell=False ) if result["retcode"] == 0: ret = {"comment": "pf enabled", "changes": True} else: # If pf was already enabled the return code is also non-zero. # Don't raise an exception in that case. if result["stderr"] == "pfctl: pf already enabled": ret = {"comment": "pf already enabled", "changes": False} else: raise CommandExecutionError( "Could not enable pf", info={"errors": [result["stderr"]], "changes": False}, ) return ret def disable(): """ Disable the Packet Filter. CLI Example: .. code-block:: bash salt '*' pf.disable """ ret = {} result = __salt__["cmd.run_all"]( "pfctl -d", output_loglevel="trace", python_shell=False ) if result["retcode"] == 0: ret = {"comment": "pf disabled", "changes": True} else: # If pf was already disabled the return code is also non-zero. # Don't raise an exception in that case. if result["stderr"] == "pfctl: pf not enabled": ret = {"comment": "pf already disabled", "changes": False} else: raise CommandExecutionError( "Could not disable pf", info={"errors": [result["stderr"]], "changes": False}, ) return ret def loglevel(level): """ Set the debug level which limits the severity of log messages printed by ``pf(4)``. level: Log level. Should be one of the following: emerg, alert, crit, err, warning, notice, info or debug (OpenBSD); or none, urgent, misc, loud (FreeBSD). CLI Example: .. code-block:: bash salt '*' pf.loglevel emerg """ # There's no way to getting the previous loglevel so imply we've # always made a change. ret = {"changes": True} myos = __grains__["os"] if myos == "FreeBSD": all_levels = ["none", "urgent", "misc", "loud"] else: all_levels = [ "emerg", "alert", "crit", "err", "warning", "notice", "info", "debug", ] if level not in all_levels: raise SaltInvocationError("Unknown loglevel: {}".format(level)) result = __salt__["cmd.run_all"]( "pfctl -x {}".format(level), output_loglevel="trace", python_shell=False ) if result["retcode"] != 0: raise CommandExecutionError( "Problem encountered setting loglevel", info={"errors": [result["stderr"]], "changes": False}, ) return ret def load(file="/etc/pf.conf", noop=False): """ Load a ruleset from the specific file, overwriting the currently loaded ruleset. file: Full path to the file containing the ruleset. noop: Don't actually load the rules, just parse them. CLI Example: .. code-block:: bash salt '*' pf.load /etc/pf.conf.d/lockdown.conf """ # We cannot precisely determine if loading the ruleset implied # any changes so assume it always does. ret = {"changes": True} cmd = ["pfctl", "-f", file] if noop: ret["changes"] = False cmd.append("-n") result = __salt__["cmd.run_all"](cmd, output_loglevel="trace", python_shell=False) if result["retcode"] != 0: raise CommandExecutionError( "Problem loading the ruleset from {}".format(file), info={"errors": [result["stderr"]], "changes": False}, ) return ret def flush(modifier): """ Flush the specified packet filter parameters. modifier: Should be one of the following: - all - info - osfp - rules - sources - states - tables Please refer to the OpenBSD `pfctl(8) <https://man.openbsd.org/pfctl#T>`_ documentation for a detailed explanation of each command. CLI Example: .. code-block:: bash salt '*' pf.flush states """ ret = {} all_modifiers = ["rules", "states", "info", "osfp", "all", "sources", "tables"] # Accept the following two modifiers to allow for a consistent interface between # pfctl(8) and Salt. capital_modifiers = ["Sources", "Tables"] all_modifiers += capital_modifiers if modifier.title() in capital_modifiers: modifier = modifier.title() if modifier not in all_modifiers: raise SaltInvocationError("Unknown modifier: {}".format(modifier)) cmd = "pfctl -v -F {}".format(modifier) result = __salt__["cmd.run_all"](cmd, output_loglevel="trace", python_shell=False) if result["retcode"] == 0: if re.match(r"^0.*", result["stderr"]): ret["changes"] = False else: ret["changes"] = True ret["comment"] = result["stderr"] else: raise CommandExecutionError( "Could not flush {}".format(modifier), info={"errors": [result["stderr"]], "changes": False}, ) return ret def table(command, table, **kwargs): """ Apply a command on the specified table. table: Name of the table. command: Command to apply to the table. Supported commands are: - add - delete - expire - flush - kill - replace - show - test - zero Please refer to the OpenBSD `pfctl(8) <https://man.openbsd.org/pfctl#T>`_ documentation for a detailed explanation of each command. CLI Example: .. code-block:: bash salt '*' pf.table expire table=spam_hosts number=300 salt '*' pf.table add table=local_hosts addresses='["127.0.0.1", "::1"]' """ ret = {} all_commands = [ "kill", "flush", "add", "delete", "expire", "replace", "show", "test", "zero", ] if command not in all_commands: raise SaltInvocationError("Unknown table command: {}".format(command)) cmd = ["pfctl", "-t", table, "-T", command] if command in ["add", "delete", "replace", "test"]: cmd += kwargs.get("addresses", []) elif command == "expire": number = kwargs.get("number", None) if not number: raise SaltInvocationError("need expire_number argument for expire command") else: cmd.append(number) result = __salt__["cmd.run_all"](cmd, output_level="trace", python_shell=False) if result["retcode"] == 0: if command == "show": ret = {"comment": result["stdout"].split()} elif command == "test": ret = {"comment": result["stderr"], "matches": True} else: if re.match(r"^(0.*|no changes)", result["stderr"]): ret["changes"] = False else: ret["changes"] = True ret["comment"] = result["stderr"] else: # 'test' returns a non-zero code if the address didn't match, even if # the command itself ran fine; also set 'matches' to False since not # everything matched. if command == "test" and re.match( r"^\d+/\d+ addresses match.$", result["stderr"] ): ret = {"comment": result["stderr"], "matches": False} else: raise CommandExecutionError( "Could not apply {} on table {}".format(command, table), info={"errors": [result["stderr"]], "changes": False}, ) return ret def show(modifier): """ Show filter parameters. modifier: Modifier to apply for filtering. Only a useful subset of what pfctl supports can be used with Salt. - rules - states - tables CLI Example: .. code-block:: bash salt '*' pf.show rules """ # By definition showing the parameters makes no changes. ret = {"changes": False} capital_modifiers = ["Tables"] all_modifiers = ["rules", "states", "tables"] all_modifiers += capital_modifiers if modifier.title() in capital_modifiers: modifier = modifier.title() if modifier not in all_modifiers: raise SaltInvocationError("Unknown modifier: {}".format(modifier)) cmd = "pfctl -s {}".format(modifier) result = __salt__["cmd.run_all"](cmd, output_loglevel="trace", python_shell=False) if result["retcode"] == 0: ret["comment"] = result["stdout"].split("\n") else: raise CommandExecutionError( "Could not show {}".format(modifier), info={"errors": [result["stderr"]], "changes": False}, ) return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/pf.py
0.591605
0.231875
pf.py
pypi
import logging import salt.utils.path from salt.utils.versions import warn_until_date log = logging.getLogger(__name__) HAS_PYCASSA = False try: from pycassa.system_manager import SystemManager HAS_PYCASSA = True except ImportError: pass def __virtual__(): """ Only load if pycassa is available and the system is configured """ if not HAS_PYCASSA: return ( False, "The cassandra execution module cannot be loaded: pycassa not installed.", ) warn_until_date( "20240101", "The cassandra returner is broken and deprecated, and will be removed" " after {date}. Use the cassandra_cql returner instead", ) if HAS_PYCASSA and salt.utils.path.which("nodetool"): return "cassandra" return ( False, "The cassandra execution module cannot be loaded: nodetool not found.", ) def _nodetool(cmd): """ Internal cassandra nodetool wrapper. Some functions are not available via pycassa so we must rely on nodetool. """ nodetool = __salt__["config.option"]("cassandra.nodetool") host = __salt__["config.option"]("cassandra.host") return __salt__["cmd.run_stdout"]("{} -h {} {}".format(nodetool, host, cmd)) def _sys_mgr(): """ Return a pycassa system manager connection object """ thrift_port = str(__salt__["config.option"]("cassandra.THRIFT_PORT")) host = __salt__["config.option"]("cassandra.host") return SystemManager("{}:{}".format(host, thrift_port)) def compactionstats(): """ Return compactionstats info CLI Example: .. code-block:: bash salt '*' cassandra.compactionstats """ return _nodetool("compactionstats") def version(): """ Return the cassandra version CLI Example: .. code-block:: bash salt '*' cassandra.version """ return _nodetool("version") def netstats(): """ Return netstats info CLI Example: .. code-block:: bash salt '*' cassandra.netstats """ return _nodetool("netstats") def tpstats(): """ Return tpstats info CLI Example: .. code-block:: bash salt '*' cassandra.tpstats """ return _nodetool("tpstats") def info(): """ Return cassandra node info CLI Example: .. code-block:: bash salt '*' cassandra.info """ return _nodetool("info") def ring(): """ Return cassandra ring info CLI Example: .. code-block:: bash salt '*' cassandra.ring """ return _nodetool("ring") def keyspaces(): """ Return existing keyspaces CLI Example: .. code-block:: bash salt '*' cassandra.keyspaces """ sys = _sys_mgr() return sys.list_keyspaces() def column_families(keyspace=None): """ Return existing column families for all keyspaces or just the provided one. CLI Example: .. code-block:: bash salt '*' cassandra.column_families salt '*' cassandra.column_families <keyspace> """ sys = _sys_mgr() ksps = sys.list_keyspaces() if keyspace: if keyspace in ksps: return list(sys.get_keyspace_column_families(keyspace).keys()) else: return None else: ret = {} for kspace in ksps: ret[kspace] = list(sys.get_keyspace_column_families(kspace).keys()) return ret def column_family_definition(keyspace, column_family): """ Return a dictionary of column family definitions for the given keyspace/column_family CLI Example: .. code-block:: bash salt '*' cassandra.column_family_definition <keyspace> <column_family> """ sys = _sys_mgr() try: return vars(sys.get_keyspace_column_families(keyspace)[column_family]) except Exception: # pylint: disable=broad-except log.debug("Invalid Keyspace/CF combination") return None
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/cassandra_mod.py
0.615897
0.157752
cassandra_mod.py
pypi
import fnmatch import glob import os import re __func_alias__ = {"reload_": "reload"} # Define the module's virtual name __virtualname__ = "service" def __virtual__(): """ Only work on NetBSD """ if __grains__["os"] == "NetBSD" and os.path.exists("/etc/rc.subr"): return __virtualname__ return ( False, "The netbsdservice execution module failed to load: only available on NetBSD.", ) def start(name): """ Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> """ cmd = "/etc/rc.d/{} onestart".format(name) return not __salt__["cmd.retcode"](cmd) def stop(name): """ Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> """ cmd = "/etc/rc.d/{} onestop".format(name) return not __salt__["cmd.retcode"](cmd) def restart(name): """ Restart the named service CLI Example: .. code-block:: bash salt '*' service.restart <service name> """ cmd = "/etc/rc.d/{} onerestart".format(name) return not __salt__["cmd.retcode"](cmd) def reload_(name): """ Reload the named service CLI Example: .. code-block:: bash salt '*' service.reload <service name> """ cmd = "/etc/rc.d/{} onereload".format(name) return not __salt__["cmd.retcode"](cmd) def force_reload(name): """ Force-reload the named service CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> """ cmd = "/etc/rc.d/{} forcereload".format(name) return not __salt__["cmd.retcode"](cmd) def status(name, sig=None): """ Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Signature to use to find the service via ps Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature] """ if sig: return bool(__salt__["status.pid"](sig)) contains_globbing = bool(re.search(r"\*|\?|\[.+\]", name)) if contains_globbing: services = fnmatch.filter(get_all(), name) else: services = [name] results = {} for service in services: cmd = "/etc/rc.d/{} onestatus".format(service) results[service] = not __salt__["cmd.retcode"](cmd, ignore_retcode=True) if contains_globbing: return results return results[name] def _get_svc(rcd, service_status): """ Returns a unique service status """ ena = None lines = __salt__["cmd.run"]("{} rcvar".format(rcd)).splitlines() for rcvar in lines: if rcvar.startswith("$") and "={}".format(service_status) in rcvar: ena = "yes" elif rcvar.startswith("#"): svc = rcvar.split(" ", 1)[1] else: continue if ena and svc: return svc return None def _get_svc_list(service_status): """ Returns all service statuses """ prefix = "/etc/rc.d/" ret = set() lines = glob.glob("{}*".format(prefix)) for line in lines: svc = _get_svc(line, service_status) if svc is not None: ret.add(svc) return sorted(ret) def get_enabled(): """ Return a list of service that are enabled on boot CLI Example: .. code-block:: bash salt '*' service.get_enabled """ return _get_svc_list("YES") def get_disabled(): """ Return a set of services that are installed but disabled CLI Example: .. code-block:: bash salt '*' service.get_disabled """ return _get_svc_list("NO") def available(name): """ Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd """ return name in get_all() def missing(name): """ The inverse of service.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd """ return name not in get_all() def get_all(): """ Return all available boot services CLI Example: .. code-block:: bash salt '*' service.get_all """ return _get_svc_list("") def _rcconf_status(name, service_status): """ Modifies /etc/rc.conf so a service is started or not at boot time and can be started via /etc/rc.d/<service> """ rcconf = "/etc/rc.conf" rxname = "^{}=.*".format(name) newstatus = "{}={}".format(name, service_status) ret = __salt__["cmd.retcode"]("grep '{}' {}".format(rxname, rcconf)) if ret == 0: # service found in rc.conf, modify its status __salt__["file.replace"](rcconf, rxname, newstatus) else: ret = __salt__["file.append"](rcconf, newstatus) return ret def enable(name, **kwargs): """ Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name> """ return _rcconf_status(name, "YES") def disable(name, **kwargs): """ Disable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.disable <service name> """ return _rcconf_status(name, "NO") def enabled(name, **kwargs): """ Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.enabled <service name> """ return _get_svc("/etc/rc.d/{}".format(name), "YES") def disabled(name): """ Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.disabled <service name> """ return _get_svc("/etc/rc.d/{}".format(name), "NO") # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/netbsdservice.py
0.676192
0.178705
netbsdservice.py
pypi
import datetime import hashlib import re import socket import salt.utils.network import salt.utils.platform import salt.utils.validate.net from salt._compat import ipaddress from salt.modules.network import ( calc_net, convert_cidr, get_fqdn, get_hostname, ifacestartswith, interface, interface_ip, ip_in_subnet, iphexval, subnets6, wol, ) from salt.utils.functools import namespaced_function try: import salt.utils.winapi HAS_DEPENDENCIES = True except ImportError: HAS_DEPENDENCIES = False try: import wmi # pylint: disable=import-error except ImportError: HAS_DEPENDENCIES = False if salt.utils.platform.is_windows() and HAS_DEPENDENCIES: wol = namespaced_function(wol, globals()) get_hostname = namespaced_function(get_hostname, globals()) interface = namespaced_function(interface, globals()) interface_ip = namespaced_function(interface_ip, globals()) subnets6 = namespaced_function(subnets6, globals()) ip_in_subnet = namespaced_function(ip_in_subnet, globals()) convert_cidr = namespaced_function(convert_cidr, globals()) calc_net = namespaced_function(calc_net, globals()) get_fqdn = namespaced_function(get_fqdn, globals()) ifacestartswith = namespaced_function(ifacestartswith, globals()) iphexval = namespaced_function(iphexval, globals()) # Define the module's virtual name __virtualname__ = "network" def __virtual__(): """ Only works on Windows systems """ if not salt.utils.platform.is_windows(): return False, "Module win_network: Only available on Windows" if not HAS_DEPENDENCIES: return False, "Module win_network: Missing dependencies" return __virtualname__ def ping(host, timeout=False, return_boolean=False): """ Performs a ping to a host CLI Example: .. code-block:: bash salt '*' network.ping archlinux.org .. versionadded:: 2016.11.0 Return a True or False instead of ping output. .. code-block:: bash salt '*' network.ping archlinux.org return_boolean=True Set the time to wait for a response in seconds. .. code-block:: bash salt '*' network.ping archlinux.org timeout=3 """ if timeout: # Windows ping differs by having timeout be for individual echo requests.' # Divide timeout by tries to mimic BSD behaviour. timeout = int(timeout) * 1000 // 4 cmd = [ "ping", "-n", "4", "-w", str(timeout), salt.utils.network.sanitize_host(host), ] else: cmd = ["ping", "-n", "4", salt.utils.network.sanitize_host(host)] if return_boolean: ret = __salt__["cmd.run_all"](cmd, python_shell=False) if ret["retcode"] != 0: return False else: return True else: return __salt__["cmd.run"](cmd, python_shell=False) def netstat(): """ Return information on open ports and states CLI Example: .. code-block:: bash salt '*' network.netstat """ ret = [] cmd = ["netstat", "-nao"] lines = __salt__["cmd.run"](cmd, python_shell=False).splitlines() for line in lines: comps = line.split() if line.startswith(" TCP"): ret.append( { "local-address": comps[1], "proto": comps[0], "remote-address": comps[2], "state": comps[3], "program": comps[4], } ) if line.startswith(" UDP"): ret.append( { "local-address": comps[1], "proto": comps[0], "remote-address": comps[2], "state": None, "program": comps[3], } ) return ret def traceroute(host): """ Performs a traceroute to a 3rd party host CLI Example: .. code-block:: bash salt '*' network.traceroute archlinux.org """ ret = [] cmd = ["tracert", salt.utils.network.sanitize_host(host)] lines = __salt__["cmd.run"](cmd, python_shell=False).splitlines() for line in lines: if " " not in line: continue if line.startswith("Trac"): continue if line.startswith("over"): continue comps = line.split() complength = len(comps) # This method still needs to better catch rows of other lengths # For example if some of the ms returns are '*' if complength == 9: result = { "count": comps[0], "hostname": comps[7], "ip": comps[8], "ms1": comps[1], "ms2": comps[3], "ms3": comps[5], } ret.append(result) elif complength == 8: result = { "count": comps[0], "hostname": None, "ip": comps[7], "ms1": comps[1], "ms2": comps[3], "ms3": comps[5], } ret.append(result) else: result = { "count": comps[0], "hostname": None, "ip": None, "ms1": None, "ms2": None, "ms3": None, } ret.append(result) return ret def nslookup(host): """ Query DNS for information about a domain or ip address CLI Example: .. code-block:: bash salt '*' network.nslookup archlinux.org """ ret = [] addresses = [] cmd = ["nslookup", salt.utils.network.sanitize_host(host)] lines = __salt__["cmd.run"](cmd, python_shell=False).splitlines() for line in lines: if addresses: # We're in the last block listing addresses addresses.append(line.strip()) continue if line.startswith("Non-authoritative"): continue if "Addresses" in line: comps = line.split(":", 1) addresses.append(comps[1].strip()) continue if ":" in line: comps = line.split(":", 1) ret.append({comps[0].strip(): comps[1].strip()}) if addresses: ret.append({"Addresses": addresses}) return ret def get_route(ip): """ Return routing information for given destination ip .. versionadded:: 2016.11.5 CLI Example: .. code-block:: bash salt '*' network.get_route 10.10.10.10 """ cmd = "Find-NetRoute -RemoteIPAddress {}".format(ip) out = __salt__["cmd.run"](cmd, shell="powershell", python_shell=True) regexp = re.compile( r"^IPAddress\s+:\s(?P<source>[\d\.:]+)?.*" r"^InterfaceAlias\s+:\s(?P<interface>[\w\.\:\-\ ]+)?.*" r"^NextHop\s+:\s(?P<gateway>[\d\.:]+)", flags=re.MULTILINE | re.DOTALL, ) m = regexp.search(out) ret = { "destination": ip, "gateway": m.group("gateway"), "interface": m.group("interface"), "source": m.group("source"), } return ret def dig(host): """ Performs a DNS lookup with dig Note: dig must be installed on the Windows minion CLI Example: .. code-block:: bash salt '*' network.dig archlinux.org """ cmd = ["dig", salt.utils.network.sanitize_host(host)] return __salt__["cmd.run"](cmd, python_shell=False) def interfaces_names(): """ Return a list of all the interfaces names CLI Example: .. code-block:: bash salt '*' network.interfaces_names """ ret = [] with salt.utils.winapi.Com(): c = wmi.WMI() for iface in c.Win32_NetworkAdapter(NetEnabled=True): ret.append(iface.NetConnectionID) return ret def interfaces(): """ Return a dictionary of information about all the interfaces on the minion CLI Example: .. code-block:: bash salt '*' network.interfaces """ return salt.utils.network.win_interfaces() def hw_addr(iface): """ Return the hardware address (a.k.a. MAC address) for a given interface CLI Example: .. code-block:: bash salt '*' network.hw_addr 'Wireless Connection #1' """ return salt.utils.network.hw_addr(iface) # Alias hwaddr to preserve backward compat hwaddr = salt.utils.functools.alias_function(hw_addr, "hwaddr") def subnets(): """ Returns a list of subnets to which the host belongs CLI Example: .. code-block:: bash salt '*' network.subnets """ return salt.utils.network.subnets() def in_subnet(cidr): """ Returns True if host is within specified subnet, otherwise False CLI Example: .. code-block:: bash salt '*' network.in_subnet 10.0.0.0/16 """ return salt.utils.network.in_subnet(cidr) def ip_addrs(interface=None, include_loopback=False, cidr=None, type=None): """ Returns a list of IPv4 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback 127.0.0.1 IPv4 address. cidr Describes subnet using CIDR notation and only IPv4 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 type If option set to 'public' then only public addresses will be returned. Ditto for 'private'. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs salt '*' network.ip_addrs cidr=10.0.0.0/8 salt '*' network.ip_addrs cidr=192.168.0.0/16 type=private """ addrs = salt.utils.network.ip_addrs( interface=interface, include_loopback=include_loopback ) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: if type == "public": return [i for i in addrs if not is_private(i)] elif type == "private": return [i for i in addrs if is_private(i)] else: return addrs ipaddrs = salt.utils.functools.alias_function(ip_addrs, "ipaddrs") def ip_addrs6(interface=None, include_loopback=False, cidr=None): """ Returns a list of IPv6 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback ::1 IPv6 address. cidr Describes subnet using CIDR notation and only IPv6 addresses that belong to this subnet will be returned. .. versionchanged:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.ip_addrs6 salt '*' network.ip_addrs6 cidr=2000::/3 """ addrs = salt.utils.network.ip_addrs6( interface=interface, include_loopback=include_loopback ) if cidr: return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])] else: return addrs ipaddrs6 = salt.utils.functools.alias_function(ip_addrs6, "ipaddrs6") def connect(host, port=None, **kwargs): """ Test connectivity to a host using a particular port from the minion. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' network.connect archlinux.org 80 salt '*' network.connect archlinux.org 80 timeout=3 salt '*' network.connect archlinux.org 80 timeout=3 family=ipv4 salt '*' network.connect google-public-dns-a.google.com port=53 proto=udp timeout=3 """ ret = {"result": None, "comment": ""} if not host: ret["result"] = False ret["comment"] = "Required argument, host, is missing." return ret if not port: ret["result"] = False ret["comment"] = "Required argument, port, is missing." return ret proto = kwargs.get("proto", "tcp") timeout = kwargs.get("timeout", 5) family = kwargs.get("family", None) if salt.utils.validate.net.ipv4_addr(host) or salt.utils.validate.net.ipv6_addr( host ): address = host else: address = "{}".format(salt.utils.network.sanitize_host(host)) # just in case we encounter error on getaddrinfo _address = ("unknown",) try: if proto == "udp": __proto = socket.SOL_UDP else: __proto = socket.SOL_TCP proto = "tcp" if family: if family == "ipv4": __family = socket.AF_INET elif family == "ipv6": __family = socket.AF_INET6 else: __family = 0 else: __family = 0 (family, socktype, _proto, garbage, _address) = socket.getaddrinfo( address, port, __family, 0, __proto )[0] skt = socket.socket(family, socktype, _proto) skt.settimeout(timeout) if proto == "udp": # Generate a random string of a # decent size to test UDP connection md5h = hashlib.md5() md5h.update(datetime.datetime.now().strftime("%s")) msg = md5h.hexdigest() skt.sendto(msg, _address) recv, svr = skt.recvfrom(255) skt.close() else: skt.connect(_address) skt.shutdown(2) except Exception as exc: # pylint: disable=broad-except ret["result"] = False ret["comment"] = "Unable to connect to {} ({}) on {} port {}".format( host, _address[0], proto, port ) return ret ret["result"] = True ret["comment"] = "Successfully connected to {} ({}) on {} port {}".format( host, _address[0], proto, port ) return ret def is_private(ip_addr): """ Check if the given IP address is a private address .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' network.is_private 10.0.0.3 """ return ipaddress.ip_address(ip_addr).is_private
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/win_network.py
0.477554
0.182826
win_network.py
pypi
import logging log = logging.getLogger(__name__) __func_alias__ = { "filter_": "filter", } def _udev(udev_info, key): """ Return the value for a udev key. The `key` parameter is a lower case text joined by dots. For example, 'e.id_bus' will represent the key for `udev_info['E']['ID_BUS']`. """ k, _, r = key.partition(".") if not k: return udev_info if not isinstance(udev_info, dict): return "n/a" if not r: return udev_info.get(k.upper(), "n/a") return _udev(udev_info.get(k.upper(), {}), r) def _match(udev_info, match_info): """ Check if `udev_info` match the information from `match_info`. """ res = True for key, value in match_info.items(): udev_value = _udev(udev_info, key) if isinstance(udev_value, dict): # If is a dict we probably make a mistake in key from # match_info, as is not accessing a final value log.warning( "The key %s for the udev information dictionary is not a leaf element", key, ) continue # Converting both values to sets make easy to see if there is # a coincidence between both values value = set(value) if isinstance(value, list) else {value} udev_value = set(udev_value) if isinstance(udev_value, list) else {udev_value} res = res and (value & udev_value) return res def filter_(udev_in=None, udev_ex=None): """ Returns a list of devices, filtered under udev keys. udev_in A dictionary of key:values that are expected in the device udev information udev_ex A dictionary of key:values that are not expected in the device udev information (excluded) The key is a lower case string, joined by dots, that represent a path in the udev information dictionary. For example, 'e.id_bus' will represent the udev entry `udev['E']['ID_BUS']` If the udev entry is a list, the algorithm will check that at least one item match one item of the value of the parameters. Returns list of devices that match `udev_in` and do not match `udev_ex`. CLI Example: .. code-block:: bash salt '*' devinfo.filter udev_in='{"e.id_bus": "ata"}' """ udev_in = udev_in if udev_in else {} udev_ex = udev_ex if udev_ex else {} all_devices = __grains__["disks"] # Get the udev information only one time udev_info = {d: __salt__["udev.info"](d) for d in all_devices} devices_udev_key_in = {d for d in all_devices if _match(udev_info[d], udev_in)} devices_udev_key_ex = { d for d in all_devices if _match(udev_info[d], udev_ex) if udev_ex } return sorted(devices_udev_key_in - devices_udev_key_ex) def _hwinfo_parse_short(report): """Parse the output of hwinfo and return a dictionary""" result = {} current_result = {} key_counter = 0 for line in report.strip().splitlines(): if line.startswith(" "): key = key_counter key_counter += 1 current_result[key] = line.strip() elif line.startswith(" "): key, value = line.strip().split(" ", 1) current_result[key] = value.strip() elif line.endswith(":"): key = line[:-1] value = {} result[key] = value current_result = value key_counter = 0 else: log.error("Error parsing hwinfo short output: %s", line) return result def _hwinfo_parse_full(report): """Parse the output of hwinfo and return a dictionary""" result = {} result_stack = [] level = 0 for line in report.strip().splitlines(): current_level = line.count(" ") if level != current_level or len(result_stack) != result_stack: result_stack = result_stack[:current_level] level = current_level line = line.strip() # Ignore empty lines if not line: continue # Initial line of a segment if level == 0: key, value = line.split(":", 1) sub_result = {} result[key] = sub_result # The first line contains also a sub-element key, value = value.strip().split(": ", 1) sub_result[key] = value result_stack.append(sub_result) level += 1 continue # Line is a note if line.startswith("[") or ":" not in line: sub_result = result_stack[-1] sub_result["Note"] = line if not line.startswith("[") else line[1:-1] continue key, value = line.split(":", 1) key, value = key.strip(), value.strip() sub_result = result_stack[-1] # If there is a value and it not starts with hash, this is a # (key, value) entry. But there are exception on the rule, # like when is about 'El Torito info', that is the begining of # a new dictorionart. if value and not value.startswith("#") and key != "El Torito info": if key == "I/O Port": key = "I/O Ports" elif key == "Config Status": value = dict(item.split("=") for item in value.split(", ")) elif key in ("Driver", "Driver Modules"): value = value.replace('"', "").split(", ") elif key in ("Tags", "Device Files", "Features"): # We cannot split by ', ', as using spaces in # inconsisten in some fields value = [v.strip() for v in value.split(",")] else: if value.startswith('"'): value = value[1:-1] # If there is a collision, we store it as a list if key in sub_result: current_value = sub_result[key] if type(current_value) is not list: current_value = [current_value] if value not in current_value: current_value.append(value) if len(current_value) == 1: value = current_value[0] else: value = current_value sub_result[key] = value else: if value.startswith("#"): value = {"Handle": value} elif key == "El Torito info": value = value.split(", ") value = { "platform": value[0].split()[-1], "bootable": "no" if "not" in value[1] else "yes", } else: value = {} sub_result[key] = value result_stack.append(value) level += 1 return result def _hwinfo_parse(report, short): """Parse the output of hwinfo and return a dictionary""" if short: return _hwinfo_parse_short(report) else: return _hwinfo_parse_full(report) def _hwinfo_efi(): """Return information about EFI""" return { "efi": __grains__["efi"], "efi-secure-boot": __grains__["efi-secure-boot"], } def _hwinfo_memory(): """Return information about the memory""" return { "mem_total": __grains__["mem_total"], } def _hwinfo_network(short): """Return network information""" info = { "fqdn": __grains__["fqdn"], "ip_interfaces": __grains__["ip_interfaces"], } if not short: info["dns"] = __grains__["dns"] return info def hwinfo(items=None, short=True, listmd=False, devices=None): """ Probe for hardware items List of hardware items to inspect. Default ['bios', 'cpu', 'disk', 'memory', 'network', 'partition'] short Show only a summary. Default True. listmd Report RAID devices. Default False. devices List of devices to show information from. Default None. CLI Example: .. code-block:: bash salt '*' devinfo.hwinfo salt '*' devinfo.hwinfo items='["disk"]' short=no salt '*' devinfo.hwinfo items='["disk"]' short=no devices='["/dev/sda"]' salt '*' devinfo.hwinfo devices=/dev/sda """ result = {} if not items: items = ["bios", "cpu", "disk", "memory", "network", "partition"] if not isinstance(items, (list, tuple)): items = [items] if not devices: devices = [] if devices and not isinstance(devices, (list, tuple)): devices = [devices] cmd = ["hwinfo"] for item in items: cmd.append("--{}".format(item)) if short: cmd.append("--short") if listmd: cmd.append("--listmd") for device in devices: cmd.append("--only {}".format(device)) out = __salt__["cmd.run_stdout"](cmd) result["hwinfo"] = _hwinfo_parse(out, short) if "bios" in items: result["bios grains"] = _hwinfo_efi() if "memory" in items: result["memory grains"] = _hwinfo_memory() if "network" in items: result["network grains"] = _hwinfo_network(short) return result
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/devinfo.py
0.729905
0.26877
devinfo.py
pypi
import fnmatch import logging import re import salt.utils.platform log = logging.getLogger(__name__) __func_alias__ = {"list_": "list"} # Define the module's virtual name __virtualname__ = "service" def __virtual__(): """ Only work on systems that are a proxy minion """ try: if ( salt.utils.platform.is_proxy() and __opts__["proxy"]["proxytype"] == "rest_sample" ): return __virtualname__ except KeyError: return ( False, "The rest_service execution module failed to load. Check the " "proxy key in pillar.", ) return ( False, "The rest_service execution module failed to load: only works on a " "rest_sample proxy minion.", ) def get_all(): """ Return a list of all available services .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' service.get_all """ proxy_fn = "rest_sample.service_list" return __proxy__[proxy_fn]() def list_(): """ Return a list of all available services. .. versionadded:: 2015.8.1 CLI Example: .. code-block:: bash salt '*' service.list """ return get_all() def start(name, sig=None): """ Start the specified service on the rest_sample .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' service.start <service name> """ proxy_fn = "rest_sample.service_start" return __proxy__[proxy_fn](name) def stop(name, sig=None): """ Stop the specified service on the rest_sample .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' service.stop <service name> """ proxy_fn = "rest_sample.service_stop" return __proxy__[proxy_fn](name) def restart(name, sig=None): """ Restart the specified service with rest_sample .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' service.restart <service name> """ proxy_fn = "rest_sample.service_restart" return __proxy__[proxy_fn](name) def status(name, sig=None): """ Return the status for a service via rest_sample. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionadded:: 2015.8.0 .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Not implemented Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> """ proxy_fn = "rest_sample.service_status" contains_globbing = bool(re.search(r"\*|\?|\[.+\]", name)) if contains_globbing: services = fnmatch.filter(get_all(), name) else: services = [name] results = {} for service in services: resp = __proxy__[proxy_fn](service) if resp["comment"] == "running": results[service] = True else: results[service] = False if contains_globbing: return results return results[name] def running(name, sig=None): """ Return whether this service is running. .. versionadded:: 2015.8.0 """ return status(name).get(name, False) def enabled(name, sig=None): """ Only the 'redbull' service is 'enabled' in the test .. versionadded:: 2015.8.1 """ return name == "redbull"
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/rest_service.py
0.713032
0.173253
rest_service.py
pypi
import base64 import random import salt.utils.data import salt.utils.pycrypto from salt.exceptions import SaltInvocationError # Define the module's virtual name __virtualname__ = "random" def __virtual__(): return __virtualname__ def hash(value, algorithm="sha512"): """ .. versionadded:: 2014.7.0 Encodes a value with the specified encoder. value The value to be hashed. algorithm : sha512 The algorithm to use. May be any valid algorithm supported by hashlib. CLI Example: .. code-block:: bash salt '*' random.hash 'I am a string' md5 """ return salt.utils.data.hash(value, algorithm=algorithm) def str_encode(value, encoder="base64"): """ .. versionadded:: 2014.7.0 value The value to be encoded. encoder : base64 The encoder to use on the subsequent string. CLI Example: .. code-block:: bash salt '*' random.str_encode 'I am a new string' base64 """ if isinstance(value, str): value = value.encode(__salt_system_encoding__) if encoder == "base64": try: out = base64.b64encode(value) out = out.decode(__salt_system_encoding__) except TypeError: raise SaltInvocationError("Value must be an encode-able string") else: try: out = value.encode(encoder) except LookupError: raise SaltInvocationError("You must specify a valid encoder") except AttributeError: raise SaltInvocationError("Value must be an encode-able string") return out def get_str( length=20, chars=None, lowercase=True, uppercase=True, digits=True, punctuation=True, whitespace=False, printable=False, ): """ .. versionadded:: 2014.7.0 .. versionchanged:: 3004.0 Changed the default character set used to include symbols and implemented arguments to control the used character set. Returns a random string of the specified length. length : 20 Any valid number of bytes. chars : None .. versionadded:: 3004.0 String with any character that should be used to generate random string. This argument supersedes all other character controlling arguments. lowercase : True .. versionadded:: 3004.0 Use lowercase letters in generated random string. (see :py:data:`string.ascii_lowercase`) This argument is superseded by chars. uppercase : True .. versionadded:: 3004.0 Use uppercase letters in generated random string. (see :py:data:`string.ascii_uppercase`) This argument is superseded by chars. digits : True .. versionadded:: 3004.0 Use digits in generated random string. (see :py:data:`string.digits`) This argument is superseded by chars. printable : False .. versionadded:: 3004.0 Use printable characters in generated random string and includes lowercase, uppercase, digits, punctuation and whitespace. (see :py:data:`string.printable`) It is disabled by default as includes whitespace characters which some systems do not handle well in passwords. This argument also supersedes all other classes because it includes them. This argument is superseded by chars. punctuation : True .. versionadded:: 3004.0 Use punctuation characters in generated random string. (see :py:data:`string.punctuation`) This argument is superseded by chars. whitespace : False .. versionadded:: 3004.0 Use whitespace characters in generated random string. (see :py:data:`string.whitespace`) It is disabled by default as some systems do not handle whitespace characters in passwords well. This argument is superseded by chars. CLI Example: .. code-block:: bash salt '*' random.get_str 128 salt '*' random.get_str 128 chars='abc123.!()' salt '*' random.get_str 128 lowercase=False whitespace=True """ return salt.utils.pycrypto.secure_password( length=length, chars=chars, lowercase=lowercase, uppercase=uppercase, digits=digits, punctuation=punctuation, whitespace=whitespace, printable=printable, ) def shadow_hash(crypt_salt=None, password=None, algorithm="sha512"): """ Generates a salted hash suitable for /etc/shadow. crypt_salt : None Salt to be used in the generation of the hash. If one is not provided, a random salt will be generated. password : None Value to be salted and hashed. If one is not provided, a random password will be generated. algorithm : sha512 Hash algorithm to use. CLI Example: .. code-block:: bash salt '*' random.shadow_hash 'My5alT' 'MyP@asswd' md5 """ return salt.utils.pycrypto.gen_hash(crypt_salt, password, algorithm) def rand_int(start=1, end=10, seed=None): """ Returns a random integer number between the start and end number. .. versionadded:: 2015.5.3 start : 1 Any valid integer number end : 10 Any valid integer number seed : Optional hashable object .. versionchanged:: 2019.2.0 Added seed argument. Will return the same result when run with the same seed. CLI Example: .. code-block:: bash salt '*' random.rand_int 1 10 """ if seed is not None: random.seed(seed) return random.randint(start, end) def seed(range=10, hash=None): """ Returns a random number within a range. Optional hash argument can be any hashable object. If hash is omitted or None, the id of the minion is used. .. versionadded:: 2015.8.0 hash: None Any hashable object. range: 10 Any valid integer number CLI Example: .. code-block:: bash salt '*' random.seed 10 hash=None """ if hash is None: hash = __grains__["id"] random.seed(hash) return random.randrange(range) def sample(value, size, seed=None): """ Return a given sample size from a list. By default, the random number generator uses the current system time unless given a seed value. .. versionadded:: 3005 value A list to e used as input. size The sample size to return. seed Any value which will be hashed as a seed for random. CLI Example: .. code-block:: bash salt '*' random.sample '["one", "two"]' 1 seed="something" """ return salt.utils.data.sample(value, size, seed=seed) def shuffle(value, seed=None): """ Return a shuffled copy of an input list. By default, the random number generator uses the current system time unless given a seed value. .. versionadded:: 3005 value A list to be used as input. seed Any value which will be hashed as a seed for random. CLI Example: .. code-block:: bash salt '*' random.shuffle '["one", "two"]' seed="something" """ return salt.utils.data.shuffle(value, seed=seed)
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/mod_random.py
0.820829
0.296737
mod_random.py
pypi
import getpass import shlex import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError __virtualname__ = "system" def __virtual__(): """ Only for MacOS with atrun enabled """ if not salt.utils.platform.is_darwin(): return ( False, "The mac_system module could not be loaded: " "module only works on MacOS systems.", ) if getpass.getuser() != "root": return False, "The mac_system module is not useful for non-root users." if not _atrun_enabled(): if not _enable_atrun(): return False, "atrun could not be enabled on this system" return __virtualname__ def _atrun_enabled(): """ Check to see if atrun is running and enabled on the system """ try: return __salt__["service.list"]("com.apple.atrun") except CommandExecutionError: return False def _enable_atrun(): """ Enable and start the atrun daemon """ name = "com.apple.atrun" try: __salt__["service.enable"](name) __salt__["service.start"](name) except CommandExecutionError: return False return _atrun_enabled() def _execute_command(cmd, at_time=None): """ Helper function to execute the command :param str cmd: the command to run :param str at_time: If passed, the cmd will be scheduled. Returns: bool """ if at_time: cmd = "echo '{}' | at {}".format(cmd, shlex.quote(at_time)) return not bool(__salt__["cmd.retcode"](cmd, python_shell=True)) def halt(at_time=None): """ Halt a running system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.halt salt '*' system.halt 'now + 10 minutes' """ cmd = "shutdown -h now" return _execute_command(cmd, at_time) def sleep(at_time=None): """ Sleep the system. If a user is active on the system it will likely fail to sleep. :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.sleep salt '*' system.sleep '10:00 PM' """ cmd = "shutdown -s now" return _execute_command(cmd, at_time) def restart(at_time=None): """ Restart the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.restart salt '*' system.restart '12:00 PM fri' """ cmd = "shutdown -r now" return _execute_command(cmd, at_time) def shutdown(at_time=None): """ Shutdown the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.shutdown salt '*' system.shutdown 'now + 1 hour' """ return halt(at_time) def get_remote_login(): """ Displays whether remote login (SSH) is on or off. :return: True if remote login is on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_login """ ret = __utils__["mac_utils.execute_return_result"]("systemsetup -getremotelogin") enabled = __utils__["mac_utils.validate_enabled"]( __utils__["mac_utils.parse_return"](ret) ) return enabled == "on" def set_remote_login(enable): """ Set the remote login (SSH) to either on or off. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_login True """ state = __utils__["mac_utils.validate_enabled"](enable) cmd = "systemsetup -f -setremotelogin {}".format(state) __utils__["mac_utils.execute_return_success"](cmd) return __utils__["mac_utils.confirm_updated"]( state, get_remote_login, normalize_ret=True ) def get_remote_events(): """ Displays whether remote apple events are on or off. :return: True if remote apple events are on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_events """ ret = __utils__["mac_utils.execute_return_result"]( "systemsetup -getremoteappleevents" ) enabled = __utils__["mac_utils.validate_enabled"]( __utils__["mac_utils.parse_return"](ret) ) return enabled == "on" def set_remote_events(enable): """ Set whether the server responds to events sent by other computers (such as AppleScripts) :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_events On """ state = __utils__["mac_utils.validate_enabled"](enable) cmd = "systemsetup -setremoteappleevents {}".format(state) __utils__["mac_utils.execute_return_success"](cmd) return __utils__["mac_utils.confirm_updated"]( state, get_remote_events, normalize_ret=True, ) def get_computer_name(): """ Gets the computer name :return: The computer name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_name """ ret = __utils__["mac_utils.execute_return_result"]("scutil --get ComputerName") return __utils__["mac_utils.parse_return"](ret) def set_computer_name(name): """ Set the computer name :param str name: The new computer name :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_computer_name "Mike's Mac" """ cmd = 'scutil --set ComputerName "{}"'.format(name) __utils__["mac_utils.execute_return_success"](cmd) return __utils__["mac_utils.confirm_updated"]( name, get_computer_name, ) def get_subnet_name(): """ Gets the local subnet name :return: The local subnet name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_subnet_name """ ret = __utils__["mac_utils.execute_return_result"]( "systemsetup -getlocalsubnetname" ) return __utils__["mac_utils.parse_return"](ret) def set_subnet_name(name): """ Set the local subnet name :param str name: The new local subnet name .. note:: Spaces are changed to dashes. Other special characters are removed. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash The following will be set as 'Mikes-Mac' salt '*' system.set_subnet_name "Mike's Mac" """ cmd = 'systemsetup -setlocalsubnetname "{}"'.format(name) __utils__["mac_utils.execute_return_success"](cmd) return __utils__["mac_utils.confirm_updated"]( name, get_subnet_name, ) def get_startup_disk(): """ Displays the current startup disk :return: The current startup disk :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_startup_disk """ ret = __utils__["mac_utils.execute_return_result"]("systemsetup -getstartupdisk") return __utils__["mac_utils.parse_return"](ret) def list_startup_disks(): """ List all valid startup disks on the system. :return: A list of valid startup disks :rtype: list CLI Example: .. code-block:: bash salt '*' system.list_startup_disks """ ret = __utils__["mac_utils.execute_return_result"]("systemsetup -liststartupdisks") return ret.splitlines() def set_startup_disk(path): """ Set the current startup disk to the indicated path. Use ``system.list_startup_disks`` to find valid startup disks on the system. :param str path: The valid startup disk path :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_startup_disk /System/Library/CoreServices """ if path not in list_startup_disks(): msg = ( "Invalid value passed for path.\n" "Must be a valid startup disk as found in " "system.list_startup_disks.\n" "Passed: {}".format(path) ) raise SaltInvocationError(msg) cmd = "systemsetup -setstartupdisk {}".format(path) __utils__["mac_utils.execute_return_result"](cmd) return __utils__["mac_utils.confirm_updated"]( path, get_startup_disk, ) def get_restart_delay(): """ Get the number of seconds after which the computer will start up after a power failure. :return: A string value representing the number of seconds the system will delay restart after power loss :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_restart_delay """ ret = __utils__["mac_utils.execute_return_result"]( "systemsetup -getwaitforstartupafterpowerfailure" ) return __utils__["mac_utils.parse_return"](ret) def set_restart_delay(seconds): """ Set the number of seconds after which the computer will start up after a power failure. .. warning:: This command fails with the following error: ``Error, IOServiceOpen returned 0x10000003`` The setting is not updated. This is an apple bug. It seems like it may only work on certain versions of Mac Server X. This article explains the issue in more detail, though it is quite old. http://lists.apple.com/archives/macos-x-server/2006/Jul/msg00967.html :param int seconds: The number of seconds. Must be a multiple of 30 :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_restart_delay 180 """ if seconds % 30 != 0: msg = ( "Invalid value passed for seconds.\n" "Must be a multiple of 30.\n" "Passed: {}".format(seconds) ) raise SaltInvocationError(msg) cmd = "systemsetup -setwaitforstartupafterpowerfailure {}".format(seconds) __utils__["mac_utils.execute_return_success"](cmd) return __utils__["mac_utils.confirm_updated"]( seconds, get_restart_delay, ) def get_disable_keyboard_on_lock(): """ Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :return: True if disable keyboard on lock is on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_disable_keyboard_on_lock """ ret = __utils__["mac_utils.execute_return_result"]( "systemsetup -getdisablekeyboardwhenenclosurelockisengaged" ) enabled = __utils__["mac_utils.validate_enabled"]( __utils__["mac_utils.parse_return"](ret) ) return enabled == "on" def set_disable_keyboard_on_lock(enable): """ Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_disable_keyboard_on_lock False """ state = __utils__["mac_utils.validate_enabled"](enable) cmd = "systemsetup -setdisablekeyboardwhenenclosurelockisengaged {}".format(state) __utils__["mac_utils.execute_return_success"](cmd) return __utils__["mac_utils.confirm_updated"]( state, get_disable_keyboard_on_lock, normalize_ret=True, ) def get_boot_arch(): """ Get the kernel architecture setting from ``com.apple.Boot.plist`` :return: A string value representing the boot architecture setting :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_boot_arch """ ret = __utils__["mac_utils.execute_return_result"]( "systemsetup -getkernelbootarchitecturesetting" ) arch = __utils__["mac_utils.parse_return"](ret) if "default" in arch: return "default" elif "i386" in arch: return "i386" elif "x86_64" in arch: return "x86_64" return "unknown" def set_boot_arch(arch="default"): """ Set the kernel to boot in 32 or 64 bit mode on next boot. .. note:: When this function fails with the error ``changes to kernel architecture failed to save!``, then the boot arch is not updated. This is either an Apple bug, not available on the test system, or a result of system files being locked down in macOS (SIP Protection). :param str arch: A string representing the desired architecture. If no value is passed, default is assumed. Valid values include: - i386 - x86_64 - default :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_boot_arch i386 """ if arch not in ["i386", "x86_64", "default"]: msg = ( "Invalid value passed for arch.\n" "Must be i386, x86_64, or default.\n" "Passed: {}".format(arch) ) raise SaltInvocationError(msg) cmd = "systemsetup -setkernelbootarchitecture {}".format(arch) __utils__["mac_utils.execute_return_success"](cmd) return __utils__["mac_utils.confirm_updated"]( arch, get_boot_arch, )
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/mac_system.py
0.637595
0.240775
mac_system.py
pypi
import logging import time import salt.utils.compat import salt.utils.data import salt.utils.json import salt.utils.versions from salt.exceptions import CommandExecutionError, SaltInvocationError try: # pylint: disable=unused-import import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.blockdevicemapping import BlockDeviceMapping, BlockDeviceType from boto.ec2.networkinterface import ( NetworkInterfaceSpecification, NetworkInterfaceCollection, ) HAS_BOTO = True except ImportError: HAS_BOTO = False log = logging.getLogger(__name__) def __virtual__(): """ Only load if boto libraries exist and if boto libraries are greater than a given version. """ # the boto_ec2 execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver="2.8.0", check_boto3=False ) if has_boto_reqs is True: __utils__["boto.assign_funcs"](__name__, "ec2", pack=__salt__) return has_boto_reqs def __init__(opts): if HAS_BOTO: __utils__["boto.assign_funcs"](__name__, "ec2") def _get_all_eip_addresses( addresses=None, allocation_ids=None, region=None, key=None, keyid=None, profile=None ): """ Get all EIP's associated with the current credentials. addresses (list) - Optional list of addresses. If provided, only those those in the list will be returned. allocation_ids (list) - Optional list of allocation IDs. If provided, only the addresses associated with the given allocation IDs will be returned. returns (list) - The requested Addresses as a list of :class:`boto.ec2.address.Address` """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_addresses( addresses=addresses, allocation_ids=allocation_ids ) except boto.exception.BotoServerError as e: log.error(e) return [] def get_all_eip_addresses( addresses=None, allocation_ids=None, region=None, key=None, keyid=None, profile=None ): """ Get public addresses of some, or all EIPs associated with the current account. addresses (list) - Optional list of addresses. If provided, only the addresses associated with those in the list will be returned. allocation_ids (list) - Optional list of allocation IDs. If provided, only the addresses associated with the given allocation IDs will be returned. returns (list) - A list of the requested EIP addresses CLI Example: .. code-block:: bash salt-call boto_ec2.get_all_eip_addresses .. versionadded:: 2016.3.0 """ return [ x.public_ip for x in _get_all_eip_addresses( addresses, allocation_ids, region, key, keyid, profile ) ] def get_unassociated_eip_address( domain="standard", region=None, key=None, keyid=None, profile=None ): """ Return the first unassociated EIP domain Indicates whether the address is an EC2 address or a VPC address (standard|vpc). CLI Example: .. code-block:: bash salt-call boto_ec2.get_unassociated_eip_address .. versionadded:: 2016.3.0 """ eip = None for address in get_all_eip_addresses( region=region, key=key, keyid=keyid, profile=profile ): address_info = get_eip_address_info( addresses=address, region=region, key=key, keyid=keyid, profile=profile )[0] if address_info["instance_id"]: log.debug( "%s is already associated with the instance %s", address, address_info["instance_id"], ) continue if address_info["network_interface_id"]: log.debug( "%s is already associated with the network interface %s", address, address_info["network_interface_id"], ) continue if address_info["domain"] == domain: log.debug( "The first unassociated EIP address in the domain '%s' is %s", domain, address, ) eip = address break if not eip: log.debug("No unassociated Elastic IP found!") return eip def get_eip_address_info( addresses=None, allocation_ids=None, region=None, key=None, keyid=None, profile=None ): """ Get 'interesting' info about some, or all EIPs associated with the current account. addresses (list) - Optional list of addresses. If provided, only the addresses associated with those in the list will be returned. allocation_ids (list) - Optional list of allocation IDs. If provided, only the addresses associated with the given allocation IDs will be returned. returns (list of dicts) - A list of dicts, each containing the info for one of the requested EIPs. CLI Example: .. code-block:: bash salt-call boto_ec2.get_eip_address_info addresses=52.4.2.15 .. versionadded:: 2016.3.0 """ if isinstance(addresses, str): addresses = [addresses] if isinstance(allocation_ids, str): allocation_ids = [allocation_ids] ret = _get_all_eip_addresses( addresses=addresses, allocation_ids=allocation_ids, region=region, key=key, keyid=keyid, profile=profile, ) interesting = [ "allocation_id", "association_id", "domain", "instance_id", "network_interface_id", "network_interface_owner_id", "public_ip", "private_ip_address", ] return [{x: getattr(address, x) for x in interesting} for address in ret] def allocate_eip_address(domain=None, region=None, key=None, keyid=None, profile=None): """ Allocate a new Elastic IP address and associate it with your account. domain (string) Optional param - if set to exactly 'vpc', the address will be allocated to the VPC. The default simply maps the EIP to your account container. returns (dict) dict of 'interesting' information about the newly allocated EIP, with probably the most interesting keys being 'public_ip'; and 'allocation_id' iff 'domain=vpc' was passed. CLI Example: .. code-block:: bash salt-call boto_ec2.allocate_eip_address domain=vpc .. versionadded:: 2016.3.0 """ if domain and domain != "vpc": raise SaltInvocationError( "The only permitted value for the 'domain' param is 'vpc'." ) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: address = conn.allocate_address(domain=domain) except boto.exception.BotoServerError as e: log.error(e) return False interesting = [ "allocation_id", "association_id", "domain", "instance_id", "network_interface_id", "network_interface_owner_id", "public_ip", "private_ip_address", ] return {x: getattr(address, x) for x in interesting} def release_eip_address( public_ip=None, allocation_id=None, region=None, key=None, keyid=None, profile=None ): """ Free an Elastic IP address. Pass either a public IP address to release an EC2 Classic EIP, or an AllocationId to release a VPC EIP. public_ip (string) - The public IP address - for EC2 elastic IPs. allocation_id (string) - The Allocation ID - for VPC elastic IPs. returns (bool) - True on success, False on failure CLI Example: .. code-block:: bash salt myminion boto_ec2.release_eip_address allocation_id=eipalloc-ef382c8a .. versionadded:: 2016.3.0 """ if not salt.utils.data.exactly_one((public_ip, allocation_id)): raise SaltInvocationError( "Exactly one of 'public_ip' OR 'allocation_id' must be provided" ) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.release_address(public_ip, allocation_id) except boto.exception.BotoServerError as e: log.error(e) return False def associate_eip_address( instance_id=None, instance_name=None, public_ip=None, allocation_id=None, network_interface_id=None, network_interface_name=None, private_ip_address=None, allow_reassociation=False, region=None, key=None, keyid=None, profile=None, ): """ Associate an Elastic IP address with a currently running instance or a network interface. This requires exactly one of either 'public_ip' or 'allocation_id', depending on whether you’re associating a VPC address or a plain EC2 address. instance_id (string) – ID of the instance to associate with (exclusive with 'instance_name') instance_name (string) – Name tag of the instance to associate with (exclusive with 'instance_id') public_ip (string) – Public IP address, for standard EC2 based allocations. allocation_id (string) – Allocation ID for a VPC-based EIP. network_interface_id (string) - ID of the network interface to associate the EIP with network_interface_name (string) - Name of the network interface to associate the EIP with private_ip_address (string) – The primary or secondary private IP address to associate with the Elastic IP address. allow_reassociation (bool) – Allow a currently associated EIP to be re-associated with the new instance or interface. returns (bool) - True on success, False on failure. CLI Example: .. code-block:: bash salt myminion boto_ec2.associate_eip_address instance_name=bubba.ho.tep allocation_id=eipalloc-ef382c8a .. versionadded:: 2016.3.0 """ if not salt.utils.data.exactly_one( (instance_id, instance_name, network_interface_id, network_interface_name) ): raise SaltInvocationError( "Exactly one of 'instance_id', " "'instance_name', 'network_interface_id', " "'network_interface_name' must be provided" ) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_name: try: instance_id = get_id( name=instance_name, region=region, key=key, keyid=keyid, profile=profile ) except boto.exception.BotoServerError as e: log.error(e) return False if not instance_id: log.error( "Given instance_name '%s' cannot be mapped to an instance_id", instance_name, ) return False if network_interface_name: try: network_interface_id = get_network_interface_id( network_interface_name, region=region, key=key, keyid=keyid, profile=profile, ) except boto.exception.BotoServerError as e: log.error(e) return False if not network_interface_id: log.error( "Given network_interface_name '%s' cannot be mapped to " "an network_interface_id", network_interface_name, ) return False try: return conn.associate_address( instance_id=instance_id, public_ip=public_ip, allocation_id=allocation_id, network_interface_id=network_interface_id, private_ip_address=private_ip_address, allow_reassociation=allow_reassociation, ) except boto.exception.BotoServerError as e: log.error(e) return False def disassociate_eip_address( public_ip=None, association_id=None, region=None, key=None, keyid=None, profile=None ): """ Disassociate an Elastic IP address from a currently running instance. This requires exactly one of either 'association_id' or 'public_ip', depending on whether you’re dealing with a VPC or EC2 Classic address. public_ip (string) – Public IP address, for EC2 Classic allocations. association_id (string) – Association ID for a VPC-bound EIP. returns (bool) - True on success, False on failure. CLI Example: .. code-block:: bash salt myminion boto_ec2.disassociate_eip_address association_id=eipassoc-e3ba2d16 .. versionadded:: 2016.3.0 """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.disassociate_address(public_ip, association_id) except boto.exception.BotoServerError as e: log.error(e) return False def assign_private_ip_addresses( network_interface_name=None, network_interface_id=None, private_ip_addresses=None, secondary_private_ip_address_count=None, allow_reassignment=False, region=None, key=None, keyid=None, profile=None, ): """ Assigns one or more secondary private IP addresses to a network interface. network_interface_id (string) - ID of the network interface to associate the IP with (exclusive with 'network_interface_name') network_interface_name (string) - Name of the network interface to associate the IP with (exclusive with 'network_interface_id') private_ip_addresses (list) - Assigns the specified IP addresses as secondary IP addresses to the network interface (exclusive with 'secondary_private_ip_address_count') secondary_private_ip_address_count (int) - The number of secondary IP addresses to assign to the network interface. (exclusive with 'private_ip_addresses') allow_reassociation (bool) – Allow a currently associated EIP to be re-associated with the new instance or interface. returns (bool) - True on success, False on failure. CLI Example: .. code-block:: bash salt myminion boto_ec2.assign_private_ip_addresses network_interface_name=my_eni private_ip_addresses=private_ip salt myminion boto_ec2.assign_private_ip_addresses network_interface_name=my_eni secondary_private_ip_address_count=2 .. versionadded:: 2017.7.0 """ if not salt.utils.data.exactly_one((network_interface_name, network_interface_id)): raise SaltInvocationError( "Exactly one of 'network_interface_name', " "'network_interface_id' must be provided" ) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if network_interface_name: try: network_interface_id = get_network_interface_id( network_interface_name, region=region, key=key, keyid=keyid, profile=profile, ) except boto.exception.BotoServerError as e: log.error(e) return False if not network_interface_id: log.error( "Given network_interface_name '%s' cannot be mapped to " "an network_interface_id", network_interface_name, ) return False try: return conn.assign_private_ip_addresses( network_interface_id=network_interface_id, private_ip_addresses=private_ip_addresses, secondary_private_ip_address_count=secondary_private_ip_address_count, allow_reassignment=allow_reassignment, ) except boto.exception.BotoServerError as e: log.error(e) return False def unassign_private_ip_addresses( network_interface_name=None, network_interface_id=None, private_ip_addresses=None, region=None, key=None, keyid=None, profile=None, ): """ Unassigns one or more secondary private IP addresses from a network interface network_interface_id (string) - ID of the network interface to associate the IP with (exclusive with 'network_interface_name') network_interface_name (string) - Name of the network interface to associate the IP with (exclusive with 'network_interface_id') private_ip_addresses (list) - Assigns the specified IP addresses as secondary IP addresses to the network interface. returns (bool) - True on success, False on failure. CLI Example: .. code-block:: bash salt myminion boto_ec2.unassign_private_ip_addresses network_interface_name=my_eni private_ip_addresses=private_ip .. versionadded:: 2017.7.0 """ if not salt.utils.data.exactly_one((network_interface_name, network_interface_id)): raise SaltInvocationError( "Exactly one of 'network_interface_name', " "'network_interface_id' must be provided" ) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if network_interface_name: try: network_interface_id = get_network_interface_id( network_interface_name, region=region, key=key, keyid=keyid, profile=profile, ) except boto.exception.BotoServerError as e: log.error(e) return False if not network_interface_id: log.error( "Given network_interface_name '%s' cannot be mapped to " "an network_interface_id", network_interface_name, ) return False try: return conn.unassign_private_ip_addresses( network_interface_id=network_interface_id, private_ip_addresses=private_ip_addresses, ) except boto.exception.BotoServerError as e: log.error(e) return False def get_zones(region=None, key=None, keyid=None, profile=None): """ Get a list of AZs for the configured region. CLI Example: .. code-block:: bash salt myminion boto_ec2.get_zones """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) return [z.name for z in conn.get_all_zones()] def find_instances( instance_id=None, name=None, tags=None, region=None, key=None, keyid=None, profile=None, return_objs=False, in_states=None, filters=None, ): """ Given instance properties, find and return matching instance ids CLI Examples: .. code-block:: bash salt myminion boto_ec2.find_instances # Lists all instances salt myminion boto_ec2.find_instances name=myinstance salt myminion boto_ec2.find_instances tags='{"mytag": "value"}' salt myminion boto_ec2.find_instances filters='{"vpc-id": "vpc-12345678"}' """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: filter_parameters = {"filters": {}} if instance_id: filter_parameters["instance_ids"] = [instance_id] if name: filter_parameters["filters"]["tag:Name"] = name if tags: for tag_name, tag_value in tags.items(): filter_parameters["filters"]["tag:{}".format(tag_name)] = tag_value if filters: filter_parameters["filters"].update(filters) reservations = conn.get_all_reservations(**filter_parameters) instances = [i for r in reservations for i in r.instances] log.debug( "The filters criteria %s matched the following instances:%s", filter_parameters, instances, ) if in_states: instances = [i for i in instances if i.state in in_states] log.debug( "Limiting instance matches to those in the requested states: %s", instances, ) if instances: if return_objs: return instances return [instance.id for instance in instances] else: return [] except boto.exception.BotoServerError as exc: log.error(exc) return [] def create_image( ami_name, instance_id=None, instance_name=None, tags=None, region=None, key=None, keyid=None, profile=None, description=None, no_reboot=False, dry_run=False, filters=None, ): """ Given instance properties that define exactly one instance, create AMI and return AMI-id. CLI Examples: .. code-block:: bash salt myminion boto_ec2.create_image ami_name instance_name=myinstance salt myminion boto_ec2.create_image another_ami_name tags='{"mytag": "value"}' description='this is my ami' """ instances = find_instances( instance_id=instance_id, name=instance_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile, return_objs=True, filters=filters, ) if not instances: log.error("Source instance not found") return False if len(instances) > 1: log.error( "Multiple instances found, must match exactly only one instance to create" " an image from" ) return False instance = instances[0] try: return instance.create_image( ami_name, description=description, no_reboot=no_reboot, dry_run=dry_run ) except boto.exception.BotoServerError as exc: log.error(exc) return False def find_images( ami_name=None, executable_by=None, owners=None, image_ids=None, tags=None, region=None, key=None, keyid=None, profile=None, return_objs=False, ): """ Given image properties, find and return matching AMI ids CLI Examples: .. code-block:: bash salt myminion boto_ec2.find_images tags='{"mytag": "value"}' """ retries = 30 conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) while retries: try: filter_parameters = {"filters": {}} if image_ids: filter_parameters["image_ids"] = [image_ids] if executable_by: filter_parameters["executable_by"] = [executable_by] if owners: filter_parameters["owners"] = [owners] if ami_name: filter_parameters["filters"]["name"] = ami_name if tags: for tag_name, tag_value in tags.items(): filter_parameters["filters"]["tag:{}".format(tag_name)] = tag_value images = conn.get_all_images(**filter_parameters) log.debug( "The filters criteria %s matched the following images:%s", filter_parameters, images, ) if images: if return_objs: return images return [image.id for image in images] else: return False except boto.exception.BotoServerError as exc: if exc.error_code == "Throttling": log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error("Failed to convert AMI name `%s` to an AMI ID: %s", ami_name, exc) return False return False def terminate( instance_id=None, name=None, region=None, key=None, keyid=None, profile=None, filters=None, ): """ Terminate the instance described by instance_id or name. CLI Example: .. code-block:: bash salt myminion boto_ec2.terminate name=myinstance salt myminion boto_ec2.terminate instance_id=i-a46b9f """ instances = find_instances( instance_id=instance_id, name=name, region=region, key=key, keyid=keyid, profile=profile, return_objs=True, filters=filters, ) if instances in (False, None, []): return instances if len(instances) == 1: instances[0].terminate() return True else: log.warning("Refusing to terminate multiple instances at once") return False def get_id( name=None, tags=None, region=None, key=None, keyid=None, profile=None, in_states=None, filters=None, ): """ Given instance properties, return the instance id if it exists. CLI Example: .. code-block:: bash salt myminion boto_ec2.get_id myinstance """ instance_ids = find_instances( name=name, tags=tags, region=region, key=key, keyid=keyid, profile=profile, in_states=in_states, filters=filters, ) if instance_ids: log.info("Instance ids: %s", " ".join(instance_ids)) if len(instance_ids) == 1: return instance_ids[0] else: raise CommandExecutionError( "Found more than one instance matching the criteria." ) else: log.warning("Could not find instance.") return None def get_tags(instance_id=None, keyid=None, key=None, profile=None, region=None): """ Given an instance_id, return a list of tags associated with that instance. returns (list) - list of tags as key/value pairs CLI Example: .. code-block:: bash salt myminion boto_ec2.get_tags instance_id """ tags = [] client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) result = client.get_all_tags(filters={"resource-id": instance_id}) if result: for tag in result: tags.append({tag.name: tag.value}) else: log.info("No tags found for instance_id %s", instance_id) return tags def exists( instance_id=None, name=None, tags=None, region=None, key=None, keyid=None, profile=None, in_states=None, filters=None, ): """ Given an instance id, check to see if the given instance id exists. Returns True if the given instance with the given id, name, or tags exists; otherwise, False is returned. CLI Example: .. code-block:: bash salt myminion boto_ec2.exists myinstance """ instances = find_instances( instance_id=instance_id, name=name, tags=tags, region=region, key=key, keyid=keyid, profile=profile, in_states=in_states, filters=filters, ) if instances: log.info("Instance exists.") return True else: log.warning("Instance does not exist.") return False def _to_blockdev_map(thing): """ Convert a string, or a json payload, or a dict in the right format, into a boto.ec2.blockdevicemapping.BlockDeviceMapping as needed by instance_present(). The following YAML is a direct representation of what is expected by the underlying boto EC2 code. YAML example: .. code-block:: yaml device-maps: /dev/sdb: ephemeral_name: ephemeral0 /dev/sdc: ephemeral_name: ephemeral1 /dev/sdd: ephemeral_name: ephemeral2 /dev/sde: ephemeral_name: ephemeral3 /dev/sdf: size: 20 volume_type: gp2 """ if not thing: return None if isinstance(thing, BlockDeviceMapping): return thing if isinstance(thing, str): thing = salt.utils.json.loads(thing) if not isinstance(thing, dict): log.error( "Can't convert '%s' of type %s to a " "boto.ec2.blockdevicemapping.BlockDeviceMapping", thing, type(thing), ) return None bdm = BlockDeviceMapping() for d, t in thing.items(): bdt = BlockDeviceType( ephemeral_name=t.get("ephemeral_name"), no_device=t.get("no_device", False), volume_id=t.get("volume_id"), snapshot_id=t.get("snapshot_id"), status=t.get("status"), attach_time=t.get("attach_time"), delete_on_termination=t.get("delete_on_termination", False), size=t.get("size"), volume_type=t.get("volume_type"), iops=t.get("iops"), encrypted=t.get("encrypted"), ) bdm[d] = bdt return bdm def run( image_id, name=None, tags=None, key_name=None, security_groups=None, user_data=None, instance_type="m1.small", placement=None, kernel_id=None, ramdisk_id=None, monitoring_enabled=None, vpc_id=None, vpc_name=None, subnet_id=None, subnet_name=None, private_ip_address=None, block_device_map=None, disable_api_termination=None, instance_initiated_shutdown_behavior=None, placement_group=None, client_token=None, security_group_ids=None, security_group_names=None, additional_info=None, tenancy=None, instance_profile_arn=None, instance_profile_name=None, ebs_optimized=None, network_interface_id=None, network_interface_name=None, region=None, key=None, keyid=None, profile=None, network_interfaces=None, ): # TODO: support multi-instance reservations """ Create and start an EC2 instance. Returns True if the instance was created; otherwise False. CLI Example: .. code-block:: bash salt myminion boto_ec2.run ami-b80c2b87 name=myinstance image_id (string) – The ID of the image to run. name (string) - The name of the instance. tags (dict of key: value pairs) - tags to apply to the instance. key_name (string) – The name of the key pair with which to launch instances. security_groups (list of strings) – The names of the EC2 classic security groups with which to associate instances user_data (string) – The Base64-encoded MIME user data to be made available to the instance(s) in this reservation. instance_type (string) – The type of instance to run. Note that some image types (e.g. hvm) only run on some instance types. placement (string) – The Availability Zone to launch the instance into. kernel_id (string) – The ID of the kernel with which to launch the instances. ramdisk_id (string) – The ID of the RAM disk with which to launch the instances. monitoring_enabled (bool) – Enable detailed CloudWatch monitoring on the instance. vpc_id (string) - ID of a VPC to bind the instance to. Exclusive with vpc_name. vpc_name (string) - Name of a VPC to bind the instance to. Exclusive with vpc_id. subnet_id (string) – The subnet ID within which to launch the instances for VPC. subnet_name (string) – The name of a subnet within which to launch the instances for VPC. private_ip_address (string) – If you’re using VPC, you can optionally use this parameter to assign the instance a specific available IP address from the subnet (e.g. 10.0.0.25). block_device_map (boto.ec2.blockdevicemapping.BlockDeviceMapping) – A BlockDeviceMapping data structure describing the EBS volumes associated with the Image. (string) - A string representation of a BlockDeviceMapping structure (dict) - A dict describing a BlockDeviceMapping structure YAML example: .. code-block:: yaml device-maps: /dev/sdb: ephemeral_name: ephemeral0 /dev/sdc: ephemeral_name: ephemeral1 /dev/sdd: ephemeral_name: ephemeral2 /dev/sde: ephemeral_name: ephemeral3 /dev/sdf: size: 20 volume_type: gp2 disable_api_termination (bool) – If True, the instances will be locked and will not be able to be terminated via the API. instance_initiated_shutdown_behavior (string) – Specifies whether the instance stops or terminates on instance-initiated shutdown. Valid values are: stop, terminate placement_group (string) – If specified, this is the name of the placement group in which the instance(s) will be launched. client_token (string) – Unique, case-sensitive identifier you provide to ensure idempotency of the request. Maximum 64 ASCII characters. security_group_ids (list of strings) – The ID(s) of the VPC security groups with which to associate instances. security_group_names (list of strings) – The name(s) of the VPC security groups with which to associate instances. additional_info (string) – Specifies additional information to make available to the instance(s). tenancy (string) – The tenancy of the instance you want to launch. An instance with a tenancy of ‘dedicated’ runs on single-tenant hardware and can only be launched into a VPC. Valid values are:”default” or “dedicated”. NOTE: To use dedicated tenancy you MUST specify a VPC subnet-ID as well. instance_profile_arn (string) – The Amazon resource name (ARN) of the IAM Instance Profile (IIP) to associate with the instances. instance_profile_name (string) – The name of the IAM Instance Profile (IIP) to associate with the instances. ebs_optimized (bool) – Whether the instance is optimized for EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal EBS I/O performance. This optimization isn’t available with all instance types. network_interfaces (boto.ec2.networkinterface.NetworkInterfaceCollection) – A NetworkInterfaceCollection data structure containing the ENI specifications for the instance. network_interface_id (string) - ID of the network interface to attach to the instance network_interface_name (string) - Name of the network interface to attach to the instance """ if all((subnet_id, subnet_name)): raise SaltInvocationError( "Only one of subnet_name or subnet_id may be provided." ) if subnet_name: r = __salt__["boto_vpc.get_resource_id"]( "subnet", subnet_name, region=region, key=key, keyid=keyid, profile=profile ) if "id" not in r: log.warning("Couldn't resolve subnet name %s.", subnet_name) return False subnet_id = r["id"] if all((security_group_ids, security_group_names)): raise SaltInvocationError( "Only one of security_group_ids or security_group_names may be provided." ) if security_group_names: security_group_ids = [] for sgn in security_group_names: r = __salt__["boto_secgroup.get_group_id"]( sgn, vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile, ) if not r: log.warning("Couldn't resolve security group name %s", sgn) return False security_group_ids += [r] network_interface_args = list( map( int, [ network_interface_id is not None, network_interface_name is not None, network_interfaces is not None, ], ) ) if sum(network_interface_args) > 1: raise SaltInvocationError( "Only one of network_interface_id, " "network_interface_name or " "network_interfaces may be provided." ) if network_interface_name: result = get_network_interface_id( network_interface_name, region=region, key=key, keyid=keyid, profile=profile ) network_interface_id = result["result"] if not network_interface_id: log.warning( "Given network_interface_name '%s' cannot be mapped to an " "network_interface_id", network_interface_name, ) if network_interface_id: interface = NetworkInterfaceSpecification( network_interface_id=network_interface_id, device_index=0 ) else: interface = NetworkInterfaceSpecification( subnet_id=subnet_id, groups=security_group_ids, device_index=0 ) if network_interfaces: interfaces_specs = [ NetworkInterfaceSpecification(**x) for x in network_interfaces ] interfaces = NetworkInterfaceCollection(*interfaces_specs) else: interfaces = NetworkInterfaceCollection(interface) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) reservation = conn.run_instances( image_id, key_name=key_name, security_groups=security_groups, user_data=user_data, instance_type=instance_type, placement=placement, kernel_id=kernel_id, ramdisk_id=ramdisk_id, monitoring_enabled=monitoring_enabled, private_ip_address=private_ip_address, block_device_map=_to_blockdev_map(block_device_map), disable_api_termination=disable_api_termination, instance_initiated_shutdown_behavior=instance_initiated_shutdown_behavior, placement_group=placement_group, client_token=client_token, additional_info=additional_info, tenancy=tenancy, instance_profile_arn=instance_profile_arn, instance_profile_name=instance_profile_name, ebs_optimized=ebs_optimized, network_interfaces=interfaces, ) if not reservation: log.warning("Instance could not be reserved") return False instance = reservation.instances[0] status = "pending" while status == "pending": time.sleep(5) status = instance.update() if status == "running": if name: instance.add_tag("Name", name) if tags: instance.add_tags(tags) return {"instance_id": instance.id} else: log.warning('Instance could not be started -- status is "%s"', status) def get_key(key_name, region=None, key=None, keyid=None, profile=None): """ Check to see if a key exists. Returns fingerprint and name if it does and False if it doesn't CLI Example: .. code-block:: bash salt myminion boto_ec2.get_key mykey """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: key = conn.get_key_pair(key_name) log.debug("the key to return is : %s", key) if key is None: return False return key.name, key.fingerprint except boto.exception.BotoServerError as e: log.debug(e) return False def create_key(key_name, save_path, region=None, key=None, keyid=None, profile=None): """ Creates a key and saves it to a given path. Returns the private key. CLI Example: .. code-block:: bash salt myminion boto_ec2.create_key mykey /root/ """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: key = conn.create_key_pair(key_name) log.debug("the key to return is : %s", key) key.save(save_path) return key.material except boto.exception.BotoServerError as e: log.debug(e) return False def import_key( key_name, public_key_material, region=None, key=None, keyid=None, profile=None ): """ Imports the public key from an RSA key pair that you created with a third-party tool. Supported formats: - OpenSSH public key format (e.g., the format in ~/.ssh/authorized_keys) - Base64 encoded DER format - SSH public key file format as specified in RFC4716 - DSA keys are not supported. Make sure your key generator is set up to create RSA keys. Supported lengths: 1024, 2048, and 4096. CLI Example: .. code-block:: bash salt myminion boto_ec2.import mykey publickey """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: key = conn.import_key_pair(key_name, public_key_material) log.debug("the key to return is : %s", key) return key.fingerprint except boto.exception.BotoServerError as e: log.debug(e) return False def delete_key(key_name, region=None, key=None, keyid=None, profile=None): """ Deletes a key. Always returns True CLI Example: .. code-block:: bash salt myminion boto_ec2.delete_key mykey """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: key = conn.delete_key_pair(key_name) log.debug("the key to return is : %s", key) return key except boto.exception.BotoServerError as e: log.debug(e) return False def get_keys( keynames=None, filters=None, region=None, key=None, keyid=None, profile=None ): """ Gets all keys or filters them by name and returns a list. keynames (list):: A list of the names of keypairs to retrieve. If not provided, all key pairs will be returned. filters (dict) :: Optional filters that can be used to limit the results returned. Filters are provided in the form of a dictionary consisting of filter names as the key and filter values as the value. The set of allowable filter names/values is dependent on the request being performed. Check the EC2 API guide for details. CLI Example: .. code-block:: bash salt myminion boto_ec2.get_keys """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: keys = conn.get_all_key_pairs(keynames, filters) log.debug("the key to return is : %s", keys) key_values = [] if keys: for key in keys: key_values.append(key.name) return key_values except boto.exception.BotoServerError as e: log.debug(e) return False def get_attribute( attribute, instance_name=None, instance_id=None, region=None, key=None, keyid=None, profile=None, filters=None, ): """ Get an EC2 instance attribute. CLI Example: .. code-block:: bash salt myminion boto_ec2.get_attribute sourceDestCheck instance_name=my_instance Available attributes: * instanceType * kernel * ramdisk * userData * disableApiTermination * instanceInitiatedShutdownBehavior * rootDeviceName * blockDeviceMapping * productCodes * sourceDestCheck * groupSet * ebsOptimized * sriovNetSupport """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) attribute_list = [ "instanceType", "kernel", "ramdisk", "userData", "disableApiTermination", "instanceInitiatedShutdownBehavior", "rootDeviceName", "blockDeviceMapping", "productCodes", "sourceDestCheck", "groupSet", "ebsOptimized", "sriovNetSupport", ] if not any((instance_name, instance_id)): raise SaltInvocationError( "At least one of the following must be specified: " "instance_name or instance_id." ) if instance_name and instance_id: raise SaltInvocationError( "Both instance_name and instance_id can not be specified in the same" " command." ) if attribute not in attribute_list: raise SaltInvocationError( "Attribute must be one of: {}.".format(attribute_list) ) try: if instance_name: instances = find_instances( name=instance_name, region=region, key=key, keyid=keyid, profile=profile, filters=filters, ) if len(instances) > 1: log.error("Found more than one EC2 instance matching the criteria.") return False elif not instances: log.error("Found no EC2 instance matching the criteria.") return False instance_id = instances[0] instance_attribute = conn.get_instance_attribute(instance_id, attribute) if not instance_attribute: return False return {attribute: instance_attribute[attribute]} except boto.exception.BotoServerError as exc: log.error(exc) return False def set_attribute( attribute, attribute_value, instance_name=None, instance_id=None, region=None, key=None, keyid=None, profile=None, filters=None, ): """ Set an EC2 instance attribute. Returns whether the operation succeeded or not. CLI Example: .. code-block:: bash salt myminion boto_ec2.set_attribute sourceDestCheck False instance_name=my_instance Available attributes: * instanceType * kernel * ramdisk * userData * disableApiTermination * instanceInitiatedShutdownBehavior * rootDeviceName * blockDeviceMapping * productCodes * sourceDestCheck * groupSet * ebsOptimized * sriovNetSupport """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) attribute_list = [ "instanceType", "kernel", "ramdisk", "userData", "disableApiTermination", "instanceInitiatedShutdownBehavior", "rootDeviceName", "blockDeviceMapping", "productCodes", "sourceDestCheck", "groupSet", "ebsOptimized", "sriovNetSupport", ] if not any((instance_name, instance_id)): raise SaltInvocationError( "At least one of the following must be specified: instance_name or" " instance_id." ) if instance_name and instance_id: raise SaltInvocationError( "Both instance_name and instance_id can not be specified in the same" " command." ) if attribute not in attribute_list: raise SaltInvocationError( "Attribute must be one of: {}.".format(attribute_list) ) try: if instance_name: instances = find_instances( name=instance_name, region=region, key=key, keyid=keyid, profile=profile, filters=filters, ) if len(instances) != 1: raise CommandExecutionError( "Found more than one EC2 instance matching the criteria." ) instance_id = instances[0] attribute = conn.modify_instance_attribute( instance_id, attribute, attribute_value ) if not attribute: return False return attribute except boto.exception.BotoServerError as exc: log.error(exc) return False def get_network_interface_id(name, region=None, key=None, keyid=None, profile=None): """ Get an Elastic Network Interface id from its name tag. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_ec2.get_network_interface_id name=my_eni """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: enis = conn.get_all_network_interfaces(filters={"tag:Name": name}) if not enis: r["error"] = {"message": "No ENIs found."} elif len(enis) > 1: r["error"] = {"message": "Name specified is tagged on multiple ENIs."} else: eni = enis[0] r["result"] = eni.id except boto.exception.EC2ResponseError as e: r["error"] = __utils__["boto.get_error"](e) return r def get_network_interface( name=None, network_interface_id=None, region=None, key=None, keyid=None, profile=None, ): """ Get an Elastic Network Interface. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_ec2.get_network_interface name=my_eni """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} result = _get_network_interface(conn, name, network_interface_id) if "error" in result: if result["error"]["message"] == "No ENIs found.": r["result"] = None return r return result eni = result["result"] r["result"] = _describe_network_interface(eni) return r def _get_network_interface(conn, name=None, network_interface_id=None): r = {} if not (name or network_interface_id): raise SaltInvocationError( "Either name or network_interface_id must be provided." ) try: if network_interface_id: enis = conn.get_all_network_interfaces([network_interface_id]) else: enis = conn.get_all_network_interfaces(filters={"tag:Name": name}) if not enis: r["error"] = {"message": "No ENIs found."} elif len(enis) > 1: r["error"] = {"message": "Name specified is tagged on multiple ENIs."} else: eni = enis[0] r["result"] = eni except boto.exception.EC2ResponseError as e: r["error"] = __utils__["boto.get_error"](e) return r def _describe_network_interface(eni): r = {} for attr in [ "status", "description", "availability_zone", "requesterId", "requester_managed", "mac_address", "private_ip_address", "vpc_id", "id", "source_dest_check", "owner_id", "tags", "subnet_id", "associationId", "publicDnsName", "owner_id", "ipOwnerId", "publicIp", "allocationId", ]: if hasattr(eni, attr): r[attr] = getattr(eni, attr) r["region"] = eni.region.name r["groups"] = [] for group in eni.groups: r["groups"].append({"name": group.name, "id": group.id}) r["private_ip_addresses"] = [] for address in eni.private_ip_addresses: r["private_ip_addresses"].append( { "private_ip_address": address.private_ip_address, "primary": address.primary, } ) r["attachment"] = {} for attr in [ "status", "attach_time", "device_index", "delete_on_termination", "instance_id", "instance_owner_id", "id", ]: if hasattr(eni.attachment, attr): r["attachment"][attr] = getattr(eni.attachment, attr) return r def create_network_interface( name, subnet_id=None, subnet_name=None, private_ip_address=None, description=None, groups=None, region=None, key=None, keyid=None, profile=None, ): """ Create an Elastic Network Interface. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_ec2.create_network_interface my_eni subnet-12345 description=my_eni groups=['my_group'] """ if not salt.utils.data.exactly_one((subnet_id, subnet_name)): raise SaltInvocationError( "One (but not both) of subnet_id or subnet_name must be provided." ) if subnet_name: resource = __salt__["boto_vpc.get_resource_id"]( "subnet", subnet_name, region=region, key=key, keyid=keyid, profile=profile ) if "id" not in resource: log.warning("Couldn't resolve subnet name %s.", subnet_name) return False subnet_id = resource["id"] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} result = _get_network_interface(conn, name) if "result" in result: r["error"] = {"message": "An ENI with this Name tag already exists."} return r vpc_id = __salt__["boto_vpc.get_subnet_association"]( [subnet_id], region=region, key=key, keyid=keyid, profile=profile ) vpc_id = vpc_id.get("vpc_id") if not vpc_id: msg = "subnet_id {} does not map to a valid vpc id.".format(subnet_id) r["error"] = {"message": msg} return r _groups = __salt__["boto_secgroup.convert_to_group_ids"]( groups, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile ) try: eni = conn.create_network_interface( subnet_id, private_ip_address=private_ip_address, description=description, groups=_groups, ) eni.add_tag("Name", name) except boto.exception.EC2ResponseError as e: r["error"] = __utils__["boto.get_error"](e) return r r["result"] = _describe_network_interface(eni) return r def delete_network_interface( name=None, network_interface_id=None, region=None, key=None, keyid=None, profile=None, ): """ Create an Elastic Network Interface. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_ec2.create_network_interface my_eni subnet-12345 description=my_eni groups=['my_group'] """ if not (name or network_interface_id): raise SaltInvocationError( "Either name or network_interface_id must be provided." ) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} result = _get_network_interface(conn, name, network_interface_id) if "error" in result: return result eni = result["result"] try: info = _describe_network_interface(eni) network_interface_id = info["id"] except KeyError: r["error"] = {"message": "ID not found for this network interface."} return r try: r["result"] = conn.delete_network_interface(network_interface_id) except boto.exception.EC2ResponseError as e: r["error"] = __utils__["boto.get_error"](e) return r def attach_network_interface( device_index, name=None, network_interface_id=None, instance_name=None, instance_id=None, region=None, key=None, keyid=None, profile=None, ): """ Attach an Elastic Network Interface. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_ec2.attach_network_interface my_eni instance_name=salt-master device_index=0 """ if not salt.utils.data.exactly_one((name, network_interface_id)): raise SaltInvocationError( "Exactly one (but not both) of 'name' or 'network_interface_id' " "must be provided." ) if not salt.utils.data.exactly_one((instance_name, instance_id)): raise SaltInvocationError( "Exactly one (but not both) of 'instance_name' or 'instance_id' " "must be provided." ) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} result = _get_network_interface(conn, name, network_interface_id) if "error" in result: return result eni = result["result"] try: info = _describe_network_interface(eni) network_interface_id = info["id"] except KeyError: r["error"] = {"message": "ID not found for this network interface."} return r if instance_name: try: instance_id = get_id( name=instance_name, region=region, key=key, keyid=keyid, profile=profile ) except boto.exception.BotoServerError as e: log.error(e) return False try: r["result"] = conn.attach_network_interface( network_interface_id, instance_id, device_index ) except boto.exception.EC2ResponseError as e: r["error"] = __utils__["boto.get_error"](e) return r def detach_network_interface( name=None, network_interface_id=None, attachment_id=None, force=False, region=None, key=None, keyid=None, profile=None, ): """ Detach an Elastic Network Interface. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_ec2.detach_network_interface my_eni """ if not (name or network_interface_id or attachment_id): raise SaltInvocationError( "Either name or network_interface_id or attachment_id must be provided." ) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} if not attachment_id: result = _get_network_interface(conn, name, network_interface_id) if "error" in result: return result eni = result["result"] info = _describe_network_interface(eni) try: attachment_id = info["attachment"]["id"] except KeyError: r["error"] = {"message": "Attachment id not found for this ENI."} return r try: r["result"] = conn.detach_network_interface(attachment_id, force) except boto.exception.EC2ResponseError as e: r["error"] = __utils__["boto.get_error"](e) return r def modify_network_interface_attribute( name=None, network_interface_id=None, attr=None, value=None, region=None, key=None, keyid=None, profile=None, ): """ Modify an attribute of an Elastic Network Interface. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_ec2.modify_network_interface_attribute my_eni attr=description value='example description' """ if not (name or network_interface_id): raise SaltInvocationError( "Either name or network_interface_id must be provided." ) if attr is None and value is None: raise SaltInvocationError("attr and value must be provided.") r = {} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) result = _get_network_interface(conn, name, network_interface_id) if "error" in result: return result eni = result["result"] info = _describe_network_interface(eni) network_interface_id = info["id"] # munge attr into what the API requires if attr == "groups": _attr = "groupSet" elif attr == "source_dest_check": _attr = "sourceDestCheck" elif attr == "delete_on_termination": _attr = "deleteOnTermination" else: _attr = attr _value = value if info.get("vpc_id") and _attr == "groupSet": _value = __salt__["boto_secgroup.convert_to_group_ids"]( value, vpc_id=info.get("vpc_id"), region=region, key=key, keyid=keyid, profile=profile, ) if not _value: r["error"] = { "message": "Security groups do not map to valid security group ids" } return r _attachment_id = None if _attr == "deleteOnTermination": try: _attachment_id = info["attachment"]["id"] except KeyError: r["error"] = { "message": ( "No attachment id found for this ENI. The ENI must" " be attached before delete_on_termination can be" " modified" ) } return r try: r["result"] = conn.modify_network_interface_attribute( network_interface_id, _attr, _value, attachment_id=_attachment_id ) except boto.exception.EC2ResponseError as e: r["error"] = __utils__["boto.get_error"](e) return r def get_all_volumes( volume_ids=None, filters=None, return_objs=False, region=None, key=None, keyid=None, profile=None, ): """ Get a list of all EBS volumes, optionally filtered by provided 'filters' param .. versionadded:: 2016.11.0 volume_ids (list) - Optional list of volume_ids. If provided, only the volumes associated with those in the list will be returned. filters (dict) - Additional constraints on which volumes to return. Valid filters are: - attachment.attach-time - The time stamp when the attachment initiated. - attachment.delete-on-termination - Whether the volume is deleted on instance termination. - attachment.device - The device name that is exposed to the instance (for example, /dev/sda1). - attachment.instance-id - The ID of the instance the volume is attached to. - attachment.status - The attachment state (attaching | attached | detaching | detached). - availability-zone - The Availability Zone in which the volume was created. - create-time - The time stamp when the volume was created. - encrypted - The encryption status of the volume. - size - The size of the volume, in GiB. - snapshot-id - The snapshot from which the volume was created. - status - The status of the volume (creating | available | in-use | deleting | deleted | error). - tag:key=value - The key/value combination of a tag assigned to the resource. - volume-id - The volume ID. - volume-type - The Amazon EBS volume type. This can be ``gp2`` for General Purpose SSD, ``io1`` for Provisioned IOPS SSD, ``st1`` for Throughput Optimized HDD, ``sc1`` for Cold HDD, or ``standard`` for Magnetic volumes. return_objs (bool) - Changes the return type from list of volume IDs to list of boto.ec2.volume.Volume objects returns (list) - A list of the requested values: Either the volume IDs or, if return_objs is ``True``, boto.ec2.volume.Volume objects. CLI Example: .. code-block:: bash salt-call boto_ec2.get_all_volumes filters='{"tag:Name": "myVolume01"}' """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_all_volumes(volume_ids=volume_ids, filters=filters) return ret if return_objs else [r.id for r in ret] except boto.exception.BotoServerError as e: log.error(e) return [] def set_volumes_tags( tag_maps, authoritative=False, dry_run=False, region=None, key=None, keyid=None, profile=None, ): """ .. versionadded:: 2016.11.0 tag_maps (list) List of dicts of filters and tags, where 'filters' is a dict suitable for passing to the 'filters' argument of get_all_volumes() above, and 'tags' is a dict of tags to be set on volumes (via create_tags/delete_tags) as matched by the given filters. The filter syntax is extended to permit passing either a list of volume_ids or an instance_name (with instance_name being the Name tag of the instance to which the desired volumes are mapped). Each mapping in the list is applied separately, so multiple sets of volumes can be all tagged differently with one call to this function. If filtering by instance Name, You may additionally limit the instances matched by passing in a list of desired instance states. The default set of states is ('pending', 'rebooting', 'running', 'stopping', 'stopped'). YAML example fragment: .. code-block:: yaml - filters: attachment.instance_id: i-abcdef12 tags: Name: dev-int-abcdef12.aws-foo.com - filters: attachment.device: /dev/sdf tags: ManagedSnapshots: true BillingGroup: bubba.hotep@aws-foo.com in_states: - stopped - terminated - filters: instance_name: prd-foo-01.aws-foo.com tags: Name: prd-foo-01.aws-foo.com BillingGroup: infra-team@aws-foo.com - filters: volume_ids: [ vol-12345689, vol-abcdef12 ] tags: BillingGroup: infra-team@aws-foo.com authoritative (bool) If true, any existing tags on the matched volumes, and not explicitly requested here, will be removed. dry_run (bool) If true, don't change anything, just return a dictionary describing any changes which would have been applied. returns (dict) A dict describing status and any changes. """ ret = {"success": True, "comment": "", "changes": {}} running_states = ("pending", "rebooting", "running", "stopping", "stopped") ### First creeate a dictionary mapping all changes for a given volume to its volume ID... tag_sets = {} for tm in tag_maps: filters = dict(tm.get("filters", {})) tags = dict(tm.get("tags", {})) args = { "return_objs": True, "region": region, "key": key, "keyid": keyid, "profile": profile, } new_filters = {} log.debug("got filters: %s", filters) instance_id = None in_states = tm.get("in_states", running_states) try: for k, v in filters.items(): if k == "volume_ids": args["volume_ids"] = v elif k == "instance_name": instance_id = get_id( name=v, in_states=in_states, region=region, key=key, keyid=keyid, profile=profile, ) if not instance_id: msg = "Couldn't resolve instance Name {} to an ID.".format(v) raise CommandExecutionError(msg) new_filters["attachment.instance_id"] = instance_id else: new_filters[k] = v except CommandExecutionError as e: log.warning(e) continue # Hmme, abort or do what we can...? Guess the latter for now. args["filters"] = new_filters volumes = get_all_volumes(**args) log.debug("got volume list: %s", volumes) for vol in volumes: tag_sets.setdefault( vol.id.replace("-", "_"), {"vol": vol, "tags": tags.copy()} )["tags"].update(tags.copy()) log.debug("tag_sets after munging: %s", tag_sets) ### ...then loop through all those volume->tag pairs and apply them. changes = {"old": {}, "new": {}} for volume in tag_sets.values(): vol, tags = volume["vol"], volume["tags"] log.debug( "current tags on vol.id %s: %s", vol.id, dict(getattr(vol, "tags", {})) ) curr = set(dict(getattr(vol, "tags", {})).keys()) log.debug("requested tags on vol.id %s: %s", vol.id, tags) req = set(tags.keys()) add = list(req - curr) update = [r for r in (req & curr) if vol.tags[r] != tags[r]] remove = list(curr - req) if add or update or (authoritative and remove): changes["old"][vol.id] = dict(getattr(vol, "tags", {})) changes["new"][vol.id] = tags else: log.debug("No changes needed for vol.id %s", vol.id) if add: d = {k: tags[k] for k in add} log.debug("New tags for vol.id %s: %s", vol.id, d) if update: d = {k: tags[k] for k in update} log.debug("Updated tags for vol.id %s: %s", vol.id, d) if not dry_run: if not create_tags( vol.id, tags, region=region, key=key, keyid=keyid, profile=profile ): ret["success"] = False ret["comment"] = "Failed to set tags on vol.id {}: {}".format( vol.id, tags ) return ret if authoritative: if remove: log.debug("Removed tags for vol.id %s: %s", vol.id, remove) if not delete_tags( vol.id, remove, region=region, key=key, keyid=keyid, profile=profile, ): ret["success"] = False ret[ "comment" ] = "Failed to remove tags on vol.id {}: {}".format( vol.id, remove ) return ret if changes["old"] or changes["new"]: ret["changes"].update(changes) return ret def get_all_tags(filters=None, region=None, key=None, keyid=None, profile=None): """ Describe all tags matching the filter criteria, or all tags in the account otherwise. .. versionadded:: 2018.3.0 filters (dict) - Additional constraints on which volumes to return. Note that valid filters vary extensively depending on the resource type. When in doubt, search first without a filter and then use the returned data to help fine-tune your search. You can generally garner the resource type from its ID (e.g. `vol-XXXXX` is a volume, `i-XXXXX` is an instance, etc. CLI Example: .. code-block:: bash salt-call boto_ec2.get_all_tags '{"tag:Name": myInstanceNameTag, resource-type: instance}' """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_all_tags(filters) tags = {} for t in ret: if t.res_id not in tags: tags[t.res_id] = {} tags[t.res_id][t.name] = t.value return tags except boto.exception.BotoServerError as e: log.error(e) return {} def create_tags(resource_ids, tags, region=None, key=None, keyid=None, profile=None): """ Create new metadata tags for the specified resource ids. .. versionadded:: 2016.11.0 resource_ids (string) or (list) – List of resource IDs. A plain string will be converted to a list of one element. tags (dict) – Dictionary of name/value pairs. To create only a tag name, pass '' as the value. returns (bool) - True on success, False on failure. CLI Example: .. code-block:: bash salt-call boto_ec2.create_tags vol-12345678 '{"Name": "myVolume01"}' """ if not isinstance(resource_ids, list): resource_ids = [resource_ids] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_tags(resource_ids, tags) return True except boto.exception.BotoServerError as e: log.error(e) return False def delete_tags(resource_ids, tags, region=None, key=None, keyid=None, profile=None): """ Delete metadata tags for the specified resource ids. .. versionadded:: 2016.11.0 resource_ids (string) or (list) – List of resource IDs. A plain string will be converted to a list of one element. tags (dict) or (list) – Either a dictionary containing name/value pairs or a list containing just tag names. If you pass in a dictionary, the values must match the actual tag values or the tag will not be deleted. If you pass in a value of None for the tag value, all tags with that name will be deleted. returns (bool) - True on success, False on failure. CLI Example: .. code-block:: bash salt-call boto_ec2.delete_tags vol-12345678 '{"Name": "myVolume01"}' salt-call boto_ec2.delete_tags vol-12345678 '["Name","MountPoint"]' """ if not isinstance(resource_ids, list): resource_ids = [resource_ids] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_tags(resource_ids, tags) return True except boto.exception.BotoServerError as e: log.error(e) return False def detach_volume( volume_id, instance_id=None, device=None, force=False, wait_for_detachement=False, region=None, key=None, keyid=None, profile=None, ): """ Detach an EBS volume from an EC2 instance. .. versionadded:: 2016.11.0 volume_id (string) – The ID of the EBS volume to be detached. instance_id (string) – The ID of the EC2 instance from which it will be detached. device (string) – The device on the instance through which the volume is exposted (e.g. /dev/sdh) force (bool) – Forces detachment if the previous detachment attempt did not occur cleanly. This option can lead to data loss or a corrupted file system. Use this option only as a last resort to detach a volume from a failed instance. The instance will not have an opportunity to flush file system caches nor file system meta data. If you use this option, you must perform file system check and repair procedures. wait_for_detachement (bool) - Whether or not to wait for volume detachement to complete. returns (bool) - True on success, False on failure. CLI Example: .. code-block:: bash salt-call boto_ec2.detach_volume vol-12345678 i-87654321 """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.detach_volume(volume_id, instance_id, device, force) if ( ret and wait_for_detachement and not _wait_for_volume_available(conn, volume_id) ): timeout_msg = 'Timed out waiting for the volume status "available".' log.error(timeout_msg) return False return ret except boto.exception.BotoServerError as e: log.error(e) return False def delete_volume( volume_id, instance_id=None, device=None, force=False, region=None, key=None, keyid=None, profile=None, ): """ Detach an EBS volume from an EC2 instance. .. versionadded:: 2016.11.0 volume_id (string) – The ID of the EBS volume to be deleted. force (bool) – Forces deletion even if the device has not yet been detached from its instance. returns (bool) - True on success, False on failure. CLI Example: .. code-block:: bash salt-call boto_ec2.delete_volume vol-12345678 """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_volume(volume_id) except boto.exception.BotoServerError as e: if not force: log.error(e) return False try: conn.detach_volume(volume_id, force=force) return conn.delete_volume(volume_id) except boto.exception.BotoServerError as e: log.error(e) return False def _wait_for_volume_available(conn, volume_id, retries=5, interval=5): i = 0 while True: i = i + 1 time.sleep(interval) vols = conn.get_all_volumes(volume_ids=[volume_id]) if len(vols) != 1: return False vol = vols[0] if vol.status == "available": return True if i > retries: return False def attach_volume( volume_id, instance_id, device, region=None, key=None, keyid=None, profile=None ): """ Attach an EBS volume to an EC2 instance. .. volume_id (string) – The ID of the EBS volume to be attached. instance_id (string) – The ID of the EC2 instance to attach the volume to. device (string) – The device on the instance through which the volume is exposed (e.g. /dev/sdh) returns (bool) - True on success, False on failure. CLI Example: .. code-block:: bash salt-call boto_ec2.attach_volume vol-12345678 i-87654321 /dev/sdh """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.attach_volume(volume_id, instance_id, device) except boto.exception.BotoServerError as error: log.error(error) return False def create_volume( zone_name, size=None, snapshot_id=None, volume_type=None, iops=None, encrypted=False, kms_key_id=None, wait_for_creation=False, region=None, key=None, keyid=None, profile=None, ): """ Create an EBS volume to an availability zone. .. zone_name (string) – The Availability zone name of the EBS volume to be created. size (int) – The size of the new volume, in GiB. If you're creating the volume from a snapshot and don't specify a volume size, the default is the snapshot size. snapshot_id (string) – The snapshot ID from which the new volume will be created. volume_type (string) - The type of the volume. Valid volume types for AWS can be found here: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html iops (int) - The provisioned IOPS you want to associate with this volume. encrypted (bool) - Specifies whether the volume should be encrypted. kms_key_id (string) - If encrypted is True, this KMS Key ID may be specified to encrypt volume with this key e.g.: arn:aws:kms:us-east-1:012345678910:key/abcd1234-a123-456a-a12b-a123b4cd56ef wait_for_creation (bool) - Whether or not to wait for volume creation to complete. returns (string) - created volume id on success, error message on failure. CLI Example: .. code-block:: bash salt-call boto_ec2.create_volume us-east-1a size=10 salt-call boto_ec2.create_volume us-east-1a snapshot_id=snap-0123abcd """ if size is None and snapshot_id is None: raise SaltInvocationError("Size must be provided if not created from snapshot.") ret = {} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: vol = conn.create_volume( size=size, zone=zone_name, snapshot=snapshot_id, volume_type=volume_type, iops=iops, encrypted=encrypted, kms_key_id=kms_key_id, ) if wait_for_creation and not _wait_for_volume_available(conn, vol.id): timeout_msg = 'Timed out waiting for the volume status "available".' log.error(timeout_msg) ret["error"] = timeout_msg else: ret["result"] = vol.id except boto.exception.BotoServerError as error: ret["error"] = __utils__["boto.get_error"](error) return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/boto_ec2.py
0.725357
0.162048
boto_ec2.py
pypi
import base64 import hashlib import hmac import io import salt.exceptions import salt.utils.files import salt.utils.hashutils import salt.utils.stringutils def digest(instr, checksum="md5"): """ Return a checksum digest for a string instr A string checksum : ``md5`` The hashing algorithm to use to generate checksums. Valid options: md5, sha256, sha512. CLI Example: .. code-block:: bash salt '*' hashutil.digest 'get salted' """ hashing_funcs = { "md5": __salt__["hashutil.md5_digest"], "sha256": __salt__["hashutil.sha256_digest"], "sha512": __salt__["hashutil.sha512_digest"], } hash_func = hashing_funcs.get(checksum) if hash_func is None: raise salt.exceptions.CommandExecutionError( "Hash func '{}' is not supported.".format(checksum) ) return hash_func(instr) def digest_file(infile, checksum="md5"): """ Return a checksum digest for a file infile A file path checksum : ``md5`` The hashing algorithm to use to generate checksums. Wraps the :py:func:`hashutil.digest <salt.modules.hashutil.digest>` execution function. CLI Example: .. code-block:: bash salt '*' hashutil.digest_file /path/to/file """ if not __salt__["file.file_exists"](infile): raise salt.exceptions.CommandExecutionError( "File path '{}' not found.".format(infile) ) with salt.utils.files.fopen(infile, "rb") as f: file_hash = __salt__["hashutil.digest"](f.read(), checksum) return file_hash def base64_b64encode(instr): """ Encode a string as base64 using the "modern" Python interface. Among other possible differences, the "modern" encoder does not include newline ('\\n') characters in the encoded output. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' hashutil.base64_b64encode 'get salted' """ return salt.utils.hashutils.base64_b64encode(instr) def base64_b64decode(instr): """ Decode a base64-encoded string using the "modern" Python interface .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' hashutil.base64_b64decode 'Z2V0IHNhbHRlZA==' """ return salt.utils.hashutils.base64_b64decode(instr) def base64_encodestring(instr): """ Encode a byte-like object as base64 using the "modern" Python interface. Among other possible differences, the "modern" encoder includes a newline ('\\n') character after every 76 characters and always at the end of the encoded byte-like object. .. versionadded:: 3000 CLI Example: .. code-block:: bash salt '*' hashutil.base64_encodestring 'get salted' """ return salt.utils.hashutils.base64_encodestring(instr) def base64_encodefile(fname): """ Read a file from the file system and return as a base64 encoded string .. versionadded:: 2016.3.0 Pillar example: .. code-block:: yaml path: to: data: | {{ salt.hashutil.base64_encodefile('/path/to/binary_file') | indent(6) }} The :py:func:`file.decode <salt.states.file.decode>` state function can be used to decode this data and write it to disk. CLI Example: .. code-block:: bash salt '*' hashutil.base64_encodefile /path/to/binary_file """ encoded_f = io.BytesIO() with salt.utils.files.fopen(fname, "rb") as f: base64.encode(f, encoded_f) encoded_f.seek(0) return salt.utils.stringutils.to_str(encoded_f.read()) def base64_decodestring(instr): """ Decode a base64-encoded byte-like object using the "modern" Python interface .. versionadded:: 3000 CLI Example: .. code-block:: bash salt '*' hashutil.base64_decodestring instr='Z2V0IHNhbHRlZAo=' """ return salt.utils.hashutils.base64_decodestring(instr) def base64_decodefile(instr, outfile): r""" Decode a base64-encoded string and write the result to a file .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' hashutil.base64_decodefile instr='Z2V0IHNhbHRlZAo=' outfile='/path/to/binary_file' """ encoded_f = io.StringIO(instr) with salt.utils.files.fopen(outfile, "wb") as f: base64.decode(encoded_f, f) return True def md5_digest(instr): """ Generate an md5 hash of a given string .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' hashutil.md5_digest 'get salted' """ return salt.utils.hashutils.md5_digest(instr) def sha256_digest(instr): """ Generate an sha256 hash of a given string .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' hashutil.sha256_digest 'get salted' """ return salt.utils.hashutils.sha256_digest(instr) def sha512_digest(instr): """ Generate an sha512 hash of a given string .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' hashutil.sha512_digest 'get salted' """ return salt.utils.hashutils.sha512_digest(instr) def hmac_signature(string, shared_secret, challenge_hmac): """ Verify a challenging hmac signature against a string / shared-secret .. versionadded:: 2014.7.0 Returns a boolean if the verification succeeded or failed. CLI Example: .. code-block:: bash salt '*' hashutil.hmac_signature 'get salted' 'shared secret' 'eBWf9bstXg+NiP5AOwppB5HMvZiYMPzEM9W5YMm/AmQ=' """ return salt.utils.hashutils.hmac_signature(string, shared_secret, challenge_hmac) def hmac_compute(string, shared_secret): """ .. versionadded:: 3000 Compute a HMAC SHA256 digest using a string and secret. CLI Example: .. code-block:: bash salt '*' hashutil.hmac_compute 'get salted' 'shared secret' """ return salt.utils.hashutils.hmac_compute(string, shared_secret) def github_signature(string, shared_secret, challenge_hmac): """ Verify a challenging hmac signature against a string / shared-secret for github webhooks. .. versionadded:: 2017.7.0 Returns a boolean if the verification succeeded or failed. CLI Example: .. code-block:: bash salt '*' hashutil.github_signature '{"ref":....} ' 'shared secret' 'sha1=bc6550fc290acf5b42283fa8deaf55cea0f8c206' """ msg = string key = shared_secret hashtype, challenge = challenge_hmac.split("=") if isinstance(msg, str): msg = salt.utils.stringutils.to_bytes(msg) if isinstance(key, str): key = salt.utils.stringutils.to_bytes(key) hmac_hash = hmac.new(key, msg, getattr(hashlib, hashtype)) return hmac_hash.hexdigest() == challenge
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/hashutil.py
0.861626
0.354461
hashutil.py
pypi
import re import salt.utils.path def __virtual__(): """ loads the module, if only sysbench is installed """ # finding the path of the binary if salt.utils.path.which("sysbench"): return "sysbench" return ( False, "The sysbench execution module failed to load: the sysbench binary is not in" " the path.", ) def _parser(result): """ parses the output into a dictionary """ # regexes to match _total_time = re.compile(r"total time:\s*(\d*.\d*s)") _total_execution = re.compile(r"event execution:\s*(\d*.\d*s?)") _min_response_time = re.compile(r"min:\s*(\d*.\d*ms)") _max_response_time = re.compile(r"max:\s*(\d*.\d*ms)") _avg_response_time = re.compile(r"avg:\s*(\d*.\d*ms)") _per_response_time = re.compile(r"95 percentile:\s*(\d*.\d*ms)") # extracting data total_time = re.search(_total_time, result).group(1) total_execution = re.search(_total_execution, result).group(1) min_response_time = re.search(_min_response_time, result).group(1) max_response_time = re.search(_max_response_time, result).group(1) avg_response_time = re.search(_avg_response_time, result).group(1) per_response_time = re.search(_per_response_time, result) if per_response_time is not None: per_response_time = per_response_time.group(1) # returning the data as dictionary return { "total time": total_time, "total execution time": total_execution, "minimum response time": min_response_time, "maximum response time": max_response_time, "average response time": avg_response_time, "95 percentile": per_response_time, } def cpu(): """ Tests for the CPU performance of minions. CLI Examples: .. code-block:: bash salt '*' sysbench.cpu """ # Test data max_primes = [500, 1000, 2500, 5000] # Initializing the test variables test_command = "sysbench --test=cpu --cpu-max-prime={0} run" result = None ret_val = {} # Test beings! for primes in max_primes: key = "Prime numbers limit: {}".format(primes) run_command = test_command.format(primes) result = __salt__["cmd.run"](run_command) ret_val[key] = _parser(result) return ret_val def threads(): """ This tests the performance of the processor's scheduler CLI Example: .. code-block:: bash salt '*' sysbench.threads """ # Test data thread_yields = [100, 200, 500, 1000] thread_locks = [2, 4, 8, 16] # Initializing the test variables test_command = "sysbench --num-threads=64 --test=threads " test_command += "--thread-yields={0} --thread-locks={1} run " result = None ret_val = {} # Test begins! for yields, locks in zip(thread_yields, thread_locks): key = "Yields: {} Locks: {}".format(yields, locks) run_command = test_command.format(yields, locks) result = __salt__["cmd.run"](run_command) ret_val[key] = _parser(result) return ret_val def mutex(): """ Tests the implementation of mutex CLI Examples: .. code-block:: bash salt '*' sysbench.mutex """ # Test options and the values they take # --mutex-num = [50,500,1000] # --mutex-locks = [10000,25000,50000] # --mutex-loops = [2500,5000,10000] # Test data (Orthogonal test cases) mutex_num = [50, 50, 50, 500, 500, 500, 1000, 1000, 1000] locks = [10000, 25000, 50000, 10000, 25000, 50000, 10000, 25000, 50000] mutex_locks = [] mutex_locks.extend(locks) mutex_loops = [2500, 5000, 10000, 10000, 2500, 5000, 5000, 10000, 2500] # Initializing the test variables test_command = "sysbench --num-threads=250 --test=mutex " test_command += "--mutex-num={0} --mutex-locks={1} --mutex-loops={2} run " result = None ret_val = {} # Test begins! for num, locks, loops in zip(mutex_num, mutex_locks, mutex_loops): key = "Mutex: {} Locks: {} Loops: {}".format(num, locks, loops) run_command = test_command.format(num, locks, loops) result = __salt__["cmd.run"](run_command) ret_val[key] = _parser(result) return ret_val def memory(): """ This tests the memory for read and write operations. CLI Examples: .. code-block:: bash salt '*' sysbench.memory """ # test defaults # --memory-block-size = 10M # --memory-total-size = 1G # We test memory read / write against global / local scope of memory # Test data memory_oper = ["read", "write"] memory_scope = ["local", "global"] # Initializing the test variables test_command = "sysbench --num-threads=64 --test=memory " test_command += "--memory-oper={0} --memory-scope={1} " test_command += "--memory-block-size=1K --memory-total-size=32G run " result = None ret_val = {} # Test begins! for oper in memory_oper: for scope in memory_scope: key = "Operation: {} Scope: {}".format(oper, scope) run_command = test_command.format(oper, scope) result = __salt__["cmd.run"](run_command) ret_val[key] = _parser(result) return ret_val def fileio(): """ This tests for the file read and write operations Various modes of operations are * sequential write * sequential rewrite * sequential read * random read * random write * random read and write The test works with 32 files with each file being 1Gb in size The test consumes a lot of time. Be patient! CLI Examples: .. code-block:: bash salt '*' sysbench.fileio """ # Test data test_modes = ["seqwr", "seqrewr", "seqrd", "rndrd", "rndwr", "rndrw"] # Initializing the required variables test_command = "sysbench --num-threads=16 --test=fileio " test_command += "--file-num=32 --file-total-size=1G --file-test-mode={0} " result = None ret_val = {} # Test begins! for mode in test_modes: key = "Mode: {}".format(mode) # Prepare phase run_command = (test_command + "prepare").format(mode) __salt__["cmd.run"](run_command) # Test phase run_command = (test_command + "run").format(mode) result = __salt__["cmd.run"](run_command) ret_val[key] = _parser(result) # Clean up phase run_command = (test_command + "cleanup").format(mode) __salt__["cmd.run"](run_command) return ret_val def ping(): return True
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/sysbench.py
0.525612
0.393968
sysbench.py
pypi
import salt.utils.mac_utils import salt.utils.platform from salt.exceptions import SaltInvocationError __virtualname__ = "power" def __virtual__(): """ Only for macOS """ if not salt.utils.platform.is_darwin(): return ( False, "The mac_power module could not be loaded: " "module only works on macOS systems.", ) return __virtualname__ def _validate_sleep(minutes): """ Helper function that validates the minutes parameter. Can be any number between 1 and 180. Can also be the string values "Never" and "Off". Because "On" and "Off" get converted to boolean values on the command line it will error if "On" is passed Returns: The value to be passed to the command """ # Must be a value between 1 and 180 or Never/Off if isinstance(minutes, str): if minutes.lower() in ["never", "off"]: return "Never" else: msg = ( "Invalid String Value for Minutes.\n" 'String values must be "Never" or "Off".\n' "Passed: {}".format(minutes) ) raise SaltInvocationError(msg) elif isinstance(minutes, bool): if minutes: msg = ( "Invalid Boolean Value for Minutes.\n" 'Boolean value "On" or "True" is not allowed.\n' 'Salt CLI converts "On" to boolean True.\n' "Passed: {}".format(minutes) ) raise SaltInvocationError(msg) else: return "Never" elif isinstance(minutes, int): if minutes in range(1, 181): return minutes else: msg = ( "Invalid Integer Value for Minutes.\n" "Integer values must be between 1 and 180.\n" "Passed: {}".format(minutes) ) raise SaltInvocationError(msg) else: msg = "Unknown Variable Type Passed for Minutes.\nPassed: {}".format(minutes) raise SaltInvocationError(msg) def get_sleep(): """ Displays the amount of idle time until the machine sleeps. Settings for Computer, Display, and Hard Disk are displayed. :return: A dictionary containing the sleep status for Computer, Display, and Hard Disk :rtype: dict CLI Example: .. code-block:: bash salt '*' power.get_sleep """ return { "Computer": get_computer_sleep(), "Display": get_display_sleep(), "Hard Disk": get_harddisk_sleep(), } def set_sleep(minutes): """ Sets the amount of idle time until the machine sleeps. Sets the same value for Computer, Display, and Hard Disk. Pass "Never" or "Off" for computers that should never sleep. :param minutes: Can be an integer between 1 and 180 or "Never" or "Off" :ptype: int, str :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' power.set_sleep 120 salt '*' power.set_sleep never """ value = _validate_sleep(minutes) cmd = "systemsetup -setsleep {}".format(value) salt.utils.mac_utils.execute_return_success(cmd) state = [] for check in (get_computer_sleep, get_display_sleep, get_harddisk_sleep): state.append( salt.utils.mac_utils.confirm_updated( value, check, ) ) return all(state) def get_computer_sleep(): """ Display the amount of idle time until the computer sleeps. :return: A string representing the sleep settings for the computer :rtype: str CLI Example: .. code-block:: bash salt '*' power.get_computer_sleep """ ret = salt.utils.mac_utils.execute_return_result("systemsetup -getcomputersleep") return salt.utils.mac_utils.parse_return(ret) def set_computer_sleep(minutes): """ Set the amount of idle time until the computer sleeps. Pass "Never" of "Off" to never sleep. :param minutes: Can be an integer between 1 and 180 or "Never" or "Off" :ptype: int, str :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' power.set_computer_sleep 120 salt '*' power.set_computer_sleep off """ value = _validate_sleep(minutes) cmd = "systemsetup -setcomputersleep {}".format(value) salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.confirm_updated( str(value), get_computer_sleep, ) def get_display_sleep(): """ Display the amount of idle time until the display sleeps. :return: A string representing the sleep settings for the displey :rtype: str CLI Example: .. code-block:: bash salt '*' power.get_display_sleep """ ret = salt.utils.mac_utils.execute_return_result("systemsetup -getdisplaysleep") return salt.utils.mac_utils.parse_return(ret) def set_display_sleep(minutes): """ Set the amount of idle time until the display sleeps. Pass "Never" of "Off" to never sleep. :param minutes: Can be an integer between 1 and 180 or "Never" or "Off" :ptype: int, str :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' power.set_display_sleep 120 salt '*' power.set_display_sleep off """ value = _validate_sleep(minutes) cmd = "systemsetup -setdisplaysleep {}".format(value) salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.confirm_updated( str(value), get_display_sleep, ) def get_harddisk_sleep(): """ Display the amount of idle time until the hard disk sleeps. :return: A string representing the sleep settings for the hard disk :rtype: str CLI Example: .. code-block:: bash salt '*' power.get_harddisk_sleep """ ret = salt.utils.mac_utils.execute_return_result("systemsetup -getharddisksleep") return salt.utils.mac_utils.parse_return(ret) def set_harddisk_sleep(minutes): """ Set the amount of idle time until the harddisk sleeps. Pass "Never" of "Off" to never sleep. :param minutes: Can be an integer between 1 and 180 or "Never" or "Off" :ptype: int, str :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' power.set_harddisk_sleep 120 salt '*' power.set_harddisk_sleep off """ value = _validate_sleep(minutes) cmd = "systemsetup -setharddisksleep {}".format(value) salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.confirm_updated( str(value), get_harddisk_sleep, ) def get_wake_on_modem(): """ Displays whether 'wake on modem' is on or off if supported :return: A string value representing the "wake on modem" settings :rtype: str CLI Example: .. code-block:: bash salt '*' power.get_wake_on_modem """ ret = salt.utils.mac_utils.execute_return_result("systemsetup -getwakeonmodem") return ( salt.utils.mac_utils.validate_enabled(salt.utils.mac_utils.parse_return(ret)) == "on" ) def set_wake_on_modem(enabled): """ Set whether or not the computer will wake from sleep when modem activity is detected. :param bool enabled: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' power.set_wake_on_modem True """ state = salt.utils.mac_utils.validate_enabled(enabled) cmd = "systemsetup -setwakeonmodem {}".format(state) salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.confirm_updated( state, get_wake_on_modem, ) def get_wake_on_network(): """ Displays whether 'wake on network' is on or off if supported :return: A string value representing the "wake on network" settings :rtype: string CLI Example: .. code-block:: bash salt '*' power.get_wake_on_network """ ret = salt.utils.mac_utils.execute_return_result( "systemsetup -getwakeonnetworkaccess" ) return ( salt.utils.mac_utils.validate_enabled(salt.utils.mac_utils.parse_return(ret)) == "on" ) def set_wake_on_network(enabled): """ Set whether or not the computer will wake from sleep when network activity is detected. :param bool enabled: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' power.set_wake_on_network True """ state = salt.utils.mac_utils.validate_enabled(enabled) cmd = "systemsetup -setwakeonnetworkaccess {}".format(state) salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.confirm_updated( state, get_wake_on_network, ) def get_restart_power_failure(): """ Displays whether 'restart on power failure' is on or off if supported :return: A string value representing the "restart on power failure" settings :rtype: string CLI Example: .. code-block:: bash salt '*' power.get_restart_power_failure """ ret = salt.utils.mac_utils.execute_return_result( "systemsetup -getrestartpowerfailure" ) return ( salt.utils.mac_utils.validate_enabled(salt.utils.mac_utils.parse_return(ret)) == "on" ) def set_restart_power_failure(enabled): """ Set whether or not the computer will automatically restart after a power failure. :param bool enabled: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' power.set_restart_power_failure True """ state = salt.utils.mac_utils.validate_enabled(enabled) cmd = "systemsetup -setrestartpowerfailure {}".format(state) salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.confirm_updated( state, get_restart_power_failure, ) def get_restart_freeze(): """ Displays whether 'restart on freeze' is on or off if supported :return: A string value representing the "restart on freeze" settings :rtype: string CLI Example: .. code-block:: bash salt '*' power.get_restart_freeze """ ret = salt.utils.mac_utils.execute_return_result("systemsetup -getrestartfreeze") return ( salt.utils.mac_utils.validate_enabled(salt.utils.mac_utils.parse_return(ret)) == "on" ) def set_restart_freeze(enabled): """ Specifies whether the server restarts automatically after a system freeze. This setting doesn't seem to be editable. The command completes successfully but the setting isn't actually updated. This is probably a macOS. The functions remains in case they ever fix the bug. :param bool enabled: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' power.set_restart_freeze True """ state = salt.utils.mac_utils.validate_enabled(enabled) cmd = "systemsetup -setrestartfreeze {}".format(state) salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.confirm_updated(state, get_restart_freeze, True) def get_sleep_on_power_button(): """ Displays whether 'allow power button to sleep computer' is on or off if supported :return: A string value representing the "allow power button to sleep computer" settings :rtype: string CLI Example: .. code-block:: bash salt '*' power.get_sleep_on_power_button """ ret = salt.utils.mac_utils.execute_return_result( "systemsetup -getallowpowerbuttontosleepcomputer" ) return ( salt.utils.mac_utils.validate_enabled(salt.utils.mac_utils.parse_return(ret)) == "on" ) def set_sleep_on_power_button(enabled): """ Set whether or not the power button can sleep the computer. :param bool enabled: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' power.set_sleep_on_power_button True """ state = salt.utils.mac_utils.validate_enabled(enabled) cmd = "systemsetup -setallowpowerbuttontosleepcomputer {}".format(state) salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.confirm_updated( state, get_sleep_on_power_button, )
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/mac_power.py
0.728459
0.297763
mac_power.py
pypi
import logging from functools import wraps import salt.utils.azurearm # Azure libs HAS_LIBS = False try: import azure.mgmt.dns.models # pylint: disable=unused-import from msrest.exceptions import SerializationError from msrestazure.azure_exceptions import CloudError HAS_LIBS = True except ImportError: pass __virtualname__ = "azurearm_dns" log = logging.getLogger(__name__) def __virtual__(): if not HAS_LIBS: return ( False, "The following dependencies are required to use the AzureARM modules: " "Microsoft Azure SDK for Python >= 2.0rc6, " "MS REST Azure (msrestazure) >= 0.4", ) return __virtualname__ def _deprecation_message(function): """ Decorator wrapper to warn about azurearm deprecation """ @wraps(function) def wrapped(*args, **kwargs): salt.utils.versions.warn_until( "Chlorine", "The 'azurearm' functionality in Salt has been deprecated and its " "functionality will be removed in version 3007 in favor of the " "saltext.azurerm Salt Extension. " "(https://github.com/salt-extensions/saltext-azurerm)", category=FutureWarning, ) ret = function(*args, **salt.utils.args.clean_kwargs(**kwargs)) return ret return wrapped @_deprecation_message def record_set_create_or_update(name, zone_name, resource_group, record_type, **kwargs): """ .. versionadded:: 3000 Creates or updates a record set within a DNS zone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA can be updated but not created (they are created when the DNS zone is created). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_create_or_update myhost myzone testgroup A arecords='[{ipv4_address: 10.0.0.1}]' ttl=300 """ dnsconn = __utils__["azurearm.get_client"]("dns", **kwargs) try: record_set_model = __utils__["azurearm.create_object_model"]( "dns", "RecordSet", **kwargs ) except TypeError as exc: result = {"error": "The object model could not be built. ({})".format(str(exc))} return result try: record_set = dnsconn.record_sets.create_or_update( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, parameters=record_set_model, if_match=kwargs.get("if_match"), if_none_match=kwargs.get("if_none_match"), ) result = record_set.as_dict() except CloudError as exc: __utils__["azurearm.log_cloud_error"]("dns", str(exc), **kwargs) result = {"error": str(exc)} except SerializationError as exc: result = { "error": "The object model could not be parsed. ({})".format(str(exc)) } return result @_deprecation_message def record_set_delete(name, zone_name, resource_group, record_type, **kwargs): """ .. versionadded:: 3000 Deletes a record set from a DNS zone. This operation cannot be undone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA cannot be deleted (they are deleted when the DNS zone is deleted). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_delete myhost myzone testgroup A """ result = False dnsconn = __utils__["azurearm.get_client"]("dns", **kwargs) try: record_set = dnsconn.record_sets.delete( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, if_match=kwargs.get("if_match"), ) result = True except CloudError as exc: __utils__["azurearm.log_cloud_error"]("dns", str(exc), **kwargs) return result @_deprecation_message def record_set_get(name, zone_name, resource_group, record_type, **kwargs): """ .. versionadded:: 3000 Get a dictionary representing a record set's properties. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_get '@' myzone testgroup SOA """ dnsconn = __utils__["azurearm.get_client"]("dns", **kwargs) try: record_set = dnsconn.record_sets.get( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, ) result = record_set.as_dict() except CloudError as exc: __utils__["azurearm.log_cloud_error"]("dns", str(exc), **kwargs) result = {"error": str(exc)} return result @_deprecation_message def record_sets_list_by_type( zone_name, resource_group, record_type, top=None, recordsetnamesuffix=None, **kwargs ): """ .. versionadded:: 3000 Lists the record sets of a specified type in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of record sets to enumerate. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_type myzone testgroup SOA """ result = {} dnsconn = __utils__["azurearm.get_client"]("dns", **kwargs) try: record_sets = __utils__["azurearm.paged_object_to_list"]( dnsconn.record_sets.list_by_type( zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, top=top, recordsetnamesuffix=recordsetnamesuffix, ) ) for record_set in record_sets: result[record_set["name"]] = record_set except CloudError as exc: __utils__["azurearm.log_cloud_error"]("dns", str(exc), **kwargs) result = {"error": str(exc)} return result @_deprecation_message def record_sets_list_by_dns_zone( zone_name, resource_group, top=None, recordsetnamesuffix=None, **kwargs ): """ .. versionadded:: 3000 Lists all record sets in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_dns_zone myzone testgroup """ result = {} dnsconn = __utils__["azurearm.get_client"]("dns", **kwargs) try: record_sets = __utils__["azurearm.paged_object_to_list"]( dnsconn.record_sets.list_by_dns_zone( zone_name=zone_name, resource_group_name=resource_group, top=top, recordsetnamesuffix=recordsetnamesuffix, ) ) for record_set in record_sets: result[record_set["name"]] = record_set except CloudError as exc: __utils__["azurearm.log_cloud_error"]("dns", str(exc), **kwargs) result = {"error": str(exc)} return result @_deprecation_message def zone_create_or_update(name, resource_group, **kwargs): """ .. versionadded:: 3000 Creates or updates a DNS zone. Does not modify DNS records within the zone. :param name: The name of the DNS zone to create (without a terminating dot). :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_create_or_update myzone testgroup """ # DNS zones are global objects kwargs["location"] = "global" dnsconn = __utils__["azurearm.get_client"]("dns", **kwargs) # Convert list of ID strings to list of dictionaries with id key. if isinstance(kwargs.get("registration_virtual_networks"), list): kwargs["registration_virtual_networks"] = [ {"id": vnet} for vnet in kwargs["registration_virtual_networks"] ] if isinstance(kwargs.get("resolution_virtual_networks"), list): kwargs["resolution_virtual_networks"] = [ {"id": vnet} for vnet in kwargs["resolution_virtual_networks"] ] try: zone_model = __utils__["azurearm.create_object_model"]("dns", "Zone", **kwargs) except TypeError as exc: result = {"error": "The object model could not be built. ({})".format(str(exc))} return result try: zone = dnsconn.zones.create_or_update( zone_name=name, resource_group_name=resource_group, parameters=zone_model, if_match=kwargs.get("if_match"), if_none_match=kwargs.get("if_none_match"), ) result = zone.as_dict() except CloudError as exc: __utils__["azurearm.log_cloud_error"]("dns", str(exc), **kwargs) result = {"error": str(exc)} except SerializationError as exc: result = { "error": "The object model could not be parsed. ({})".format(str(exc)) } return result @_deprecation_message def zone_delete(name, resource_group, **kwargs): """ .. versionadded:: 3000 Delete a DNS zone within a resource group. :param name: The name of the DNS zone to delete. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_delete myzone testgroup """ result = False dnsconn = __utils__["azurearm.get_client"]("dns", **kwargs) try: zone = dnsconn.zones.delete( zone_name=name, resource_group_name=resource_group, if_match=kwargs.get("if_match"), ) zone.wait() result = True except CloudError as exc: __utils__["azurearm.log_cloud_error"]("dns", str(exc), **kwargs) return result @_deprecation_message def zone_get(name, resource_group, **kwargs): """ .. versionadded:: 3000 Get a dictionary representing a DNS zone's properties, but not the record sets within the zone. :param name: The DNS zone to get. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_get myzone testgroup """ dnsconn = __utils__["azurearm.get_client"]("dns", **kwargs) try: zone = dnsconn.zones.get(zone_name=name, resource_group_name=resource_group) result = zone.as_dict() except CloudError as exc: __utils__["azurearm.log_cloud_error"]("dns", str(exc), **kwargs) result = {"error": str(exc)} return result @_deprecation_message def zones_list_by_resource_group(resource_group, top=None, **kwargs): """ .. versionadded:: 3000 Lists the DNS zones in a resource group. :param resource_group: The name of the resource group. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list_by_resource_group testgroup """ result = {} dnsconn = __utils__["azurearm.get_client"]("dns", **kwargs) try: zones = __utils__["azurearm.paged_object_to_list"]( dnsconn.zones.list_by_resource_group( resource_group_name=resource_group, top=top ) ) for zone in zones: result[zone["name"]] = zone except CloudError as exc: __utils__["azurearm.log_cloud_error"]("dns", str(exc), **kwargs) result = {"error": str(exc)} return result @_deprecation_message def zones_list(top=None, **kwargs): """ .. versionadded:: 3000 Lists the DNS zones in all resource groups in a subscription. :param top: The maximum number of DNS zones to return. If not specified, eturns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list """ result = {} dnsconn = __utils__["azurearm.get_client"]("dns", **kwargs) try: zones = __utils__["azurearm.paged_object_to_list"](dnsconn.zones.list(top=top)) for zone in zones: result[zone["name"]] = zone except CloudError as exc: __utils__["azurearm.log_cloud_error"]("dns", str(exc), **kwargs) result = {"error": str(exc)} return result
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/azurearm_dns.py
0.759225
0.153486
azurearm_dns.py
pypi
import logging import os import re import salt.utils.json import salt.utils.path import salt.utils.stringutils from salt.exceptions import SaltInvocationError _DEFAULT_CONFIG_PATH = "/etc/aptly.conf" log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = "aptly" def __virtual__(): """ Only works on systems with the aptly binary in the system path. """ if salt.utils.path.which("aptly"): return __virtualname__ return (False, "The aptly binaries required cannot be found or are not installed.") def _cmd_run(cmd): """ Run the aptly command. :return: The string output of the command. :rtype: str """ cmd.insert(0, "aptly") cmd_ret = __salt__["cmd.run_all"](cmd, ignore_retcode=True) if cmd_ret["retcode"] != 0: log.debug("Unable to execute command: %s\nError: %s", cmd, cmd_ret["stderr"]) return cmd_ret["stdout"] def _format_repo_args( comment=None, component=None, distribution=None, uploaders_file=None, saltenv="base" ): """ Format the common arguments for creating or editing a repository. :param str comment: The description of the repository. :param str component: The default component to use when publishing. :param str distribution: The default distribution to use when publishing. :param str uploaders_file: The repository upload restrictions config. :param str saltenv: The environment the file resides in. :return: A list of the arguments formatted as aptly arguments. :rtype: list """ ret = list() cached_uploaders_path = None settings = { "comment": comment, "component": component, "distribution": distribution, } if uploaders_file: cached_uploaders_path = __salt__["cp.cache_file"](uploaders_file, saltenv) if not cached_uploaders_path: log.error("Unable to get cached copy of file: %s", uploaders_file) return False for setting in settings: if settings[setting] is not None: ret.append("-{}={}".format(setting, settings[setting])) if cached_uploaders_path: ret.append("-uploaders-file={}".format(cached_uploaders_path)) return ret def _validate_config(config_path): """ Validate that the configuration file exists and is readable. :param str config_path: The path to the configuration file for the aptly instance. :return: None :rtype: None """ log.debug("Checking configuration file: %s", config_path) if not os.path.isfile(config_path): message = "Unable to get configuration file: {}".format(config_path) log.error(message) raise SaltInvocationError(message) def get_config(config_path=_DEFAULT_CONFIG_PATH): """ Get the configuration data. :param str config_path: The path to the configuration file for the aptly instance. :return: A dictionary containing the configuration data. :rtype: dict CLI Example: .. code-block:: bash salt '*' aptly.get_config """ _validate_config(config_path) cmd = ["config", "show", "-config={}".format(config_path)] cmd_ret = _cmd_run(cmd) return salt.utils.json.loads(cmd_ret) def list_repos(config_path=_DEFAULT_CONFIG_PATH, with_packages=False): """ List all of the repos. :param str config_path: The path to the configuration file for the aptly instance. :param bool with_packages: Return a list of packages in the repo. :return: A dictionary of the repositories. :rtype: dict CLI Example: .. code-block:: bash salt '*' aptly.list_repos """ _validate_config(config_path) ret = dict() cmd = ["repo", "list", "-config={}".format(config_path), "-raw=true"] cmd_ret = _cmd_run(cmd) repos = [line.strip() for line in cmd_ret.splitlines()] log.debug("Found repositories: %s", len(repos)) for name in repos: ret[name] = get_repo( name=name, config_path=config_path, with_packages=with_packages ) return ret def get_repo(name, config_path=_DEFAULT_CONFIG_PATH, with_packages=False): """ Get the details of the repository. :param str name: The name of the repository. :param str config_path: The path to the configuration file for the aptly instance. :param bool with_packages: Return a list of packages in the repo. :return: A dictionary containing information about the repository. :rtype: dict CLI Example: .. code-block:: bash salt '*' aptly.get_repo name="test-repo" """ _validate_config(config_path) with_packages = str(bool(with_packages)).lower() ret = dict() cmd = [ "repo", "show", "-config={}".format(config_path), "-with-packages={}".format(with_packages), name, ] cmd_ret = _cmd_run(cmd) for line in cmd_ret.splitlines(): try: # Extract the settings and their values, and attempt to format # them to match their equivalent setting names. items = line.split(":") key = items[0].lower().replace("default", "").strip() key = " ".join(key.split()).replace(" ", "_") ret[key] = salt.utils.stringutils.to_none( salt.utils.stringutils.to_num(items[1].strip()) ) except (AttributeError, IndexError): # If the line doesn't have the separator or is otherwise invalid, skip it. log.debug("Skipping line: %s", line) if ret: log.debug("Found repository: %s", name) else: log.debug("Unable to find repository: %s", name) return ret def new_repo( name, config_path=_DEFAULT_CONFIG_PATH, comment=None, component=None, distribution=None, uploaders_file=None, from_snapshot=None, saltenv="base", ): """ Create the new repository. :param str name: The name of the repository. :param str config_path: The path to the configuration file for the aptly instance. :param str comment: The description of the repository. :param str component: The default component to use when publishing. :param str distribution: The default distribution to use when publishing. :param str uploaders_file: The repository upload restrictions config. :param str from_snapshot: The snapshot to initialize the repository contents from. :param str saltenv: The environment the file resides in. :return: A boolean representing whether all changes succeeded. :rtype: bool CLI Example: .. code-block:: bash salt '*' aptly.new_repo name="test-repo" comment="Test main repo" component="main" distribution="trusty" """ _validate_config(config_path) current_repo = __salt__["aptly.get_repo"](name=name, config_path=config_path) if current_repo: log.debug("Repository already exists: %s", name) return True cmd = ["repo", "create", "-config={}".format(config_path)] repo_params = _format_repo_args( comment=comment, component=component, distribution=distribution, uploaders_file=uploaders_file, saltenv=saltenv, ) cmd.extend(repo_params) cmd.append(name) if from_snapshot: cmd.extend(["from", "snapshot", from_snapshot]) _cmd_run(cmd) repo = __salt__["aptly.get_repo"](name=name, config_path=config_path) if repo: log.debug("Created repo: %s", name) return True log.error("Unable to create repo: %s", name) return False def set_repo( name, config_path=_DEFAULT_CONFIG_PATH, comment=None, component=None, distribution=None, uploaders_file=None, saltenv="base", ): """ Configure the repository settings. :param str name: The name of the repository. :param str config_path: The path to the configuration file for the aptly instance. :param str comment: The description of the repository. :param str component: The default component to use when publishing. :param str distribution: The default distribution to use when publishing. :param str uploaders_file: The repository upload restrictions config. :param str from_snapshot: The snapshot to initialize the repository contents from. :param str saltenv: The environment the file resides in. :return: A boolean representing whether all changes succeeded. :rtype: bool CLI Example: .. code-block:: bash salt '*' aptly.set_repo name="test-repo" comment="Test universe repo" component="universe" distribution="xenial" """ _validate_config(config_path) failed_settings = dict() # Only check for settings that were passed in and skip the rest. settings = { "comment": comment, "component": component, "distribution": distribution, } for setting in list(settings): if settings[setting] is None: settings.pop(setting, None) current_settings = __salt__["aptly.get_repo"](name=name, config_path=config_path) if not current_settings: log.error("Unable to get repo: %s", name) return False # Discard any additional settings that get_repo gives # us that are not present in the provided arguments. for current_setting in list(current_settings): if current_setting not in settings: current_settings.pop(current_setting, None) # Check the existing repo settings to see if they already have the desired values. if settings == current_settings: log.debug("Settings already have the desired values for repository: %s", name) return True cmd = ["repo", "edit", "-config={}".format(config_path)] repo_params = _format_repo_args( comment=comment, component=component, distribution=distribution, uploaders_file=uploaders_file, saltenv=saltenv, ) cmd.extend(repo_params) cmd.append(name) _cmd_run(cmd) new_settings = __salt__["aptly.get_repo"](name=name, config_path=config_path) # Check the new repo settings to see if they have the desired values. for setting in settings: if settings[setting] != new_settings[setting]: failed_settings.update({setting: settings[setting]}) if failed_settings: log.error("Unable to change settings for the repository: %s", name) return False log.debug( "Settings successfully changed to the desired values for repository: %s", name ) return True def delete_repo(name, config_path=_DEFAULT_CONFIG_PATH, force=False): """ Remove the repository. :param str name: The name of the repository. :param str config_path: The path to the configuration file for the aptly instance. :param bool force: Whether to remove the repository even if it is used as the source of an existing snapshot. :return: A boolean representing whether all changes succeeded. :rtype: bool CLI Example: .. code-block:: bash salt '*' aptly.delete_repo name="test-repo" """ _validate_config(config_path) force = str(bool(force)).lower() current_repo = __salt__["aptly.get_repo"](name=name, config_path=config_path) if not current_repo: log.debug("Repository already absent: %s", name) return True cmd = [ "repo", "drop", "-config={}".format(config_path), "-force={}".format(force), name, ] _cmd_run(cmd) repo = __salt__["aptly.get_repo"](name=name, config_path=config_path) if repo: log.error("Unable to remove repo: %s", name) return False log.debug("Removed repo: %s", name) return True def list_mirrors(config_path=_DEFAULT_CONFIG_PATH): """ Get a list of all the mirrors. :param str config_path: The path to the configuration file for the aptly instance. :return: A list of the mirror names. :rtype: list CLI Example: .. code-block:: bash salt '*' aptly.list_mirrors """ _validate_config(config_path) cmd = ["mirror", "list", "-config={}".format(config_path), "-raw=true"] cmd_ret = _cmd_run(cmd) ret = [line.strip() for line in cmd_ret.splitlines()] log.debug("Found mirrors: %s", len(ret)) return ret def list_published(config_path=_DEFAULT_CONFIG_PATH): """ Get a list of all the published repositories. :param str config_path: The path to the configuration file for the aptly instance. :return: A list of the published repository names. :rtype: list CLI Example: .. code-block:: bash salt '*' aptly.list_published """ _validate_config(config_path) cmd = ["publish", "list", "-config={}".format(config_path), "-raw=true"] cmd_ret = _cmd_run(cmd) ret = [line.strip() for line in cmd_ret.splitlines()] log.debug("Found published repositories: %s", len(ret)) return ret def list_snapshots(config_path=_DEFAULT_CONFIG_PATH, sort_by_time=False): """ Get a list of all the snapshots. :param str config_path: The path to the configuration file for the aptly instance. :param bool sort_by_time: Whether to sort by creation time instead of by name. :return: A list of the snapshot names. :rtype: list CLI Example: .. code-block:: bash salt '*' aptly.list_snapshots """ _validate_config(config_path) cmd = ["snapshot", "list", "-config={}".format(config_path), "-raw=true"] if sort_by_time: cmd.append("-sort=time") else: cmd.append("-sort=name") cmd_ret = _cmd_run(cmd) ret = [line.strip() for line in cmd_ret.splitlines()] log.debug("Found snapshots: %s", len(ret)) return ret def cleanup_db(config_path=_DEFAULT_CONFIG_PATH, dry_run=False): """ Remove data regarding unreferenced packages and delete files in the package pool that are no longer being used by packages. :param bool dry_run: Report potential changes without making any changes. :return: A dictionary of the package keys and files that were removed. :rtype: dict CLI Example: .. code-block:: bash salt '*' aptly.cleanup_db """ _validate_config(config_path) dry_run = str(bool(dry_run)).lower() ret = {"deleted_keys": list(), "deleted_files": list()} cmd = [ "db", "cleanup", "-config={}".format(config_path), "-dry-run={}".format(dry_run), "-verbose=true", ] cmd_ret = _cmd_run(cmd) type_pattern = r"^List\s+[\w\s]+(?P<package_type>(file|key)s)[\w\s]+:$" list_pattern = r"^\s+-\s+(?P<package>.*)$" current_block = None for line in cmd_ret.splitlines(): if current_block: match = re.search(list_pattern, line) if match: package_type = "deleted_{}".format(current_block) ret[package_type].append(match.group("package")) else: current_block = None # Intentionally not using an else here, in case of a situation where # the next list header might be bordered by the previous list. if not current_block: match = re.search(type_pattern, line) if match: current_block = match.group("package_type") log.debug("Package keys identified for deletion: %s", len(ret["deleted_keys"])) log.debug("Package files identified for deletion: %s", len(ret["deleted_files"])) return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/aptly.py
0.591723
0.151875
aptly.py
pypi
import logging import os from salt.utils.files import fopen try: import textfsm HAS_TEXTFSM = True except ImportError: HAS_TEXTFSM = False try: from textfsm import clitable HAS_CLITABLE = True except ImportError: HAS_CLITABLE = False log = logging.getLogger(__name__) __virtualname__ = "textfsm" __proxyenabled__ = ["*"] def __virtual__(): """ Only load this execution module if TextFSM is installed. """ if HAS_TEXTFSM: return __virtualname__ return ( False, "The textfsm execution module failed to load: requires the textfsm library.", ) def _clitable_to_dict(objects, fsm_handler): """ Converts TextFSM cli_table object to list of dictionaries. """ objs = [] log.debug("Cli Table: %s; FSM handler: %s", objects, fsm_handler) for row in objects: temp_dict = {} for index, element in enumerate(row): temp_dict[fsm_handler.header[index].lower()] = element objs.append(temp_dict) log.debug("Extraction result: %s", objs) return objs def extract(template_path, raw_text=None, raw_text_file=None, saltenv="base"): r""" Extracts the data entities from the unstructured raw text sent as input and returns the data mapping, processing using the TextFSM template. template_path The path to the TextFSM template. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the template from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` raw_text: ``None`` The unstructured text to be parsed. raw_text_file: ``None`` Text file to read, having the raw text to be parsed using the TextFSM template. Supports the same URL schemes as the ``template_path`` argument. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. Ignored if ``template_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' textfsm.extract salt://textfsm/juniper_version_template raw_text_file=s3://junos_ver.txt salt '*' textfsm.extract http://some-server/textfsm/juniper_version_template raw_text='Hostname: router.abc ... snip ...' Jinja template example: .. code-block:: jinja {%- set raw_text = 'Hostname: router.abc ... snip ...' -%} {%- set textfsm_extract = salt.textfsm.extract('https://some-server/textfsm/juniper_version_template', raw_text) -%} Raw text example: .. code-block:: text Hostname: router.abc Model: mx960 JUNOS Base OS boot [9.1S3.5] JUNOS Base OS Software Suite [9.1S3.5] JUNOS Kernel Software Suite [9.1S3.5] JUNOS Crypto Software Suite [9.1S3.5] JUNOS Packet Forwarding Engine Support (M/T Common) [9.1S3.5] JUNOS Packet Forwarding Engine Support (MX Common) [9.1S3.5] JUNOS Online Documentation [9.1S3.5] JUNOS Routing Software Suite [9.1S3.5] TextFSM Example: .. code-block:: text Value Chassis (\S+) Value Required Model (\S+) Value Boot (.*) Value Base (.*) Value Kernel (.*) Value Crypto (.*) Value Documentation (.*) Value Routing (.*) Start # Support multiple chassis systems. ^\S+:$$ -> Continue.Record ^${Chassis}:$$ ^Model: ${Model} ^JUNOS Base OS boot \[${Boot}\] ^JUNOS Software Release \[${Base}\] ^JUNOS Base OS Software Suite \[${Base}\] ^JUNOS Kernel Software Suite \[${Kernel}\] ^JUNOS Crypto Software Suite \[${Crypto}\] ^JUNOS Online Documentation \[${Documentation}\] ^JUNOS Routing Software Suite \[${Routing}\] Output example: .. code-block:: json { "comment": "", "result": true, "out": [ { "kernel": "9.1S3.5", "documentation": "9.1S3.5", "boot": "9.1S3.5", "crypto": "9.1S3.5", "chassis": "", "routing": "9.1S3.5", "base": "9.1S3.5", "model": "mx960" } ] } """ ret = {"result": False, "comment": "", "out": None} log.debug( "Caching %s(saltenv: %s) using the Salt fileserver", template_path, saltenv ) tpl_cached_path = __salt__["cp.cache_file"](template_path, saltenv=saltenv) if tpl_cached_path is False: ret["comment"] = "Unable to read the TextFSM template from {}".format( template_path ) log.error(ret["comment"]) return ret try: log.debug("Reading TextFSM template from cache path: %s", tpl_cached_path) # Disabling pylint W8470 to nto complain about fopen. # Unfortunately textFSM needs the file handle rather than the content... # pylint: disable=W8470 tpl_file_handle = fopen(tpl_cached_path, "r") # pylint: disable=W8470 log.debug(tpl_file_handle.read()) tpl_file_handle.seek(0) # move the object position back at the top of the file fsm_handler = textfsm.TextFSM(tpl_file_handle) except textfsm.TextFSMTemplateError as tfte: log.error("Unable to parse the TextFSM template", exc_info=True) ret[ "comment" ] = "Unable to parse the TextFSM template from {}: {}. Please check the logs.".format( template_path, tfte ) return ret if not raw_text and raw_text_file: log.debug("Trying to read the raw input from %s", raw_text_file) raw_text = __salt__["cp.get_file_str"](raw_text_file, saltenv=saltenv) if raw_text is False: ret[ "comment" ] = "Unable to read from {}. Please specify a valid input file or text.".format( raw_text_file ) log.error(ret["comment"]) return ret if not raw_text: ret["comment"] = "Please specify a valid input file or text." log.error(ret["comment"]) return ret log.debug("Processing the raw text:\n%s", raw_text) objects = fsm_handler.ParseText(raw_text) ret["out"] = _clitable_to_dict(objects, fsm_handler) ret["result"] = True return ret def index( command, platform=None, platform_grain_name=None, platform_column_name=None, output=None, output_file=None, textfsm_path=None, index_file=None, saltenv="base", include_empty=False, include_pat=None, exclude_pat=None, ): """ Dynamically identify the template required to extract the information from the unstructured raw text. The output has the same structure as the ``extract`` execution function, the difference being that ``index`` is capable to identify what template to use, based on the platform details and the ``command``. command The command executed on the device, to get the output. platform The platform name, as defined in the TextFSM index file. .. note:: For ease of use, it is recommended to define the TextFSM indexfile with values that can be matches using the grains. platform_grain_name The name of the grain used to identify the platform name in the TextFSM index file. .. note:: This option can be also specified in the minion configuration file or pillar as ``textfsm_platform_grain``. .. note:: This option is ignored when ``platform`` is specified. platform_column_name: ``Platform`` The column name used to identify the platform, exactly as specified in the TextFSM index file. Default: ``Platform``. .. note:: This is field is case sensitive, make sure to assign the correct value to this option, exactly as defined in the index file. .. note:: This option can be also specified in the minion configuration file or pillar as ``textfsm_platform_column_name``. output The raw output from the device, to be parsed and extract the structured data. output_file The path to a file that contains the raw output from the device, used to extract the structured data. This option supports the usual Salt-specific schemes: ``file://``, ``salt://``, ``http://``, ``https://``, ``ftp://``, ``s3://``, ``swift://``. textfsm_path The path where the TextFSM templates can be found. This can be either absolute path on the server, either specified using the following URL schemes: ``file://``, ``salt://``, ``http://``, ``https://``, ``ftp://``, ``s3://``, ``swift://``. .. note:: This needs to be a directory with a flat structure, having an index file (whose name can be specified using the ``index_file`` option) and a number of TextFSM templates. .. note:: This option can be also specified in the minion configuration file or pillar as ``textfsm_path``. index_file: ``index`` The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``. .. note:: This option can be also specified in the minion configuration file or pillar as ``textfsm_index_file``. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. Ignored if ``textfsm_path`` is not a ``salt://`` URL. include_empty: ``False`` Include empty files under the ``textfsm_path``. include_pat Glob or regex to narrow down the files cached from the given path. If matching with a regex, the regex must be prefixed with ``E@``, otherwise the expression will be interpreted as a glob. exclude_pat Glob or regex to exclude certain files from being cached from the given path. If matching with a regex, the regex must be prefixed with ``E@``, otherwise the expression will be interpreted as a glob. .. note:: If used with ``include_pat``, files matching this pattern will be excluded from the subset of files defined by ``include_pat``. CLI Example: .. code-block:: bash salt '*' textfsm.index 'sh ver' platform=Juniper output_file=salt://textfsm/juniper_version_example textfsm_path=salt://textfsm/ salt '*' textfsm.index 'sh ver' output_file=salt://textfsm/juniper_version_example textfsm_path=ftp://textfsm/ platform_column_name=Vendor salt '*' textfsm.index 'sh ver' output_file=salt://textfsm/juniper_version_example textfsm_path=https://some-server/textfsm/ platform_column_name=Vendor platform_grain_name=vendor TextFSM index file example: ``salt://textfsm/index`` .. code-block:: text Template, Hostname, Vendor, Command juniper_version_template, .*, Juniper, sh[[ow]] ve[[rsion]] The usage can be simplified, by defining (some of) the following options: ``textfsm_platform_grain``, ``textfsm_path``, ``textfsm_platform_column_name``, or ``textfsm_index_file``, in the (proxy) minion configuration file or pillar. Configuration example: .. code-block:: yaml textfsm_platform_grain: vendor textfsm_path: salt://textfsm/ textfsm_platform_column_name: Vendor And the CLI usage becomes as simple as: .. code-block:: bash salt '*' textfsm.index 'sh ver' output_file=salt://textfsm/juniper_version_example Usgae inside a Jinja template: .. code-block:: jinja {%- set command = 'sh ver' -%} {%- set output = salt.net.cli(command) -%} {%- set textfsm_extract = salt.textfsm.index(command, output=output) -%} """ ret = {"out": None, "result": False, "comment": ""} if not HAS_CLITABLE: ret["comment"] = "TextFSM does not seem that has clitable embedded." log.error(ret["comment"]) return ret if not platform: platform_grain_name = __opts__.get("textfsm_platform_grain") or __pillar__.get( "textfsm_platform_grain", platform_grain_name ) if platform_grain_name: log.debug( "Using the %s grain to identify the platform name", platform_grain_name ) platform = __grains__.get(platform_grain_name) if not platform: ret[ "comment" ] = "Unable to identify the platform name using the {} grain.".format( platform_grain_name ) return ret log.info("Using platform: %s", platform) else: ret[ "comment" ] = "No platform specified, no platform grain identifier configured." log.error(ret["comment"]) return ret if not textfsm_path: log.debug( "No TextFSM templates path specified, trying to look into the opts and" " pillar" ) textfsm_path = __opts__.get("textfsm_path") or __pillar__.get("textfsm_path") if not textfsm_path: ret["comment"] = ( "No TextFSM templates path specified. Please configure in" " opts/pillar/function args." ) log.error(ret["comment"]) return ret log.debug( "Caching %s(saltenv: %s) using the Salt fileserver", textfsm_path, saltenv ) textfsm_cachedir_ret = __salt__["cp.cache_dir"]( textfsm_path, saltenv=saltenv, include_empty=include_empty, include_pat=include_pat, exclude_pat=exclude_pat, ) log.debug("Cache fun return:\n%s", textfsm_cachedir_ret) if not textfsm_cachedir_ret: ret[ "comment" ] = "Unable to fetch from {}. Is the TextFSM path correctly specified?".format( textfsm_path ) log.error(ret["comment"]) return ret textfsm_cachedir = os.path.dirname(textfsm_cachedir_ret[0]) # first item index_file = __opts__.get("textfsm_index_file") or __pillar__.get( "textfsm_index_file", "index" ) index_file_path = os.path.join(textfsm_cachedir, index_file) log.debug("Using the cached index file: %s", index_file_path) log.debug("TextFSM templates cached under: %s", textfsm_cachedir) textfsm_obj = clitable.CliTable(index_file_path, textfsm_cachedir) attrs = {"Command": command} platform_column_name = __opts__.get( "textfsm_platform_column_name" ) or __pillar__.get("textfsm_platform_column_name", "Platform") log.info("Using the TextFSM platform idenfiticator: %s", platform_column_name) attrs[platform_column_name] = platform log.debug("Processing the TextFSM index file using the attributes: %s", attrs) if not output and output_file: log.debug("Processing the output from %s", output_file) output = __salt__["cp.get_file_str"](output_file, saltenv=saltenv) if output is False: ret[ "comment" ] = "Unable to read from {}. Please specify a valid file or text.".format( output_file ) log.error(ret["comment"]) return ret if not output: ret["comment"] = "Please specify a valid output text or file" log.error(ret["comment"]) return ret log.debug("Processing the raw text:\n%s", output) try: # Parse output through template textfsm_obj.ParseCmd(output, attrs) ret["out"] = _clitable_to_dict(textfsm_obj, textfsm_obj) ret["result"] = True except clitable.CliTableError as cterr: log.error("Unable to proces the CliTable", exc_info=True) ret["comment"] = "Unable to process the output: {}".format(cterr) return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/textfsm_mod.py
0.554953
0.264762
textfsm_mod.py
pypi
import copy import inspect import logging import sys from collections.abc import Mapping import salt.loader from salt.defaults import DEFAULT_TARGET_DELIM from salt.exceptions import SaltException __func_alias__ = {"list_": "list"} log = logging.getLogger(__name__) def compound(tgt, minion_id=None): """ Return True if the minion ID matches the given compound target minion_id Specify the minion ID to match against the target expression .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' match.compound 'L@cheese,foo and *' """ if minion_id is not None: if not isinstance(minion_id, str): minion_id = str(minion_id) matchers = salt.loader.matchers(__opts__) try: ret = matchers["compound_match.match"](tgt, opts=__opts__, minion_id=minion_id) except Exception as exc: # pylint: disable=broad-except log.exception(exc) ret = False return ret def ipcidr(tgt): """ Return True if the minion matches the given ipcidr target CLI Example: .. code-block:: bash salt '*' match.ipcidr '192.168.44.0/24' delimiter Pillar Example: .. code-block:: yaml '172.16.0.0/12': - match: ipcidr - nodeclass: internal """ matchers = salt.loader.matchers(__opts__) try: return matchers["ipcidr_match.match"](tgt, opts=__opts__) except Exception as exc: # pylint: disable=broad-except log.exception(exc) return False def pillar_pcre(tgt, delimiter=DEFAULT_TARGET_DELIM): """ Return True if the minion matches the given pillar_pcre target. The ``delimiter`` argument can be used to specify a different delimiter. CLI Example: .. code-block:: bash salt '*' match.pillar_pcre 'cheese:(swiss|american)' salt '*' match.pillar_pcre 'clone_url|https://github\\.com/.*\\.git' delimiter='|' delimiter Specify an alternate delimiter to use when traversing a nested dict .. versionadded:: 2014.7.0 delim Specify an alternate delimiter to use when traversing a nested dict .. versionadded:: 0.16.4 .. deprecated:: 2015.8.0 """ matchers = salt.loader.matchers(__opts__) try: return matchers["pillar_pcre_match.match"]( tgt, delimiter=delimiter, opts=__opts__ ) except Exception as exc: # pylint: disable=broad-except log.exception(exc) return False def pillar(tgt, delimiter=DEFAULT_TARGET_DELIM): """ Return True if the minion matches the given pillar target. The ``delimiter`` argument can be used to specify a different delimiter. CLI Example: .. code-block:: bash salt '*' match.pillar 'cheese:foo' salt '*' match.pillar 'clone_url|https://github.com/saltstack/salt.git' delimiter='|' delimiter Specify an alternate delimiter to use when traversing a nested dict .. versionadded:: 2014.7.0 delim Specify an alternate delimiter to use when traversing a nested dict .. versionadded:: 0.16.4 .. deprecated:: 2015.8.0 """ matchers = salt.loader.matchers(__opts__) try: return matchers["pillar_match.match"](tgt, delimiter=delimiter, opts=__opts__) except Exception as exc: # pylint: disable=broad-except log.exception(exc) return False def data(tgt): """ Return True if the minion matches the given data target CLI Example: .. code-block:: bash salt '*' match.data 'spam:eggs' """ matchers = salt.loader.matchers(__opts__) try: return matchers["data_match.match"](tgt, opts=__opts__) except Exception as exc: # pylint: disable=broad-except log.exception(exc) return False def grain_pcre(tgt, delimiter=DEFAULT_TARGET_DELIM): """ Return True if the minion matches the given grain_pcre target. The ``delimiter`` argument can be used to specify a different delimiter. CLI Example: .. code-block:: bash salt '*' match.grain_pcre 'os:Fedo.*' salt '*' match.grain_pcre 'ipv6|2001:.*' delimiter='|' delimiter Specify an alternate delimiter to use when traversing a nested dict .. versionadded:: 2014.7.0 delim Specify an alternate delimiter to use when traversing a nested dict .. versionadded:: 0.16.4 .. deprecated:: 2015.8.0 """ matchers = salt.loader.matchers(__opts__) try: return matchers["grain_pcre_match.match"]( tgt, delimiter=delimiter, opts=__opts__ ) except Exception as exc: # pylint: disable=broad-except log.exception(exc) return False def grain(tgt, delimiter=DEFAULT_TARGET_DELIM): """ Return True if the minion matches the given grain target. The ``delimiter`` argument can be used to specify a different delimiter. CLI Example: .. code-block:: bash salt '*' match.grain 'os:Ubuntu' salt '*' match.grain 'ipv6|2001:db8::ff00:42:8329' delimiter='|' delimiter Specify an alternate delimiter to use when traversing a nested dict .. versionadded:: 2014.7.0 delim Specify an alternate delimiter to use when traversing a nested dict .. versionadded:: 0.16.4 .. deprecated:: 2015.8.0 """ matchers = salt.loader.matchers(__opts__) try: return matchers["grain_match.match"](tgt, delimiter=delimiter, opts=__opts__) except Exception as exc: # pylint: disable=broad-except log.exception(exc) return False def list_(tgt, minion_id=None): """ Return True if the minion ID matches the given list target minion_id Specify the minion ID to match against the target expression .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' match.list 'server1,server2' """ if minion_id is not None: if not isinstance(minion_id, str): minion_id = str(minion_id) matchers = salt.loader.matchers(__opts__) try: return matchers["list_match.match"](tgt, opts=__opts__, minion_id=minion_id) except Exception as exc: # pylint: disable=broad-except log.exception(exc) return False def pcre(tgt, minion_id=None): """ Return True if the minion ID matches the given pcre target minion_id Specify the minion ID to match against the target expression .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' match.pcre '.*' """ if minion_id is not None: if not isinstance(minion_id, str): minion_id = str(minion_id) matchers = salt.loader.matchers(__opts__) try: return matchers["pcre_match.match"](tgt, opts=__opts__, minion_id=minion_id) except Exception as exc: # pylint: disable=broad-except log.exception(exc) return False def glob(tgt, minion_id=None): """ Return True if the minion ID matches the given glob target minion_id Specify the minion ID to match against the target expression .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' match.glob '*' """ if minion_id is not None: if not isinstance(minion_id, str): minion_id = str(minion_id) matchers = salt.loader.matchers(__opts__) try: return matchers["glob_match.match"](tgt, opts=__opts__, minion_id=minion_id) except Exception as exc: # pylint: disable=broad-except log.exception(exc) return False def filter_by( lookup, tgt_type="compound", minion_id=None, merge=None, merge_lists=False, default="default", ): """ Return the first match in a dictionary of target patterns .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' match.filter_by '{foo*: Foo!, bar*: Bar!}' minion_id=bar03 Pillar Example: .. code-block:: jinja # Filter the data for the current minion into a variable: {% set roles = salt['match.filter_by']({ 'web*': ['app', 'caching'], 'db*': ['db'], }, minion_id=grains['id'], default='web*') %} # Make the filtered data available to Pillar: roles: {{ roles | yaml() }} """ expr_funcs = dict( inspect.getmembers(sys.modules[__name__], predicate=inspect.isfunction) ) for key in lookup: params = (key, minion_id) if minion_id else (key,) if expr_funcs[tgt_type](*params): if merge: if not isinstance(merge, Mapping): raise SaltException( "filter_by merge argument must be a dictionary." ) if lookup[key] is None: return merge else: salt.utils.dictupdate.update( lookup[key], copy.deepcopy(merge), merge_lists=merge_lists ) return lookup[key] return lookup.get(default, None) def search_by(lookup, tgt_type="compound", minion_id=None): """ Search a dictionary of target strings for matching targets This is the inverse of :py:func:`match.filter_by <salt.modules.match.filter_by>` and allows matching values instead of matching keys. A minion can be matched by multiple entries. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt '*' match.search_by '{web: [node1, node2], db: [node2, node]}' Pillar Example: .. code-block:: jinja {% set roles = salt.match.search_by({ 'web': ['G@os_family:Debian not nodeX'], 'db': ['L@node2,node3 and G@datacenter:west'], 'caching': ['node3', 'node4'], }) %} # Make the filtered data available to Pillar: roles: {{ roles | yaml() }} """ expr_funcs = dict( inspect.getmembers(sys.modules[__name__], predicate=inspect.isfunction) ) matches = [] for key, target_list in lookup.items(): for target in target_list: params = (target, minion_id) if minion_id else (target,) if expr_funcs[tgt_type](*params): matches.append(key) return matches or None
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/match.py
0.586286
0.254984
match.py
pypi
import datetime import logging import time import salt.utils.http import salt.utils.json from salt.exceptions import SaltInvocationError log = logging.getLogger(__name__) _api_key_missing_error = "No VictorOps api key found." def __virtual__(): """ Only load the module if apache is installed """ if not __salt__["config.get"]("victorops.api_key") and not __salt__["config.get"]( "victorops:api_key" ): return (False, _api_key_missing_error) return True def _query( action=None, routing_key=None, args=None, method="GET", header_dict=None, data=None ): """ Make a web call to VictorOps """ api_key = __salt__["config.get"]("victorops.api_key") or __salt__["config.get"]( "victorops:api_key" ) path = "https://alert.victorops.com/integrations/generic/20131114/" if action: path += "{}/".format(action) if api_key: path += "{}/".format(api_key) if routing_key: path += routing_key log.debug("VictorOps URL: %s", path) if not isinstance(args, dict): args = {} if header_dict is None: header_dict = {"Content-type": "application/json"} if method != "POST": header_dict["Accept"] = "application/json" decode = True if method == "DELETE": decode = False result = salt.utils.http.query( path, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type="json", text=True, status=True, cookies=True, persist_session=True, opts=__opts__, ) if "error" in result: log.error(result["error"]) return [result["status"], result["error"]] return [result["status"], result.get("dict", {})] def create_event(message_type=None, routing_key="everybody", **kwargs): """ Create an event in VictorOps. Designed for use in states. The following parameters are required: :param message_type: One of the following values: INFO, WARNING, ACKNOWLEDGEMENT, CRITICAL, RECOVERY. The following parameters are optional: :param routing_key: The key for where messages should be routed. By default, sent to 'everyone' route. :param entity_id: The name of alerting entity. If not provided, a random name will be assigned. :param timestamp: Timestamp of the alert in seconds since epoch. Defaults to the time the alert is received at VictorOps. :param timestamp_fmt The date format for the timestamp parameter. :param state_start_time: The time this entity entered its current state (seconds since epoch). Defaults to the time alert is received. :param state_start_time_fmt: The date format for the timestamp parameter. :param state_message: Any additional status information from the alert item. :param entity_is_host: Used within VictorOps to select the appropriate display format for the incident. :param entity_display_name: Used within VictorOps to display a human-readable name for the entity. :param ack_message: A user entered comment for the acknowledgment. :param ack_author: The user that acknowledged the incident. :return: A dictionary with result, entity_id, and message if result was failure. CLI Example: .. code-block:: yaml salt myminion victorops.create_event message_type='CRITICAL' routing_key='everyone' \ entity_id='hostname/diskspace' salt myminion victorops.create_event message_type='ACKNOWLEDGEMENT' routing_key='everyone' \ entity_id='hostname/diskspace' ack_message='Acknowledged' ack_author='username' salt myminion victorops.create_event message_type='RECOVERY' routing_key='everyone' \ entity_id='hostname/diskspace' The following parameters are required: message_type """ keyword_args = { "entity_id": str, "state_message": str, "entity_is_host": bool, "entity_display_name": str, "ack_message": str, "ack_author": str, } data = {} if not message_type: raise SaltInvocationError('Required argument "message_type" is missing.') if message_type.upper() not in [ "INFO", "WARNING", "ACKNOWLEDGEMENT", "CRITICAL", "RECOVERY", ]: raise SaltInvocationError( '"message_type" must be INFO, WARNING, ACKNOWLEDGEMENT, CRITICAL, or' " RECOVERY." ) data["message_type"] = message_type data["monitoring_tool"] = "SaltStack" if "timestamp" in kwargs: timestamp_fmt = kwargs.get("timestamp_fmt", "%Y-%m-%dT%H:%M:%S") try: timestamp = datetime.datetime.strptime(kwargs["timestamp"], timestamp_fmt) data["timestamp"] = int(time.mktime(timestamp.timetuple())) except (TypeError, ValueError): raise SaltInvocationError( "Date string could not be parsed: {}, {}".format( kwargs["timestamp"], timestamp_fmt ) ) if "state_start_time" in kwargs: state_start_time_fmt = kwargs.get("state_start_time_fmt", "%Y-%m-%dT%H:%M:%S") try: state_start_time = datetime.datetime.strptime( kwargs["state_start_time"], state_start_time_fmt ) data["state_start_time"] = int(time.mktime(state_start_time.timetuple())) except (TypeError, ValueError): raise SaltInvocationError( "Date string could not be parsed: {}, {}".format( kwargs["state_start_time"], state_start_time_fmt ) ) for kwarg in keyword_args: if kwarg in kwargs: if isinstance(kwargs[kwarg], keyword_args[kwarg]): data[kwarg] = kwargs[kwarg] else: # Should this faile on the wrong type. log.error("Wrong type, skipping %s", kwarg) status, result = _query( action="alert", routing_key=routing_key, data=salt.utils.json.dumps(data), method="POST", ) return result
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/victorops.py
0.631026
0.200519
victorops.py
pypi
import logging import os import salt.utils.path log = logging.getLogger(__name__) __virtualname__ = "webutil" def __virtual__(): """ Only load the module if htpasswd is installed """ if salt.utils.path.which("htpasswd"): return __virtualname__ return ( False, "The htpasswd execution mdule cannot be loaded: htpasswd binary not in path.", ) def useradd(pwfile, user, password, opts="", runas=None): """ Add a user to htpasswd file using the htpasswd command. If the htpasswd file does not exist, it will be created. pwfile Path to htpasswd file user User name password User password opts Valid options that can be passed are: - `n` Don't update file; display results on stdout. - `m` Force MD5 encryption of the password (default). - `d` Force CRYPT encryption of the password. - `p` Do not encrypt the password (plaintext). - `s` Force SHA encryption of the password. runas The system user to run htpasswd command with CLI Examples: .. code-block:: bash salt '*' webutil.useradd /etc/httpd/htpasswd larry badpassword salt '*' webutil.useradd /etc/httpd/htpasswd larry badpass opts=ns """ if not os.path.exists(pwfile): opts += "c" cmd = ["htpasswd", "-b{}".format(opts), pwfile, user, password] return __salt__["cmd.run_all"](cmd, runas=runas, python_shell=False) def userdel(pwfile, user, runas=None, all_results=False): """ Delete a user from the specified htpasswd file. pwfile Path to htpasswd file user User name runas The system user to run htpasswd command with all_results Return stdout, stderr, and retcode, not just stdout CLI Examples: .. code-block:: bash salt '*' webutil.userdel /etc/httpd/htpasswd larry """ if not os.path.exists(pwfile): return "Error: The specified htpasswd file does not exist" cmd = ["htpasswd", "-D", pwfile, user] if all_results: out = __salt__["cmd.run_all"](cmd, runas=runas, python_shell=False) else: out = __salt__["cmd.run"](cmd, runas=runas, python_shell=False).splitlines() return out def verify(pwfile, user, password, opts="", runas=None): """ Return True if the htpasswd file exists, the user has an entry, and their password matches. pwfile Fully qualified path to htpasswd file user User name password User password opts Valid options that can be passed are: - `m` Force MD5 encryption of the password (default). - `d` Force CRYPT encryption of the password. - `p` Do not encrypt the password (plaintext). - `s` Force SHA encryption of the password. runas The system user to run htpasswd command with CLI Examples: .. code-block:: bash salt '*' webutil.verify /etc/httpd/htpasswd larry maybepassword salt '*' webutil.verify /etc/httpd/htpasswd larry maybepassword opts=ns """ if not os.path.exists(pwfile): return False cmd = ["htpasswd", "-bv{}".format(opts), pwfile, user, password] ret = __salt__["cmd.run_all"](cmd, runas=runas, python_shell=False) log.debug("Result of verifying htpasswd for user %s: %s", user, ret) return ret["retcode"] == 0
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/webutil.py
0.650245
0.152284
webutil.py
pypi
import logging import os import shlex import salt.utils.platform try: import pipes HAS_DEPS = True except ImportError: HAS_DEPS = False log = logging.getLogger(__name__) __virtualname__ = "macpackage" if hasattr(shlex, "quote"): _quote = shlex.quote elif HAS_DEPS and hasattr(pipes, "quote"): _quote = pipes.quote else: _quote = None def __virtual__(): """ Only work on Mac OS """ if salt.utils.platform.is_darwin() and _quote is not None: return __virtualname__ return (False, "Only available on Mac OS systems with pipes") def install(pkg, target="LocalSystem", store=False, allow_untrusted=False): """ Install a pkg file Args: pkg (str): The package to install target (str): The target in which to install the package to store (bool): Should the package be installed as if it was from the store? allow_untrusted (bool): Allow the installation of untrusted packages? Returns: dict: A dictionary containing the results of the installation CLI Example: .. code-block:: bash salt '*' macpackage.install test.pkg """ if "*." not in pkg: # If we use wildcards, we cannot use quotes pkg = _quote(pkg) target = _quote(target) cmd = "installer -pkg {} -target {}".format(pkg, target) if store: cmd += " -store" if allow_untrusted: cmd += " -allowUntrusted" # We can only use wildcards in python_shell which is # sent by the macpackage state python_shell = False if "*." in cmd: python_shell = True return __salt__["cmd.run_all"](cmd, python_shell=python_shell) def install_app(app, target="/Applications/"): """ Install an app file by moving it into the specified Applications directory Args: app (str): The location of the .app file target (str): The target in which to install the package to Default is ''/Applications/'' Returns: str: The results of the rsync command CLI Example: .. code-block:: bash salt '*' macpackage.install_app /tmp/tmp.app /Applications/ """ if target[-4:] != ".app": if app[-1:] == "/": base_app = os.path.basename(app[:-1]) else: base_app = os.path.basename(app) target = os.path.join(target, base_app) if not app[-1] == "/": app += "/" cmd = 'rsync -a --delete "{}" "{}"'.format(app, target) return __salt__["cmd.run"](cmd) def uninstall_app(app): """ Uninstall an app file by removing it from the Applications directory Args: app (str): The location of the .app file Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' macpackage.uninstall_app /Applications/app.app """ return __salt__["file.remove"](app) def mount(dmg): """ Attempt to mount a dmg file to a temporary location and return the location of the pkg file inside Args: dmg (str): The location of the dmg file to mount Returns: tuple: Tuple containing the results of the command along with the mount point CLI Example: .. code-block:: bash salt '*' macpackage.mount /tmp/software.dmg """ temp_dir = __salt__["temp.dir"](prefix="dmg-") cmd = 'hdiutil attach -readonly -nobrowse -mountpoint {} "{}"'.format(temp_dir, dmg) return __salt__["cmd.run"](cmd), temp_dir def unmount(mountpoint): """ Attempt to unmount a dmg file from a temporary location Args: mountpoint (str): The location of the mount point Returns: str: The results of the hdutil detach command CLI Example: .. code-block:: bash salt '*' macpackage.unmount /dev/disk2 """ cmd = 'hdiutil detach "{}"'.format(mountpoint) return __salt__["cmd.run"](cmd) def installed_pkgs(): """ Return the list of installed packages on the machine Returns: list: List of installed packages CLI Example: .. code-block:: bash salt '*' macpackage.installed_pkgs """ cmd = "pkgutil --pkgs" return __salt__["cmd.run"](cmd).split("\n") def get_pkg_id(pkg): """ Attempt to get the package ID from a .pkg file Args: pkg (str): The location of the pkg file Returns: list: List of all of the package IDs CLI Example: .. code-block:: bash salt '*' macpackage.get_pkg_id /tmp/test.pkg """ pkg = _quote(pkg) package_ids = [] # Create temp directory temp_dir = __salt__["temp.dir"](prefix="pkg-") try: # List all of the PackageInfo files cmd = "xar -t -f {} | grep PackageInfo".format(pkg) out = __salt__["cmd.run"](cmd, python_shell=True, output_loglevel="quiet") files = out.split("\n") if "Error opening" not in out: # Extract the PackageInfo files cmd = "xar -x -f {} {}".format(pkg, " ".join(files)) __salt__["cmd.run"](cmd, cwd=temp_dir, output_loglevel="quiet") # Find our identifiers for f in files: i = _get_pkg_id_from_pkginfo(os.path.join(temp_dir, f)) if i: package_ids.extend(i) else: package_ids = _get_pkg_id_dir(pkg) finally: # Clean up __salt__["file.remove"](temp_dir) return package_ids def get_mpkg_ids(mpkg): """ Attempt to get the package IDs from a mounted .mpkg file Args: mpkg (str): The location of the mounted mpkg file Returns: list: List of package IDs CLI Example: .. code-block:: bash salt '*' macpackage.get_mpkg_ids /dev/disk2 """ mpkg = _quote(mpkg) package_infos = [] base_path = os.path.dirname(mpkg) # List all of the .pkg files cmd = "find {} -name *.pkg".format(base_path) out = __salt__["cmd.run"](cmd, python_shell=True) pkg_files = out.split("\n") for p in pkg_files: package_infos.extend(get_pkg_id(p)) return package_infos def _get_pkg_id_from_pkginfo(pkginfo): # Find our identifiers pkginfo = _quote(pkginfo) cmd = "cat {} | grep -Eo 'identifier=\"[a-zA-Z.0-9\\-]*\"' | cut -c 13- | tr -d '\"'".format( pkginfo ) out = __salt__["cmd.run"](cmd, python_shell=True) if "No such file" not in out: return out.split("\n") return [] def _get_pkg_id_dir(path): path = _quote(os.path.join(path, "Contents/Info.plist")) cmd = '/usr/libexec/PlistBuddy -c "print :CFBundleIdentifier" {}'.format(path) # We can only use wildcards in python_shell which is # sent by the macpackage state python_shell = False if "*." in cmd: python_shell = True out = __salt__["cmd.run"](cmd, python_shell=python_shell) if "Does Not Exist" not in out: return [out] return []
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/macpackage.py
0.589598
0.180974
macpackage.py
pypi
import logging import salt.utils.json import salt.utils.path log = logging.getLogger(__name__) _OUTPUT = "--output json" def __virtual__(): if salt.utils.path.which("aws"): # awscli is installed, load the module return True return (False, "The module aws_sqs could not be loaded: aws command not found") def _region(region): """ Return the region argument. """ return " --region {r}".format(r=region) def _run_aws(cmd, region, opts, user, **kwargs): """ Runs the given command against AWS. cmd Command to run region Region to execute cmd in opts Pass in from salt user Pass in from salt kwargs Key-value arguments to pass to the command """ # These args need a specific key value that aren't # valid python parameter keys receipthandle = kwargs.pop("receipthandle", None) if receipthandle: kwargs["receipt-handle"] = receipthandle num = kwargs.pop("num", None) if num: kwargs["max-number-of-messages"] = num _formatted_args = ['--{} "{}"'.format(k, v) for k, v in kwargs.items()] cmd = "aws sqs {cmd} {args} {region} {out}".format( cmd=cmd, args=" ".join(_formatted_args), region=_region(region), out=_OUTPUT ) rtn = __salt__["cmd.run"](cmd, runas=user, python_shell=False) return salt.utils.json.loads(rtn) if rtn else "" def receive_message(queue, region, num=1, opts=None, user=None): """ Receive one or more messages from a queue in a region queue The name of the queue to receive messages from region Region where SQS queues exists num : 1 The max number of messages to receive opts : None Any additional options to add to the command line user : None Run as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' aws_sqs.receive_message <sqs queue> <region> salt '*' aws_sqs.receive_message <sqs queue> <region> num=10 .. versionadded:: 2014.7.0 """ ret = { "Messages": None, } queues = list_queues(region, opts, user) url_map = _parse_queue_list(queues) if queue not in url_map: log.info('"%s" queue does not exist.', queue) return ret out = _run_aws("receive-message", region, opts, user, queue=url_map[queue], num=num) ret["Messages"] = out["Messages"] return ret def delete_message(queue, region, receipthandle, opts=None, user=None): """ Delete one or more messages from a queue in a region queue The name of the queue to delete messages from region Region where SQS queues exists receipthandle The ReceiptHandle of the message to delete. The ReceiptHandle is obtained in the return from receive_message opts : None Any additional options to add to the command line user : None Run as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' aws_sqs.delete_message <sqs queue> <region> receipthandle='<sqs ReceiptHandle>' .. versionadded:: 2014.7.0 """ queues = list_queues(region, opts, user) url_map = _parse_queue_list(queues) if queue not in url_map: log.info('"%s" queue does not exist.', queue) return False out = _run_aws( "delete-message", region, opts, user, receipthandle=receipthandle, queue=url_map[queue], ) return True def list_queues(region, opts=None, user=None): """ List the queues in the selected region. region Region to list SQS queues for opts : None Any additional options to add to the command line user : None Run hg as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' aws_sqs.list_queues <region> """ out = _run_aws("list-queues", region, opts, user) ret = { "retcode": 0, "stdout": out["QueueUrls"], } return ret def create_queue(name, region, opts=None, user=None): """ Creates a queue with the correct name. name Name of the SQS queue to create region Region to create the SQS queue in opts : None Any additional options to add to the command line user : None Run hg as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' aws_sqs.create_queue <sqs queue> <region> """ create = {"queue-name": name} out = _run_aws("create-queue", region=region, opts=opts, user=user, **create) ret = { "retcode": 0, "stdout": out["QueueUrl"], "stderr": "", } return ret def delete_queue(name, region, opts=None, user=None): """ Deletes a queue in the region. name Name of the SQS queue to deletes region Name of the region to delete the queue from opts : None Any additional options to add to the command line user : None Run hg as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' aws_sqs.delete_queue <sqs queue> <region> """ queues = list_queues(region, opts, user) url_map = _parse_queue_list(queues) log.debug("map %s", url_map) if name in url_map: delete = {"queue-url": url_map[name]} rtn = _run_aws("delete-queue", region=region, opts=opts, user=user, **delete) success = True err = "" out = "{} deleted".format(name) else: out = "" err = "Delete failed" success = False ret = { "retcode": 0 if success else 1, "stdout": out, "stderr": err, } return ret def queue_exists(name, region, opts=None, user=None): """ Returns True or False on whether the queue exists in the region name Name of the SQS queue to search for region Name of the region to search for the queue in opts : None Any additional options to add to the command line user : None Run hg as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' aws_sqs.queue_exists <sqs queue> <region> """ output = list_queues(region, opts, user) return name in _parse_queue_list(output) def _parse_queue_list(list_output): """ Parse the queue to get a dict of name -> URL """ queues = {q.split("/")[-1]: q for q in list_output["stdout"]} return queues
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/aws_sqs.py
0.641085
0.206514
aws_sqs.py
pypi
import logging import salt.utils.http import salt.utils.json from salt.exceptions import SaltInvocationError log = logging.getLogger(__name__) def __virtual__(): """ Only load the module if apache is installed """ if not __opts__.get("rallydev", {}).get("username", None): return ( False, "The rallydev execution module failed to load: rallydev:username not" " defined in config.", ) if not __opts__.get("rallydev", {}).get("password", None): return ( False, "The rallydev execution module failed to load: rallydev:password not" " defined in config.", ) return True def _get_token(): """ Get an auth token """ username = __opts__.get("rallydev", {}).get("username", None) password = __opts__.get("rallydev", {}).get("password", None) path = "https://rally1.rallydev.com/slm/webservice/v2.0/security/authorize" result = salt.utils.http.query( path, decode=True, decode_type="json", text=True, status=True, username=username, password=password, cookies=True, persist_session=True, opts=__opts__, ) if "dict" not in result: return None return result["dict"]["OperationResult"]["SecurityToken"] def _query( action=None, command=None, args=None, method="GET", header_dict=None, data=None ): """ Make a web call to RallyDev. """ token = _get_token() username = __opts__.get("rallydev", {}).get("username", None) password = __opts__.get("rallydev", {}).get("password", None) path = "https://rally1.rallydev.com/slm/webservice/v2.0/" if action: path += action if command: path += "/{}".format(command) log.debug("RallyDev URL: %s", path) if not isinstance(args, dict): args = {} args["key"] = token if header_dict is None: header_dict = {"Content-type": "application/json"} if method != "POST": header_dict["Accept"] = "application/json" decode = True if method == "DELETE": decode = False return_content = None result = salt.utils.http.query( path, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type="json", text=True, status=True, username=username, password=password, cookies=True, persist_session=True, opts=__opts__, ) log.debug("RallyDev Response Status Code: %s", result["status"]) if "error" in result: log.error(result["error"]) return [result["status"], result["error"]] return [result["status"], result.get("dict", {})] def list_items(name): """ List items of a particular type CLI Examples: .. code-block:: bash salt myminion rallydev.list_<item name>s salt myminion rallydev.list_users salt myminion rallydev.list_artifacts """ status, result = _query(action=name) return result def query_item(name, query_string, order="Rank"): """ Query a type of record for one or more items. Requires a valid query string. See https://rally1.rallydev.com/slm/doc/webservice/introduction.jsp for information on query syntax. CLI Example: .. code-block:: bash salt myminion rallydev.query_<item name> <query string> [<order>] salt myminion rallydev.query_task '(Name contains github)' salt myminion rallydev.query_task '(Name contains reactor)' Rank """ status, result = _query(action=name, args={"query": query_string, "order": order}) return result def show_item(name, id_): """ Show an item CLI Example: .. code-block:: bash salt myminion rallydev.show_<item name> <item id> """ status, result = _query(action=name, command=id_) return result def update_item(name, id_, field=None, value=None, postdata=None): """ Update an item. Either a field and a value, or a chunk of POST data, may be used, but not both. CLI Example: .. code-block:: bash salt myminion rallydev.update_<item name> <item id> field=<field> value=<value> salt myminion rallydev.update_<item name> <item id> postdata=<post data> """ if field and value: if postdata: raise SaltInvocationError( "Either a field and a value, or a chunk " "of POST data, may be specified, but not both." ) postdata = {name.title(): {field: value}} if postdata is None: raise SaltInvocationError( "Either a field and a value, or a chunk of POST data must be specified." ) status, result = _query( action=name, command=id_, method="POST", data=salt.utils.json.dumps(postdata), ) return result def show_artifact(id_): """ Show an artifact CLI Example: .. code-block:: bash salt myminion rallydev.show_artifact <artifact id> """ return show_item("artifact", id_) def list_users(): """ List the users CLI Example: .. code-block:: bash salt myminion rallydev.list_users """ return list_items("user") def show_user(id_): """ Show a user CLI Example: .. code-block:: bash salt myminion rallydev.show_user <user id> """ return show_item("user", id_) def update_user(id_, field, value): """ Update a user CLI Example: .. code-block:: bash salt myminion rallydev.update_user <user id> <field> <new value> """ return update_item("user", id_, field, value) def query_user(query_string, order="UserName"): """ Update a user CLI Example: .. code-block:: bash salt myminion rallydev.query_user '(Name contains Jo)' """ return query_item("user", query_string, order)
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/rallydev.py
0.575946
0.197058
rallydev.py
pypi
import os import re POLICY_MAP_DICT = { "Adaptive": "ad", "CLAROpt": "co", "LeastBlocks": "lb", "LeastIos": "li", "REquest": "re", "RoundRobin": "rr", "StreamIo": "si", "SymmOpt": "so", } POLICY_RE = re.compile(".*policy=([^;]+)") def has_powerpath(): if os.path.exists("/sbin/emcpreg"): return True return False def __virtual__(): """ Provide this only on Linux systems until proven to work elsewhere. """ try: kernel_grain = __grains__["kernel"] except Exception: # pylint: disable=broad-except return ( False, "The powerpath execution module cannot be loaded: unable to detect kernel" " grain.", ) if not has_powerpath(): return ( False, "The powerpath execution module cannot be loaded: the emcpreg binary is not" " available.", ) if kernel_grain == "Linux": return "powerpath" return ( False, "The powerpath execution module cannot be loaded: only available on Linux.", ) def list_licenses(): """ returns a list of applied powerpath license keys """ KEY_PATTERN = re.compile("Key (.*)") keys = [] out = __salt__["cmd.run"]("/sbin/emcpreg -list") for line in out.splitlines(): match = KEY_PATTERN.match(line) if not match: continue keys.append({"key": match.group(1)}) return keys def add_license(key): """ Add a license """ result = {"result": False, "retcode": -1, "output": ""} if not has_powerpath(): result["output"] = "PowerPath is not installed" return result cmd = "/sbin/emcpreg -add {}".format(key) ret = __salt__["cmd.run_all"](cmd, python_shell=True) result["retcode"] = ret["retcode"] if ret["retcode"] != 0: result["output"] = ret["stderr"] else: result["output"] = ret["stdout"] result["result"] = True return result def remove_license(key): """ Remove a license """ result = {"result": False, "retcode": -1, "output": ""} if not has_powerpath(): result["output"] = "PowerPath is not installed" return result cmd = "/sbin/emcpreg -remove {}".format(key) ret = __salt__["cmd.run_all"](cmd, python_shell=True) result["retcode"] = ret["retcode"] if ret["retcode"] != 0: result["output"] = ret["stderr"] else: result["output"] = ret["stdout"] result["result"] = True return result
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/powerpath.py
0.47098
0.1933
powerpath.py
pypi
import logging import salt.utils.platform try: import wmi import salt.utils.winapi HAS_LIBS = True except ImportError: HAS_LIBS = False log = logging.getLogger(__name__) def __virtual__(): """ Only works on Windows systems """ if not salt.utils.platform.is_windows(): return False, "Module win_dns_client: module only works on Windows systems" if not HAS_LIBS: return False, "Module win_dns_client: missing required libraries" return "win_dns_client" def get_dns_servers(interface="Local Area Connection"): """ Return a list of the configured DNS servers of the specified interface Args: interface (str): The name of the network interface. This is the name as it appears in the Control Panel under Network Connections Returns: list: A list of dns servers CLI Example: .. code-block:: bash salt '*' win_dns_client.get_dns_servers 'Local Area Connection' """ # remove any escape characters interface = interface.split("\\") interface = "".join(interface) with salt.utils.winapi.Com(): c = wmi.WMI() for iface in c.Win32_NetworkAdapter(NetEnabled=True): if interface == iface.NetConnectionID: iface_config = c.Win32_NetworkAdapterConfiguration( Index=iface.Index ).pop() try: return list(iface_config.DNSServerSearchOrder) except TypeError: return [] log.debug('Interface "%s" not found', interface) return False def rm_dns(ip, interface="Local Area Connection"): """ Remove the DNS server from the network interface CLI Example: .. code-block:: bash salt '*' win_dns_client.rm_dns <ip> <interface> """ cmd = ["netsh", "interface", "ip", "delete", "dns", interface, ip, "validate=no"] return __salt__["cmd.retcode"](cmd, python_shell=False) == 0 def add_dns(ip, interface="Local Area Connection", index=1): """ Add the DNS server to the network interface (index starts from 1) Note: if the interface DNS is configured by DHCP, all the DNS servers will be removed from the interface and the requested DNS will be the only one CLI Example: .. code-block:: bash salt '*' win_dns_client.add_dns <ip> <interface> <index> """ servers = get_dns_servers(interface) # Return False if could not find the interface if servers is False: return False # Return true if configured try: if servers[index - 1] == ip: return True except IndexError: pass # If configured in the wrong order delete it if ip in servers: rm_dns(ip, interface) cmd = [ "netsh", "interface", "ip", "add", "dns", interface, ip, "index={}".format(index), "validate=no", ] return __salt__["cmd.retcode"](cmd, python_shell=False) == 0 def dns_dhcp(interface="Local Area Connection"): """ Configure the interface to get its DNS servers from the DHCP server CLI Example: .. code-block:: bash salt '*' win_dns_client.dns_dhcp <interface> """ cmd = ["netsh", "interface", "ip", "set", "dns", interface, "source=dhcp"] return __salt__["cmd.retcode"](cmd, python_shell=False) == 0 def get_dns_config(interface="Local Area Connection"): """ Get the type of DNS configuration (dhcp / static). Args: interface (str): The name of the network interface. This is the Description in the Network Connection Details for the device Returns: bool: ``True`` if DNS is configured, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' win_dns_client.get_dns_config 'Local Area Connection' """ # remove any escape characters interface = interface.split("\\") interface = "".join(interface) with salt.utils.winapi.Com(): c = wmi.WMI() for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): if interface == iface.Description: return iface.DHCPEnabled
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/win_dns_client.py
0.714329
0.159152
win_dns_client.py
pypi
import logging try: from sense_hat import SenseHat has_sense_hat = True except (ImportError, NameError): _sensehat = None has_sense_hat = False log = logging.getLogger(__name__) def __virtual__(): """ Only load the module if SenseHat is available """ if has_sense_hat: try: _sensehat = SenseHat() except OSError: return ( False, "This module can only be used on a Raspberry Pi with a SenseHat.", ) rotation = __salt__["pillar.get"]("sensehat:rotation", 0) if rotation in [0, 90, 180, 270]: _sensehat.set_rotation(rotation, False) else: log.error("%s is not a valid rotation. Using default rotation.", rotation) return True return ( False, "The SenseHat execution module cannot be loaded: 'sense_hat' python library" " unavailable.", ) def set_pixels(pixels): """ Sets the entire LED matrix based on a list of 64 pixel values pixels A list of 64 ``[R, G, B]`` color values. """ _sensehat.set_pixels(pixels) return {"pixels": pixels} def get_pixels(): """ Returns a list of 64 smaller lists of ``[R, G, B]`` pixels representing the the currently displayed image on the LED matrix. .. note:: When using ``set_pixels`` the pixel values can sometimes change when you read them again using ``get_pixels``. This is because we specify each pixel element as 8 bit numbers (0 to 255) but when they're passed into the Linux frame buffer for the LED matrix the numbers are bit shifted down to fit into RGB 565. 5 bits for red, 6 bits for green and 5 bits for blue. The loss of binary precision when performing this conversion (3 bits lost for red, 2 for green and 3 for blue) accounts for the discrepancies you see. The ``get_pixels`` method provides an accurate representation of how the pixels end up in frame buffer memory after you have called ``set_pixels``. """ return _sensehat.get_pixels() def set_pixel(x, y, color): """ Sets a single pixel on the LED matrix to a specified color. x The x coordinate of the pixel. Ranges from 0 on the left to 7 on the right. y The y coordinate of the pixel. Ranges from 0 at the top to 7 at the bottom. color The new color of the pixel as a list of ``[R, G, B]`` values. CLI Example: .. code-block:: bash salt 'raspberry' sensehat.set_pixel 0 0 '[255, 0, 0]' """ _sensehat.set_pixel(x, y, color) return {"color": color} def get_pixel(x, y): """ Returns the color of a single pixel on the LED matrix. x The x coordinate of the pixel. Ranges from 0 on the left to 7 on the right. y The y coordinate of the pixel. Ranges from 0 at the top to 7 at the bottom. .. note:: Please read the note for ``get_pixels`` """ return _sensehat.get_pixel(x, y) def low_light(low_light=True): """ Sets the LED matrix to low light mode. Useful in a dark environment. CLI Example: .. code-block:: bash salt 'raspberry' sensehat.low_light salt 'raspberry' sensehat.low_light False """ _sensehat.low_light = low_light return {"low_light": low_light} def show_message( message, msg_type=None, text_color=None, back_color=None, scroll_speed=0.1 ): """ Displays a message on the LED matrix. message The message to display msg_type The type of the message. Changes the appearance of the message. Available types are:: error: red text warning: orange text success: green text info: blue text scroll_speed The speed at which the message moves over the LED matrix. This value represents the time paused for between shifting the text to the left by one column of pixels. Defaults to '0.1'. text_color The color in which the message is shown. Defaults to '[255, 255, 255]' (white). back_color The background color of the display. Defaults to '[0, 0, 0]' (black). CLI Example: .. code-block:: bash salt 'raspberry' sensehat.show_message 'Status ok' salt 'raspberry' sensehat.show_message 'Something went wrong' error salt 'raspberry' sensehat.show_message 'Red' text_color='[255, 0, 0]' salt 'raspberry' sensehat.show_message 'Hello world' None '[0, 0, 255]' '[255, 255, 0]' 0.2 """ text_color = text_color or [255, 255, 255] back_color = back_color or [0, 0, 0] color_by_type = { "error": [255, 0, 0], "warning": [255, 100, 0], "success": [0, 255, 0], "info": [0, 0, 255], } if msg_type in color_by_type: text_color = color_by_type[msg_type] _sensehat.show_message(message, scroll_speed, text_color, back_color) return {"message": message} def show_letter(letter, text_color=None, back_color=None): """ Displays a single letter on the LED matrix. letter The letter to display text_color The color in which the letter is shown. Defaults to '[255, 255, 255]' (white). back_color The background color of the display. Defaults to '[0, 0, 0]' (black). CLI Example: .. code-block:: bash salt 'raspberry' sensehat.show_letter O salt 'raspberry' sensehat.show_letter X '[255, 0, 0]' salt 'raspberry' sensehat.show_letter B '[0, 0, 255]' '[255, 255, 0]' """ text_color = text_color or [255, 255, 255] back_color = back_color or [0, 0, 0] _sensehat.show_letter(letter, text_color, back_color) return {"letter": letter} def show_image(image): """ Displays an 8 x 8 image on the LED matrix. image The path to the image to display. The image must be 8 x 8 pixels in size. CLI Example: .. code-block:: bash salt 'raspberry' sensehat.show_image /tmp/my_image.png """ return _sensehat.load_image(image) def clear(color=None): """ Sets the LED matrix to a single color or turns all LEDs off. CLI Example: .. code-block:: bash salt 'raspberry' sensehat.clear salt 'raspberry' sensehat.clear '[255, 0, 0]' """ if color is None: _sensehat.clear() else: _sensehat.clear(color) return {"color": color} def get_humidity(): """ Get the percentage of relative humidity from the humidity sensor. """ return _sensehat.get_humidity() def get_pressure(): """ Gets the current pressure in Millibars from the pressure sensor. """ return _sensehat.get_pressure() def get_temperature(): """ Gets the temperature in degrees Celsius from the humidity sensor. Equivalent to calling ``get_temperature_from_humidity``. If you get strange results try using ``get_temperature_from_pressure``. """ return _sensehat.get_temperature() def get_temperature_from_humidity(): """ Gets the temperature in degrees Celsius from the humidity sensor. """ return _sensehat.get_temperature_from_humidity() def get_temperature_from_pressure(): """ Gets the temperature in degrees Celsius from the pressure sensor. """ return _sensehat.get_temperature_from_pressure()
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/sensehat.py
0.792103
0.52902
sensehat.py
pypi
import logging import os import re import salt.utils.files import salt.utils.path import salt.utils.stringutils import salt.utils.versions log = logging.getLogger(__name__) __func_alias__ = {"set_": "set"} # Define the module's virtual name __virtualname__ = "debconf" def __virtual__(): """ Confirm this module is on a Debian based system and that debconf-utils is installed. """ if __grains__["os_family"] != "Debian": return ( False, "The debconfmod module could not be loaded: unsupported OS family", ) if salt.utils.path.which("debconf-get-selections") is None: return ( False, "The debconfmod module could not be loaded: " "debconf-utils is not installed.", ) return __virtualname__ def _unpack_lines(out): """ Unpack the debconf lines """ rexp = ( "(?ms)" "^(?P<package>[^#]\\S+)[\t ]+" "(?P<question>\\S+)[\t ]+" "(?P<type>\\S+)[\t ]+" "(?P<value>[^\n]*)$" ) lines = re.findall(rexp, out) return lines def get_selections(fetchempty=True): """ Answers to debconf questions for all packages in the following format:: {'package': [['question', 'type', 'value'], ...]} CLI Example: .. code-block:: bash salt '*' debconf.get_selections """ selections = {} cmd = "debconf-get-selections" out = __salt__["cmd.run_stdout"](cmd) lines = _unpack_lines(out) for line in lines: package, question, type_, value = line if fetchempty or value: (selections.setdefault(package, []).append([question, type_, value])) return selections def show(name): """ Answers to debconf questions for a package in the following format:: [['question', 'type', 'value'], ...] If debconf doesn't know about a package, we return None. CLI Example: .. code-block:: bash salt '*' debconf.show <package name> """ selections = get_selections() result = selections.get(name) return result def _set_file(path): """ Execute the set selections command for debconf """ cmd = "debconf-set-selections {}".format(path) __salt__["cmd.run_stdout"](cmd, python_shell=False) def set_(package, question, type, value, *extra): """ Set answers to debconf questions for a package. CLI Example: .. code-block:: bash salt '*' debconf.set <package> <question> <type> <value> [<value> ...] """ if extra: value = " ".join((value,) + tuple(extra)) fd_, fname = salt.utils.files.mkstemp(prefix="salt-", close_fd=False) line = "{} {} {} {}".format(package, question, type, value) os.write(fd_, salt.utils.stringutils.to_bytes(line)) os.close(fd_) _set_file(fname) os.unlink(fname) return True def set_template(path, template, context, defaults, saltenv="base", **kwargs): """ Set answers to debconf questions from a template. path location of the file containing the package selections template template format context variables to add to the template environment default default values for the template environment CLI Example: .. code-block:: bash salt '*' debconf.set_template salt://pathto/pkg.selections.jinja jinja None None """ path = __salt__["cp.get_template"]( path=path, dest=None, template=template, saltenv=saltenv, context=context, defaults=defaults, **kwargs ) return set_file(path, saltenv, **kwargs) def set_file(path, saltenv="base", **kwargs): """ Set answers to debconf questions from a file. CLI Example: .. code-block:: bash salt '*' debconf.set_file salt://pathto/pkg.selections """ if "__env__" in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop("__env__") path = __salt__["cp.cache_file"](path, saltenv) if path: _set_file(path) return True return False
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/debconfmod.py
0.432303
0.151467
debconfmod.py
pypi
r""" Manage the Windows registry Hives ----- Hives are the main sections of the registry and all begin with the word HKEY. - HKEY_LOCAL_MACHINE - HKEY_CURRENT_USER - HKEY_USER Keys ---- Keys are the folders in the registry. Keys can have many nested subkeys. Keys can have a value assigned to them under the (Default) When passing a key on the CLI it must be quoted correctly depending on the backslashes being used (``\`` vs ``\\``). The following are valid methods of passing the key on the CLI: Using single backslashes: ``"SOFTWARE\Python"`` ``'SOFTWARE\Python'`` (will not work on a Windows Master) Using double backslashes: ``SOFTWARE\\Python`` ----------------- Values or Entries ----------------- Values or Entries are the name/data pairs beneath the keys and subkeys. All keys have a default name/data pair. The name is ``(Default)`` with a displayed value of ``(value not set)``. The actual value is Null. Example ------- The following example is an export from the Windows startup portion of the registry: .. code-block:: bash [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run] "RTHDVCPL"="\"C:\\Program Files\\Realtek\\Audio\\HDA\\RtkNGUI64.exe\" -s" "NvBackend"="\"C:\\Program Files (x86)\\NVIDIA Corporation\\Update Core\\NvBackend.exe\"" "BTMTrayAgent"="rundll32.exe \"C:\\Program Files (x86)\\Intel\\Bluetooth\\btmshellex.dll\",TrayApp" In this example these are the values for each: Hive: ``HKEY_LOCAL_MACHINE`` Key and subkeys: ``SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run`` Value: - There are 3 value names: - `RTHDVCPL` - `NvBackend` - `BTMTrayAgent` - Each value name has a corresponding value :depends: - salt.utils.win_reg """ # When production windows installer is using Python 3, Python 2 code can be removed import logging import salt.utils.platform from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = "reg" def __virtual__(): """ Only works on Windows systems with PyWin32 """ if not salt.utils.platform.is_windows(): return ( False, "reg execution module failed to load: " "The module will only run on Windows systems", ) if "reg.read_value" not in __utils__: return ( False, "reg execution module failed to load: The reg salt util is unavailable", ) return __virtualname__ def key_exists(hive, key, use_32bit_registry=False): r""" Check that the key is found in the registry. This refers to keys and not value/data pairs. Args: hive (str): The hive to connect to key (str): The key to check use_32bit_registry (bool): Look in the 32bit portion of the registry Returns: bool: True if exists, otherwise False CLI Example: .. code-block:: bash salt '*' reg.key_exists HKLM SOFTWARE\Microsoft """ return __utils__["reg.key_exists"]( hive=hive, key=key, use_32bit_registry=use_32bit_registry ) def value_exists(hive, key, vname, use_32bit_registry=False): r""" Check that the value/data pair is found in the registry. .. versionadded:: 3000 Args: hive (str): The hive to connect to key (str): The key to check in vname (str): The name of the value/data pair you're checking use_32bit_registry (bool): Look in the 32bit portion of the registry Returns: bool: True if exists, otherwise False CLI Example: .. code-block:: bash salt '*' reg.value_exists HKLM SOFTWARE\Microsoft\Windows\CurrentVersion CommonFilesDir """ return __utils__["reg.value_exists"]( hive=hive, key=key, vname=vname, use_32bit_registry=use_32bit_registry ) def broadcast_change(): """ Refresh the windows environment. .. note:: This will only effect new processes and windows. Services will not see the change until the system restarts. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' reg.broadcast_change """ return salt.utils.win_functions.broadcast_setting_change("Environment") def list_keys(hive, key=None, use_32bit_registry=False): """ Enumerates the subkeys in a registry key or hive. Args: hive (str): The name of the hive. Can be one of the following: - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. If a key is not passed, the keys under the hive will be returned. use_32bit_registry (bool): Accesses the 32bit portion of the registry on 64 bit installations. On 32bit machines this is ignored. Returns: list: A list of keys/subkeys under the hive or key. CLI Example: .. code-block:: bash salt '*' reg.list_keys HKLM 'SOFTWARE' """ return __utils__["reg.list_keys"]( hive=hive, key=key, use_32bit_registry=use_32bit_registry ) def list_values(hive, key=None, use_32bit_registry=False): r""" Enumerates the values in a registry key or hive. .. note:: The ``(Default)`` value will only be returned if it is set, otherwise it will not be returned in the list of values. Args: hive (str): The name of the hive. Can be one of the following: - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. If a key is not passed, the values under the hive will be returned. use_32bit_registry (bool): Accesses the 32bit portion of the registry on 64 bit installations. On 32bit machines this is ignored. Returns: list: A list of values under the hive or key. CLI Example: .. code-block:: bash salt '*' reg.list_values HKLM 'SYSTEM\\CurrentControlSet\\Services\\Tcpip' """ return __utils__["reg.list_values"]( hive=hive, key=key, use_32bit_registry=use_32bit_registry ) def read_value(hive, key, vname=None, use_32bit_registry=False): r""" Reads a registry value entry or the default value for a key. To read the default value, don't pass ``vname`` Args: hive (str): The name of the hive. Can be one of the following: - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. vname (str): The value name. These are the individual name/data pairs under the key. If not passed, the key (Default) value will be returned. use_32bit_registry (bool): Accesses the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. Returns: dict: A dictionary containing the passed settings as well as the value_data if successful. If unsuccessful, sets success to False. bool: Returns False if the key is not found If vname is not passed: - Returns the first unnamed value (Default) as a string. - Returns none if first unnamed value is empty. CLI Example: The following will get the value of the ``version`` value name in the ``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key .. code-block:: bash salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt' 'version' CLI Example: The following will get the default value of the ``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key .. code-block:: bash salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt' """ return __utils__["reg.read_value"]( hive=hive, key=key, vname=vname, use_32bit_registry=use_32bit_registry ) def set_value( hive, key, vname=None, vdata=None, vtype="REG_SZ", use_32bit_registry=False, volatile=False, ): """ Sets a value in the registry. If ``vname`` is passed, it will be the value for that value name, otherwise it will be the default value for the specified key Args: hive (str): The name of the hive. Can be one of the following - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. vname (str): The value name. These are the individual name/data pairs under the key. If not passed, the key (Default) value will be set. vdata (str, int, list, bytes): The value you'd like to set. If a value name (vname) is passed, this will be the data for that value name. If not, this will be the (Default) value for the key. The type of data this parameter expects is determined by the value type specified in ``vtype``. The correspondence is as follows: - REG_BINARY: Binary data (str in Py2, bytes in Py3) - REG_DWORD: int - REG_EXPAND_SZ: str - REG_MULTI_SZ: list of str - REG_QWORD: int - REG_SZ: str .. note:: When setting REG_BINARY, string data will be converted to binary. .. note:: The type for the (Default) value is always REG_SZ and cannot be changed. .. note:: This parameter is optional. If ``vdata`` is not passed, the Key will be created with no associated item/value pairs. vtype (str): The value type. The possible values of the vtype parameter are indicated above in the description of the vdata parameter. use_32bit_registry (bool): Sets the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. volatile (bool): When this parameter has a value of True, the registry key will be made volatile (i.e. it will not persist beyond a system reset or shutdown). This parameter only has an effect when a key is being created and at no other time. Returns: bool: True if successful, otherwise False CLI Example: This will set the version value to 2015.5.2 in the SOFTWARE\\Salt key in the HKEY_LOCAL_MACHINE hive .. code-block:: bash salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'version' '2015.5.2' CLI Example: This function is strict about the type of vdata. For instance this example will fail because vtype has a value of REG_SZ and vdata has a type of int (as opposed to str as expected). .. code-block:: bash salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' 1.2 CLI Example: In this next example vdata is properly quoted and should succeed. .. code-block:: bash salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' vtype=REG_SZ vdata="'1.2'" CLI Example: This is an example of using vtype REG_BINARY. .. code-block:: bash salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'bin_data' vtype=REG_BINARY vdata='Salty Data' CLI Example: An example of using vtype REG_MULTI_SZ is as follows: .. code-block:: bash salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'list_data' vtype=REG_MULTI_SZ vdata='["Salt", "is", "great"]' """ return __utils__["reg.set_value"]( hive=hive, key=key, vname=vname, vdata=vdata, vtype=vtype, use_32bit_registry=use_32bit_registry, volatile=volatile, ) def delete_key_recursive(hive, key, use_32bit_registry=False): r""" .. versionadded:: 2015.5.4 Delete a registry key to include all subkeys and value/data pairs. Args: hive (str): The name of the hive. Can be one of the following - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key to remove (looks like a path) use_32bit_registry (bool): Deletes the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. Returns: dict: A dictionary listing the keys that deleted successfully as well as those that failed to delete. CLI Example: The following example will remove ``delete_me`` and all its subkeys from the ``SOFTWARE`` key in ``HKEY_LOCAL_MACHINE``: .. code-block:: bash salt '*' reg.delete_key_recursive HKLM SOFTWARE\\delete_me """ return __utils__["reg.delete_key_recursive"]( hive=hive, key=key, use_32bit_registry=use_32bit_registry ) def delete_value(hive, key, vname=None, use_32bit_registry=False): r""" Delete a registry value entry or the default value for a key. Args: hive (str): The name of the hive. Can be one of the following - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. vname (str): The value name. These are the individual name/data pairs under the key. If not passed, the key (Default) value will be deleted. use_32bit_registry (bool): Deletes the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' reg.delete_value HKEY_CURRENT_USER 'SOFTWARE\\Salt' 'version' """ return __utils__["reg.delete_value"]( hive=hive, key=key, vname=vname, use_32bit_registry=use_32bit_registry ) def import_file(source, use_32bit_registry=False): """ Import registry settings from a Windows ``REG`` file by invoking ``REG.EXE``. .. versionadded:: 2018.3.0 Args: source (str): The full path of the ``REG`` file. This can be either a local file path or a URL type supported by salt (e.g. ``salt://salt_master_path``) use_32bit_registry (bool): If the value of this parameter is ``True`` then the ``REG`` file will be imported into the Windows 32 bit registry. Otherwise the Windows 64 bit registry will be used. Returns: bool: True if successful, otherwise an error is raised Raises: ValueError: If the value of ``source`` is an invalid path or otherwise causes ``cp.cache_file`` to return ``False`` CommandExecutionError: If ``reg.exe`` exits with a non-0 exit code CLI Example: .. code-block:: bash salt machine1 reg.import_file salt://win/printer_config/110_Canon/postinstall_config.reg """ cache_path = __salt__["cp.cache_file"](source) if not cache_path: error_msg = "File/URL '{}' probably invalid.".format(source) raise ValueError(error_msg) if use_32bit_registry: word_sz_txt = "32" else: word_sz_txt = "64" cmd = 'reg import "{}" /reg:{}'.format(cache_path, word_sz_txt) cmd_ret_dict = __salt__["cmd.run_all"](cmd, python_shell=True) retcode = cmd_ret_dict["retcode"] if retcode != 0: raise CommandExecutionError("reg.exe import failed", info=cmd_ret_dict) return True
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/reg.py
0.8398
0.406862
reg.py
pypi
import collections # Import Salt Modules import salt.utils.path Plugin = collections.namedtuple("Plugin", "name status update versino") def __virtual__(): if salt.utils.path.which("wp"): return True return (False, "Missing dependency: wp") def _get_plugins(stuff): return Plugin(stuff) def list_plugins(path, user): """ List plugins in an installed wordpress path path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.list_plugins /var/www/html apache """ ret = [] resp = __salt__["cmd.shell"]("wp --path={} plugin list".format(path), runas=user) for line in resp.split("\n")[1:]: ret.append(line.split("\t")) return [plugin.__dict__ for plugin in map(_get_plugins, ret)] def show_plugin(name, path, user): """ Show a plugin in a wordpress install and check if it is installed name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.show_plugin HyperDB /var/www/html apache """ ret = {"name": name} resp = __salt__["cmd.shell"]( "wp --path={} plugin status {}".format(path, name), runas=user ).split("\n") for line in resp: if "Status" in line: ret["status"] = line.split(" ")[-1].lower() elif "Version" in line: ret["version"] = line.split(" ")[-1].lower() return ret def activate(name, path, user): """ Activate a wordpress plugin name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.activate HyperDB /var/www/html apache """ check = show_plugin(name, path, user) if check["status"] == "active": # already active return None resp = __salt__["cmd.shell"]( "wp --path={} plugin activate {}".format(path, name), runas=user ) if "Success" in resp: return True elif show_plugin(name, path, user)["status"] == "active": return True return False def deactivate(name, path, user): """ Deactivate a wordpress plugin name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.deactivate HyperDB /var/www/html apache """ check = show_plugin(name, path, user) if check["status"] == "inactive": # already inactive return None resp = __salt__["cmd.shell"]( "wp --path={} plugin deactivate {}".format(path, name), runas=user ) if "Success" in resp: return True elif show_plugin(name, path, user)["status"] == "inactive": return True return False def is_installed(path, user=None): """ Check if wordpress is installed and setup path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.is_installed /var/www/html apache """ retcode = __salt__["cmd.retcode"]( "wp --path={} core is-installed".format(path), runas=user ) if retcode == 0: return True return False def install(path, user, admin_user, admin_password, admin_email, title, url): """ Run the initial setup functions for a wordpress install path path to wordpress install location user user to run the command as admin_user Username for the Administrative user for the wordpress install admin_password Initial Password for the Administrative user for the wordpress install admin_email Email for the Administrative user for the wordpress install title Title of the wordpress website for the wordpress install url Url for the wordpress install CLI Example: .. code-block:: bash salt '*' wordpress.install /var/www/html apache dwallace password123 \ dwallace@example.com "Daniel's Awesome Blog" https://blog.dwallace.com """ retcode = __salt__["cmd.retcode"]( 'wp --path={} core install --title="{}" --admin_user={} ' "--admin_password='{}' --admin_email={} --url={}".format( path, title, admin_user, admin_password, admin_email, url ), runas=user, ) if retcode == 0: return True return False
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/wordpress.py
0.563378
0.176299
wordpress.py
pypi
import logging import salt.modules.cmdmod import salt.utils.args import salt.utils.path import salt.utils.platform import salt.utils.versions from salt.utils.odict import OrderedDict __virtualname__ = "zfs" log = logging.getLogger(__name__) # Function alias to set mapping. __func_alias__ = { "list_": "list", } def __virtual__(): """ Only load when the platform has zfs support """ if __grains__.get("zfs_support"): return __virtualname__ else: return False, "The zfs module cannot be loaded: zfs not supported" def exists(name, **kwargs): """ Check if a ZFS filesystem or volume or snapshot exists. name : string name of dataset type : string also check if dataset is of a certain type, valid choices are: filesystem, snapshot, volume, bookmark, or all. .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.exists myzpool/mydataset salt '*' zfs.exists myzpool/myvolume type=volume """ ## Configure command # NOTE: initialize the defaults opts = {} # NOTE: set extra config from kwargs if kwargs.get("type", False): opts["-t"] = kwargs.get("type") ## Check if 'name' of 'type' exists res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="list", opts=opts, target=name, ), python_shell=False, ignore_retcode=True, ) return res["retcode"] == 0 def create(name, **kwargs): """ Create a ZFS File System. name : string name of dataset or volume volume_size : string if specified, a zvol will be created instead of a dataset sparse : boolean create sparse volume create_parent : boolean creates all the non-existing parent datasets. any property specified on the command line using the -o option is ignored. properties : dict additional zfs properties (-o) .. note:: ZFS properties can be specified at the time of creation of the filesystem by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary:: properties="{'property1': 'value1', 'property2': 'value2'}" .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.create myzpool/mydataset [create_parent=True|False] salt '*' zfs.create myzpool/mydataset properties="{'mountpoint': '/export/zfs', 'sharenfs': 'on'}" salt '*' zfs.create myzpool/volume volume_size=1G [sparse=True|False]` salt '*' zfs.create myzpool/volume volume_size=1G properties="{'volblocksize': '512'}" [sparse=True|False] """ ## Configure command # NOTE: initialize the defaults flags = [] opts = {} # NOTE: push filesystem properties filesystem_properties = kwargs.get("properties", {}) # NOTE: set extra config from kwargs if kwargs.get("create_parent", False): flags.append("-p") if kwargs.get("sparse", False) and kwargs.get("volume_size", None): flags.append("-s") if kwargs.get("volume_size", None): opts["-V"] = __utils__["zfs.to_size"]( kwargs.get("volume_size"), convert_to_human=False ) ## Create filesystem/volume res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="create", flags=flags, opts=opts, filesystem_properties=filesystem_properties, target=name, ), python_shell=False, ) return __utils__["zfs.parse_command_result"](res, "created") def destroy(name, **kwargs): """ Destroy a ZFS File System. name : string name of dataset, volume, or snapshot force : boolean force an unmount of any file systems using the unmount -f command. recursive : boolean recursively destroy all children. (-r) recursive_all : boolean recursively destroy all dependents, including cloned file systems outside the target hierarchy. (-R) .. warning:: watch out when using recursive and recursive_all .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.destroy myzpool/mydataset [force=True|False] """ ## Configure command # NOTE: initialize the defaults flags = [] # NOTE: set extra config from kwargs if kwargs.get("force", False): flags.append("-f") if kwargs.get("recursive_all", False): flags.append("-R") if kwargs.get("recursive", False): flags.append("-r") ## Destroy filesystem/volume/snapshot/... res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="destroy", flags=flags, target=name, ), python_shell=False, ) return __utils__["zfs.parse_command_result"](res, "destroyed") def rename(name, new_name, **kwargs): """ Rename or Relocate a ZFS File System. name : string name of dataset, volume, or snapshot new_name : string new name of dataset, volume, or snapshot force : boolean force unmount any filesystems that need to be unmounted in the process. create_parent : boolean creates all the nonexistent parent datasets. Datasets created in this manner are automatically mounted according to the mountpoint property inherited from their parent. recursive : boolean recursively rename the snapshots of all descendent datasets. snapshots are the only dataset that can be renamed recursively. .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.rename myzpool/mydataset myzpool/renameddataset """ ## Configure command # NOTE: initialize the defaults flags = [] target = [] # NOTE: set extra config from kwargs if __utils__["zfs.is_snapshot"](name): if kwargs.get("create_parent", False): log.warning( "zfs.rename - create_parent=True cannot be used with snapshots." ) if kwargs.get("force", False): log.warning("zfs.rename - force=True cannot be used with snapshots.") if kwargs.get("recursive", False): flags.append("-r") else: if kwargs.get("create_parent", False): flags.append("-p") if kwargs.get("force", False): flags.append("-f") if kwargs.get("recursive", False): log.warning("zfs.rename - recursive=True can only be used with snapshots.") # NOTE: update target target.append(name) target.append(new_name) ## Rename filesystem/volume/snapshot/... res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="rename", flags=flags, target=target, ), python_shell=False, ) return __utils__["zfs.parse_command_result"](res, "renamed") def list_(name=None, **kwargs): """ Return a list of all datasets or a specified dataset on the system and the values of their used, available, referenced, and mountpoint properties. name : string name of dataset, volume, or snapshot recursive : boolean recursively list children depth : int limit recursion to depth properties : string comma-separated list of properties to list, the name property will always be added type : string comma-separated list of types to display, where type is one of filesystem, snapshot, volume, bookmark, or all. sort : string property to sort on (default = name) order : string [ascending|descending] sort order (default = ascending) parsable : boolean display numbers in parsable (exact) values .. versionadded:: 2018.3.0 .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' zfs.list salt '*' zfs.list myzpool/mydataset [recursive=True|False] salt '*' zfs.list myzpool/mydataset properties="sharenfs,mountpoint" """ ret = OrderedDict() ## update properties # NOTE: properties should be a list properties = kwargs.get("properties", "used,avail,refer,mountpoint") if not isinstance(properties, list): properties = properties.split(",") # NOTE: name should be first property # we loop here because there 'name' can be in the list # multiple times. while "name" in properties: properties.remove("name") properties.insert(0, "name") ## Configure command # NOTE: initialize the defaults flags = ["-H"] opts = {} # NOTE: set extra config from kwargs if kwargs.get("recursive", False): flags.append("-r") if kwargs.get("recursive", False) and kwargs.get("depth", False): opts["-d"] = kwargs.get("depth") if kwargs.get("type", False): opts["-t"] = kwargs.get("type") kwargs_sort = kwargs.get("sort", False) if kwargs_sort and kwargs_sort in properties: if kwargs.get("order", "ascending").startswith("a"): opts["-s"] = kwargs_sort else: opts["-S"] = kwargs_sort if isinstance(properties, list): # NOTE: There can be only one -o and it takes a comma-separated list opts["-o"] = ",".join(properties) else: opts["-o"] = properties ## parse zfs list res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="list", flags=flags, opts=opts, target=name, ), python_shell=False, ) if res["retcode"] == 0: for ds in res["stdout"].splitlines(): if kwargs.get("parsable", True): ds_data = __utils__["zfs.from_auto_dict"]( OrderedDict(list(zip(properties, ds.split("\t")))), ) else: ds_data = __utils__["zfs.to_auto_dict"]( OrderedDict(list(zip(properties, ds.split("\t")))), convert_to_human=True, ) ret[ds_data["name"]] = ds_data del ret[ds_data["name"]]["name"] else: return __utils__["zfs.parse_command_result"](res) return ret def list_mount(): """ List mounted zfs filesystems .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt '*' zfs.list_mount """ ## List mounted filesystem res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="mount", ), python_shell=False, ) if res["retcode"] == 0: ret = OrderedDict() for mount in res["stdout"].splitlines(): mount = mount.split() ret[mount[0]] = mount[-1] return ret else: return __utils__["zfs.parse_command_result"](res) def mount(name=None, **kwargs): """ Mounts ZFS file systems name : string name of the filesystem, having this set to None will mount all filesystems. (this is the default) overlay : boolean perform an overlay mount. options : string optional comma-separated list of mount options to use temporarily for the duration of the mount. .. versionadded:: 2016.3.0 .. versionchanged:: 2018.3.1 .. warning:: Passing '-a' as name is deprecated and will be removed in 3001. CLI Example: .. code-block:: bash salt '*' zfs.mount salt '*' zfs.mount myzpool/mydataset salt '*' zfs.mount myzpool/mydataset options=ro """ ## Configure command # NOTE: initialize the defaults flags = [] opts = {} # NOTE: set extra config from kwargs if kwargs.get("overlay", False): flags.append("-O") if kwargs.get("options", False): opts["-o"] = kwargs.get("options") ## Mount filesystem res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="mount", flags=flags, opts=opts, target=name, ), python_shell=False, ) return __utils__["zfs.parse_command_result"](res, "mounted") def unmount(name, **kwargs): """ Unmounts ZFS file systems name : string name of the filesystem, you can use None to unmount all mounted filesystems. force : boolean forcefully unmount the file system, even if it is currently in use. .. warning:: Using ``-a`` for the name parameter will probably break your system, unless your rootfs is not on zfs. .. versionadded:: 2016.3.0 .. versionchanged:: 2018.3.1 .. warning:: Passing '-a' as name is deprecated and will be removed in 3001. CLI Example: .. code-block:: bash salt '*' zfs.unmount myzpool/mydataset [force=True|False] """ ## Configure command # NOTE: initialize the defaults flags = [] # NOTE: set extra config from kwargs if kwargs.get("force", False): flags.append("-f") if name in [None, "-a"]: # NOTE: still accept '-a' as name for backwards compatibility # until Salt 3001 this should just simplify # this to just set '-a' if name is not set. flags.append("-a") name = None ## Unmount filesystem res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="unmount", flags=flags, target=name, ), python_shell=False, ) return __utils__["zfs.parse_command_result"](res, "unmounted") def inherit(prop, name, **kwargs): """ Clears the specified property prop : string name of property name : string name of the filesystem, volume, or snapshot recursive : boolean recursively inherit the given property for all children. revert : boolean revert the property to the received value if one exists; otherwise operate as if the -S option was not specified. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.inherit canmount myzpool/mydataset [recursive=True|False] """ ## Configure command # NOTE: initialize the defaults flags = [] # NOTE: set extra config from kwargs if kwargs.get("recursive", False): flags.append("-r") if kwargs.get("revert", False): flags.append("-S") ## Inherit property res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="inherit", flags=flags, property_name=prop, target=name, ), python_shell=False, ) return __utils__["zfs.parse_command_result"](res, "inherited") def diff(name_a, name_b=None, **kwargs): """ Display the difference between a snapshot of a given filesystem and another snapshot of that filesystem from a later time or the current contents of the filesystem. name_a : string name of snapshot name_b : string (optional) name of snapshot or filesystem show_changetime : boolean display the path's inode change time as the first column of output. (default = True) show_indication : boolean display an indication of the type of file. (default = True) parsable : boolean if true we don't parse the timestamp to a more readable date (default = True) .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.diff myzpool/mydataset@yesterday myzpool/mydataset """ ## Configure command # NOTE: initialize the defaults flags = ["-H"] target = [] # NOTE: set extra config from kwargs if kwargs.get("show_changetime", True): flags.append("-t") if kwargs.get("show_indication", True): flags.append("-F") # NOTE: update target target.append(name_a) if name_b: target.append(name_b) ## Diff filesystem/snapshot res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="diff", flags=flags, target=target, ), python_shell=False, ) if res["retcode"] != 0: return __utils__["zfs.parse_command_result"](res) else: if not kwargs.get("parsable", True) and kwargs.get("show_changetime", True): ret = OrderedDict() for entry in res["stdout"].splitlines(): entry = entry.split() entry_timestamp = __utils__["dateutils.strftime"]( entry[0], "%Y-%m-%d.%H:%M:%S.%f" ) entry_data = "\t\t".join(entry[1:]) ret[entry_timestamp] = entry_data else: ret = res["stdout"].splitlines() return ret def rollback(name, **kwargs): """ Roll back the given dataset to a previous snapshot. name : string name of snapshot recursive : boolean destroy any snapshots and bookmarks more recent than the one specified. recursive_all : boolean destroy any more recent snapshots and bookmarks, as well as any clones of those snapshots. force : boolean used with the -R option to force an unmount of any clone file systems that are to be destroyed. .. warning:: When a dataset is rolled back, all data that has changed since the snapshot is discarded, and the dataset reverts to the state at the time of the snapshot. By default, the command refuses to roll back to a snapshot other than the most recent one. In order to do so, all intermediate snapshots and bookmarks must be destroyed by specifying the -r option. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.rollback myzpool/mydataset@yesterday """ ## Configure command # NOTE: initialize the defaults flags = [] # NOTE: set extra config from kwargs if kwargs.get("recursive_all", False): flags.append("-R") if kwargs.get("recursive", False): flags.append("-r") if kwargs.get("force", False): if kwargs.get("recursive_all", False) or kwargs.get("recursive", False): flags.append("-f") else: log.warning( "zfs.rollback - force=True can only be used with recursive_all=True or" " recursive=True" ) ## Rollback to snapshot res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="rollback", flags=flags, target=name, ), python_shell=False, ) return __utils__["zfs.parse_command_result"](res, "rolledback") def clone(name_a, name_b, **kwargs): """ Creates a clone of the given snapshot. name_a : string name of snapshot name_b : string name of filesystem or volume create_parent : boolean creates all the non-existing parent datasets. any property specified on the command line using the -o option is ignored. properties : dict additional zfs properties (-o) .. note:: ZFS properties can be specified at the time of creation of the filesystem by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary:: properties="{'property1': 'value1', 'property2': 'value2'}" .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.clone myzpool/mydataset@yesterday myzpool/mydataset_yesterday """ ## Configure command # NOTE: initialize the defaults flags = [] target = [] # NOTE: push filesystem properties filesystem_properties = kwargs.get("properties", {}) # NOTE: set extra config from kwargs if kwargs.get("create_parent", False): flags.append("-p") # NOTE: update target target.append(name_a) target.append(name_b) ## Clone filesystem/volume res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="clone", flags=flags, filesystem_properties=filesystem_properties, target=target, ), python_shell=False, ) return __utils__["zfs.parse_command_result"](res, "cloned") def promote(name): """ Promotes a clone file system to no longer be dependent on its "origin" snapshot. .. note:: This makes it possible to destroy the file system that the clone was created from. The clone parent-child dependency relationship is reversed, so that the origin file system becomes a clone of the specified file system. The snapshot that was cloned, and any snapshots previous to this snapshot, are now owned by the promoted clone. The space they use moves from the origin file system to the promoted clone, so enough space must be available to accommodate these snapshots. No new space is consumed by this operation, but the space accounting is adjusted. The promoted clone must not have any conflicting snapshot names of its own. The rename subcommand can be used to rename any conflicting snapshots. name : string name of clone-filesystem .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.promote myzpool/myclone """ ## Promote clone res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="promote", target=name, ), python_shell=False, ) return __utils__["zfs.parse_command_result"](res, "promoted") def bookmark(snapshot, bookmark): """ Creates a bookmark of the given snapshot .. note:: Bookmarks mark the point in time when the snapshot was created, and can be used as the incremental source for a zfs send command. This feature must be enabled to be used. See zpool-features(5) for details on ZFS feature flags and the bookmarks feature. snapshot : string name of snapshot to bookmark bookmark : string name of bookmark .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.bookmark myzpool/mydataset@yesterday myzpool/mydataset#complete """ # abort if we do not have feature flags if not __utils__["zfs.has_feature_flags"](): return OrderedDict([("error", "bookmarks are not supported")]) ## Configure command # NOTE: initialize the defaults target = [] # NOTE: update target target.append(snapshot) target.append(bookmark) ## Bookmark snapshot res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="bookmark", target=target, ), python_shell=False, ) return __utils__["zfs.parse_command_result"](res, "bookmarked") def holds(snapshot, **kwargs): """ Lists all existing user references for the given snapshot or snapshots. snapshot : string name of snapshot recursive : boolean lists the holds that are set on the named descendent snapshots also. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.holds myzpool/mydataset@baseline """ ## Configure command # NOTE: initialize the defaults flags = ["-H"] target = [] # NOTE: set extra config from kwargs if kwargs.get("recursive", False): flags.append("-r") # NOTE: update target target.append(snapshot) ## Lookup holds res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="holds", flags=flags, target=target, ), python_shell=False, ) ret = __utils__["zfs.parse_command_result"](res) if res["retcode"] == 0: for hold in res["stdout"].splitlines(): hold_data = OrderedDict( list( zip( ["name", "tag", "timestamp"], hold.split("\t"), ) ) ) ret[hold_data["tag"].strip()] = hold_data["timestamp"] return ret def hold(tag, *snapshot, **kwargs): """ Adds a single reference, named with the tag argument, to the specified snapshot or snapshots. .. note:: Each snapshot has its own tag namespace, and tags must be unique within that space. If a hold exists on a snapshot, attempts to destroy that snapshot by using the zfs destroy command return EBUSY. tag : string name of tag snapshot : string name of snapshot(s) recursive : boolean specifies that a hold with the given tag is applied recursively to the snapshots of all descendent file systems. .. versionadded:: 2016.3.0 .. versionchanged:: 2018.3.1 .. warning:: As of 2018.3.1 the tag parameter no longer accepts a comma-separated value. It's is now possible to create a tag that contains a comma, this was impossible before. CLI Example: .. code-block:: bash salt '*' zfs.hold mytag myzpool/mydataset@mysnapshot [recursive=True] salt '*' zfs.hold mytag myzpool/mydataset@mysnapshot myzpool/mydataset@myothersnapshot """ ## Configure command # NOTE: initialize the defaults flags = [] target = [] # NOTE: set extra config from kwargs if kwargs.get("recursive", False): flags.append("-r") # NOTE: update target target.append(tag) target.extend(snapshot) ## hold snapshot res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="hold", flags=flags, target=target, ), python_shell=False, ) return __utils__["zfs.parse_command_result"](res, "held") def release(tag, *snapshot, **kwargs): """ Removes a single reference, named with the tag argument, from the specified snapshot or snapshots. .. note:: The tag must already exist for each snapshot. If a hold exists on a snapshot, attempts to destroy that snapshot by using the zfs destroy command return EBUSY. tag : string name of tag snapshot : string name of snapshot(s) recursive : boolean recursively releases a hold with the given tag on the snapshots of all descendent file systems. .. versionadded:: 2016.3.0 .. versionchanged:: 2018.3.1 .. warning:: As of 2018.3.1 the tag parameter no longer accepts a comma-separated value. It's is now possible to create a tag that contains a comma, this was impossible before. CLI Example: .. code-block:: bash salt '*' zfs.release mytag myzpool/mydataset@mysnapshot [recursive=True] salt '*' zfs.release mytag myzpool/mydataset@mysnapshot myzpool/mydataset@myothersnapshot """ ## Configure command # NOTE: initialize the defaults flags = [] target = [] # NOTE: set extra config from kwargs if kwargs.get("recursive", False): flags.append("-r") # NOTE: update target target.append(tag) target.extend(snapshot) ## release snapshot res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="release", flags=flags, target=target, ), python_shell=False, ) return __utils__["zfs.parse_command_result"](res, "released") def snapshot(*snapshot, **kwargs): """ Creates snapshots with the given names. snapshot : string name of snapshot(s) recursive : boolean recursively create snapshots of all descendent datasets. properties : dict additional zfs properties (-o) .. note:: ZFS properties can be specified at the time of creation of the filesystem by passing an additional argument called "properties" and specifying the properties with their respective values in the form of a python dictionary:: properties="{'property1': 'value1', 'property2': 'value2'}" .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.snapshot myzpool/mydataset@yesterday [recursive=True] salt '*' zfs.snapshot myzpool/mydataset@yesterday myzpool/myotherdataset@yesterday [recursive=True] """ ## Configure command # NOTE: initialize the defaults flags = [] # NOTE: push filesystem properties filesystem_properties = kwargs.get("properties", {}) # NOTE: set extra config from kwargs if kwargs.get("recursive", False): flags.append("-r") ## Create snapshot res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="snapshot", flags=flags, filesystem_properties=filesystem_properties, target=list(snapshot), ), python_shell=False, ) return __utils__["zfs.parse_command_result"](res, "snapshotted") def set(*dataset, **kwargs): """ Sets the property or list of properties to the given value(s) for each dataset. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string additional zfs properties pairs .. note:: properties are passed as key-value pairs. e.g. compression=off .. note:: Only some properties can be edited. See the Properties section for more information on what properties can be set and acceptable values. Numeric values can be specified as exact values, or in a human-readable form with a suffix of B, K, M, G, T, P, E (for bytes, kilobytes, megabytes, gigabytes, terabytes, petabytes, or exabytes respectively). .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.set myzpool/mydataset compression=off salt '*' zfs.set myzpool/mydataset myzpool/myotherdataset compression=off salt '*' zfs.set myzpool/mydataset myzpool/myotherdataset compression=lz4 canmount=off """ ## Configure command # NOTE: push filesystem properties filesystem_properties = salt.utils.args.clean_kwargs(**kwargs) ## Set property res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="set", property_name=list(filesystem_properties.keys()), property_value=list(filesystem_properties.values()), target=list(dataset), ), python_shell=False, ) return __utils__["zfs.parse_command_result"](res, "set") def get(*dataset, **kwargs): """ Displays properties for the given datasets. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string comma-separated list of properties to list, defaults to all recursive : boolean recursively list children depth : int recursively list children to depth fields : string comma-separated list of fields to include, the name and property field will always be added type : string comma-separated list of types to display, where type is one of filesystem, snapshot, volume, bookmark, or all. .. versionchanged:: 3004 type is ignored on Solaris 10 and 11 since not a valid parameter on those platforms source : string comma-separated list of sources to display. Must be one of the following: local, default, inherited, temporary, and none. The default value is all sources. parsable : boolean display numbers in parsable (exact) values (default = True) .. versionadded:: 2018.3.0 .. note:: If no datasets are specified, then the command displays properties for all datasets on the system. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.get salt '*' zfs.get myzpool/mydataset [recursive=True|False] salt '*' zfs.get myzpool/mydataset properties="sharenfs,mountpoint" [recursive=True|False] salt '*' zfs.get myzpool/mydataset myzpool/myotherdataset properties=available fields=value depth=1 """ ## Configure command # NOTE: initialize the defaults flags = ["-H"] opts = {} # NOTE: set extra config from kwargs if kwargs.get("depth", False): opts["-d"] = kwargs.get("depth") elif kwargs.get("recursive", False): flags.append("-r") fields = kwargs.get("fields", "value,source").split(",") if "name" in fields: # ensure name is first fields.remove("name") if "property" in fields: # ensure property is second fields.remove("property") fields.insert(0, "name") fields.insert(1, "property") opts["-o"] = ",".join(fields) if not salt.utils.platform.is_sunos(): if kwargs.get("type", False): opts["-t"] = kwargs.get("type") if kwargs.get("source", False): opts["-s"] = kwargs.get("source") # NOTE: set property_name property_name = kwargs.get("properties", "all") ## Get properties res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( command="get", flags=flags, opts=opts, property_name=property_name, target=list(dataset), ), python_shell=False, ) ret = __utils__["zfs.parse_command_result"](res) if res["retcode"] == 0: for ds in res["stdout"].splitlines(): ds_data = OrderedDict(list(zip(fields, ds.split("\t")))) if "value" in ds_data: if kwargs.get("parsable", True): ds_data["value"] = __utils__["zfs.from_auto"]( ds_data["property"], ds_data["value"], ) else: ds_data["value"] = __utils__["zfs.to_auto"]( ds_data["property"], ds_data["value"], convert_to_human=True, ) if ds_data["name"] not in ret: ret[ds_data["name"]] = OrderedDict() ret[ds_data["name"]][ds_data["property"]] = ds_data del ds_data["name"] del ds_data["property"] return ret # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/zfs.py
0.657978
0.216425
zfs.py
pypi
import logging import salt.utils.data import salt.utils.platform log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = "pkg" def __virtual__(): """ Only work on systems that are a proxy minion """ try: if salt.utils.platform.is_proxy() and __opts__["proxy"]["proxytype"] == "dummy": return __virtualname__ except KeyError: return ( False, "The dummyproxy_package execution module failed to load. Check " "the proxy key in pillar or /etc/salt/proxy.", ) return ( False, "The dummyproxy_package execution module failed to load: only works " "on a dummy proxy minion.", ) def list_pkgs(versions_as_list=False, **kwargs): return __proxy__["dummy.package_list"]() def install(name=None, refresh=False, fromrepo=None, pkgs=None, sources=None, **kwargs): return __proxy__["dummy.package_install"](name, **kwargs) def remove(name=None, pkgs=None, **kwargs): return __proxy__["dummy.package_remove"](name) def version(*names, **kwargs): """ Returns a string representing the package version or an empty string if not installed. If more than one package name is specified, a dict of name/version pairs is returned. CLI Example: .. code-block:: bash salt '*' pkg.version <package name> salt '*' pkg.version <package1> <package2> <package3> ... """ if len(names) == 1: vers = __proxy__["dummy.package_status"](names[0]) return vers[names[0]] else: results = {} for n in names: vers = __proxy__["dummy.package_status"](n) results.update(vers) return results def upgrade( name=None, pkgs=None, refresh=True, skip_verify=True, normalize=True, **kwargs ): old = __proxy__["dummy.package_list"]() new = __proxy__["dummy.uptodate"]() pkg_installed = __proxy__["dummy.upgrade"]() ret = salt.utils.data.compare_dicts(old, pkg_installed) return ret def installed( name, version=None, refresh=False, fromrepo=None, skip_verify=False, pkgs=None, sources=None, **kwargs ): p = __proxy__["dummy.package_status"](name) if version is None: if "ret" in p: return str(p["ret"]) else: return True else: if p is not None: return version == str(p)
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/dummyproxy_pkg.py
0.574753
0.158435
dummyproxy_pkg.py
pypi
import salt.utils.sdb __func_alias__ = { "set_": "set", } def get(uri, strict=False): """ Get a value from a db, using a uri in the form of ``sdb://<profile>/<key>``. If the uri provided is not valid, then it will be returned as-is, unless ``strict=True`` was passed. CLI Example: .. code-block:: bash salt '*' sdb.get sdb://mymemcached/foo strict=True """ return salt.utils.sdb.sdb_get(uri, __opts__, __utils__, strict) def set_(uri, value): """ Set a value in a db, using a uri in the form of ``sdb://<profile>/<key>``. If the uri provided does not start with ``sdb://`` or the value is not successfully set, return ``False``. CLI Example: .. code-block:: bash salt '*' sdb.set sdb://mymemcached/foo bar """ return salt.utils.sdb.sdb_set(uri, value, __opts__, __utils__) def delete(uri): """ Delete a value from a db, using a uri in the form of ``sdb://<profile>/<key>``. If the uri provided does not start with ``sdb://`` or the value is not successfully deleted, return ``False``. CLI Example: .. code-block:: bash salt '*' sdb.delete sdb://mymemcached/foo """ return salt.utils.sdb.sdb_delete(uri, __opts__, __utils__) def get_or_set_hash( uri, length=8, chars="abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)" ): """ Perform a one-time generation of a hash and write it to sdb. If that value has already been set return the value instead. This is useful for generating passwords or keys that are specific to multiple minions that need to be stored somewhere centrally. State Example: .. code-block:: yaml some_mysql_user: mysql_user: - present - host: localhost - password: '{{ salt['sdb.get_or_set_hash']('some_mysql_user_pass') }}' CLI Example: .. code-block:: bash salt '*' sdb.get_or_set_hash 'SECRET_KEY' 50 .. warning:: This function could return strings which may contain characters which are reserved as directives by the YAML parser, such as strings beginning with ``%``. To avoid issues when using the output of this function in an SLS file containing YAML+Jinja, surround the call with single quotes. """ return salt.utils.sdb.sdb_get_or_set_hash(uri, __opts__, length, chars, __utils__)
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/sdb.py
0.767864
0.256256
sdb.py
pypi
import salt.utils.platform # Define the module's virtual name __virtualname__ = "auditpol" def __virtual__(): """ Only works on Windows systems """ if not salt.utils.platform.is_windows(): return False, "Module win_auditpol: module only available on Windows" return __virtualname__ def get_settings(category="All"): """ Get the current configuration for all audit settings specified in the category Args: category (str): One of the nine categories to return. Can also be ``All`` to return the settings for all categories. Valid options are: - Account Logon - Account Management - Detailed Tracking - DS Access - Logon/Logoff - Object Access - Policy Change - Privilege Use - System - All Default value is ``All`` Returns: dict: A dictionary containing all subcategories for the specified category along with their current configuration Raises: KeyError: On invalid category CommandExecutionError: If an error is encountered retrieving the settings CLI Example: .. code-block:: bash # Get current state of all audit settings salt * auditipol.get_settings # Get the current state of all audit settings in the "Account Logon" # category salt * auditpol.get_settings "Account Logon" """ return __utils__["auditpol.get_settings"](category=category) def get_setting(name): """ Get the current configuration for the named audit setting Args: name (str): The name of the setting to retrieve Returns: str: The current configuration for the named setting Raises: KeyError: On invalid setting name CommandExecutionError: If an error is encountered retrieving the settings CLI Example: .. code-block:: bash # Get current state of the "Credential Validation" setting salt * auditpol.get_setting "Credential Validation" """ return __utils__["auditpol.get_setting"](name=name) def set_setting(name, value): """ Set the configuration for the named audit setting Args: name (str): The name of the setting to configure value (str): The configuration for the named value. Valid options are: - No Auditing - Success - Failure - Success and Failure Returns: bool: True if successful Raises: KeyError: On invalid ``name`` or ``value`` CommandExecutionError: If an error is encountered modifying the setting CLI Example: .. code-block:: bash # Set the state of the "Credential Validation" setting to Success and # Failure salt * auditpol.set_setting "Credential Validation" "Success and Failure" # Set the state of the "Credential Validation" setting to No Auditing salt * auditpol.set_setting "Credential Validation" "No Auditing" """ return __utils__["auditpol.set_setting"](name=name, value=value)
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/win_auditpol.py
0.857589
0.245944
win_auditpol.py
pypi
import logging import re import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = "powercfg" def __virtual__(): """ Only work on Windows """ if not salt.utils.platform.is_windows(): return False, "PowerCFG: Module only works on Windows" return __virtualname__ def _get_current_scheme(): cmd = "powercfg /getactivescheme" out = __salt__["cmd.run"](cmd, python_shell=False) matches = re.search(r"GUID: (.*) \(", out) return matches.groups()[0].strip() def _get_powercfg_minute_values(scheme, guid, subguid, safe_name): """ Returns the AC/DC values in an dict for a guid and subguid for a the given scheme """ if scheme is None: scheme = _get_current_scheme() if __grains__["osrelease"] == "7": cmd = "powercfg /q {} {}".format(scheme, guid) else: cmd = "powercfg /q {} {} {}".format(scheme, guid, subguid) out = __salt__["cmd.run"](cmd, python_shell=False) split = out.split("\r\n\r\n") if len(split) > 1: for s in split: if safe_name in s or subguid in s: out = s break else: out = split[0] raw_settings = re.findall(r"Power Setting Index: ([0-9a-fx]+)", out) return {"ac": int(raw_settings[0], 0) / 60, "dc": int(raw_settings[1], 0) / 60} def _set_powercfg_value(scheme, sub_group, setting_guid, power, value): """ Sets the AC/DC values of a setting with the given power for the given scheme """ if scheme is None: scheme = _get_current_scheme() cmd = "powercfg /set{}valueindex {} {} {} {}".format( power, scheme, sub_group, setting_guid, value * 60 ) return __salt__["cmd.retcode"](cmd, python_shell=False) == 0 def set_monitor_timeout(timeout, power="ac", scheme=None): """ Set the monitor timeout in minutes for the given power scheme Args: timeout (int): The amount of time in minutes before the monitor will timeout power (str): Set the value for AC or DC power. Default is ``ac``. Valid options are: - ``ac`` (AC Power) - ``dc`` (Battery) scheme (str): The scheme to use, leave as ``None`` to use the current. Default is ``None``. This can be the GUID or the Alias for the Scheme. Known Aliases are: - ``SCHEME_BALANCED`` - Balanced - ``SCHEME_MAX`` - Power saver - ``SCHEME_MIN`` - High performance Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash # Sets the monitor timeout to 30 minutes salt '*' powercfg.set_monitor_timeout 30 """ return _set_powercfg_value( scheme=scheme, sub_group="SUB_VIDEO", setting_guid="VIDEOIDLE", power=power, value=timeout, ) def get_monitor_timeout(scheme=None): """ Get the current monitor timeout of the given scheme Args: scheme (str): The scheme to use, leave as ``None`` to use the current. Default is ``None``. This can be the GUID or the Alias for the Scheme. Known Aliases are: - ``SCHEME_BALANCED`` - Balanced - ``SCHEME_MAX`` - Power saver - ``SCHEME_MIN`` - High performance Returns: dict: A dictionary of both the AC and DC settings CLI Example: .. code-block:: bash salt '*' powercfg.get_monitor_timeout """ return _get_powercfg_minute_values( scheme=scheme, guid="SUB_VIDEO", subguid="VIDEOIDLE", safe_name="Turn off display after", ) def set_disk_timeout(timeout, power="ac", scheme=None): """ Set the disk timeout in minutes for the given power scheme Args: timeout (int): The amount of time in minutes before the disk will timeout power (str): Set the value for AC or DC power. Default is ``ac``. Valid options are: - ``ac`` (AC Power) - ``dc`` (Battery) scheme (str): The scheme to use, leave as ``None`` to use the current. Default is ``None``. This can be the GUID or the Alias for the Scheme. Known Aliases are: - ``SCHEME_BALANCED`` - Balanced - ``SCHEME_MAX`` - Power saver - ``SCHEME_MIN`` - High performance Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash # Sets the disk timeout to 30 minutes on battery salt '*' powercfg.set_disk_timeout 30 power=dc """ return _set_powercfg_value( scheme=scheme, sub_group="SUB_DISK", setting_guid="DISKIDLE", power=power, value=timeout, ) def get_disk_timeout(scheme=None): """ Get the current disk timeout of the given scheme Args: scheme (str): The scheme to use, leave as ``None`` to use the current. Default is ``None``. This can be the GUID or the Alias for the Scheme. Known Aliases are: - ``SCHEME_BALANCED`` - Balanced - ``SCHEME_MAX`` - Power saver - ``SCHEME_MIN`` - High performance Returns: dict: A dictionary of both the AC and DC settings CLI Example: .. code-block:: bash salt '*' powercfg.get_disk_timeout """ return _get_powercfg_minute_values( scheme=scheme, guid="SUB_DISK", subguid="DISKIDLE", safe_name="Turn off hard disk after", ) def set_standby_timeout(timeout, power="ac", scheme=None): """ Set the standby timeout in minutes for the given power scheme Args: timeout (int): The amount of time in minutes before the computer sleeps power (str): Set the value for AC or DC power. Default is ``ac``. Valid options are: - ``ac`` (AC Power) - ``dc`` (Battery) scheme (str): The scheme to use, leave as ``None`` to use the current. Default is ``None``. This can be the GUID or the Alias for the Scheme. Known Aliases are: - ``SCHEME_BALANCED`` - Balanced - ``SCHEME_MAX`` - Power saver - ``SCHEME_MIN`` - High performance Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash # Sets the system standby timeout to 30 minutes on Battery salt '*' powercfg.set_standby_timeout 30 power=dc """ return _set_powercfg_value( scheme=scheme, sub_group="SUB_SLEEP", setting_guid="STANDBYIDLE", power=power, value=timeout, ) def get_standby_timeout(scheme=None): """ Get the current standby timeout of the given scheme scheme (str): The scheme to use, leave as ``None`` to use the current. Default is ``None``. This can be the GUID or the Alias for the Scheme. Known Aliases are: - ``SCHEME_BALANCED`` - Balanced - ``SCHEME_MAX`` - Power saver - ``SCHEME_MIN`` - High performance Returns: dict: A dictionary of both the AC and DC settings CLI Example: .. code-block:: bash salt '*' powercfg.get_standby_timeout """ return _get_powercfg_minute_values( scheme=scheme, guid="SUB_SLEEP", subguid="STANDBYIDLE", safe_name="Sleep after" ) def set_hibernate_timeout(timeout, power="ac", scheme=None): """ Set the hibernate timeout in minutes for the given power scheme Args: timeout (int): The amount of time in minutes before the computer hibernates power (str): Set the value for AC or DC power. Default is ``ac``. Valid options are: - ``ac`` (AC Power) - ``dc`` (Battery) scheme (str): The scheme to use, leave as ``None`` to use the current. Default is ``None``. This can be the GUID or the Alias for the Scheme. Known Aliases are: - ``SCHEME_BALANCED`` - Balanced - ``SCHEME_MAX`` - Power saver - ``SCHEME_MIN`` - High performance Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash # Sets the hibernate timeout to 30 minutes on Battery salt '*' powercfg.set_hibernate_timeout 30 power=dc """ return _set_powercfg_value( scheme=scheme, sub_group="SUB_SLEEP", setting_guid="HIBERNATEIDLE", power=power, value=timeout, ) def get_hibernate_timeout(scheme=None): """ Get the current hibernate timeout of the given scheme scheme (str): The scheme to use, leave as ``None`` to use the current. Default is ``None``. This can be the GUID or the Alias for the Scheme. Known Aliases are: - ``SCHEME_BALANCED`` - Balanced - ``SCHEME_MAX`` - Power saver - ``SCHEME_MIN`` - High performance Returns: dict: A dictionary of both the AC and DC settings CLI Example: .. code-block:: bash salt '*' powercfg.get_hibernate_timeout """ return _get_powercfg_minute_values( scheme=scheme, guid="SUB_SLEEP", subguid="HIBERNATEIDLE", safe_name="Hibernate after", )
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/win_powercfg.py
0.839372
0.184694
win_powercfg.py
pypi
import difflib import logging from salt.exceptions import CommandExecutionError from salt.utils.args import clean_kwargs try: import pyeapi HAS_PYEAPI = True except ImportError: HAS_PYEAPI = False # ----------------------------------------------------------------------------- # execution module properties # ----------------------------------------------------------------------------- __proxyenabled__ = ["*"] # Any Proxy Minion should be able to execute these __virtualname__ = "pyeapi" # The Execution Module will be identified as ``pyeapi`` # ----------------------------------------------------------------------------- # globals # ----------------------------------------------------------------------------- log = logging.getLogger(__name__) PYEAPI_INIT_KWARGS = [ "transport", "host", "username", "password", "enablepwd", "port", "timeout", "return_node", ] # ----------------------------------------------------------------------------- # propery functions # ----------------------------------------------------------------------------- def __virtual__(): """ Execution module available only if pyeapi is installed. """ if not HAS_PYEAPI: return ( False, "The pyeapi execution module requires pyeapi library to be installed: ``pip" " install pyeapi``", ) return __virtualname__ # ----------------------------------------------------------------------------- # helper functions # ----------------------------------------------------------------------------- def _prepare_connection(**kwargs): """ Prepare the connection with the remote network device, and clean up the key value pairs, removing the args used for the connection init. """ pyeapi_kwargs = __salt__["config.get"]("pyeapi", {}) pyeapi_kwargs.update(kwargs) # merge the CLI args with the opts/pillar init_kwargs, fun_kwargs = __utils__["args.prepare_kwargs"]( pyeapi_kwargs, PYEAPI_INIT_KWARGS ) if "transport" not in init_kwargs: init_kwargs["transport"] = "https" conn = pyeapi.client.connect(**init_kwargs) node = pyeapi.client.Node(conn, enablepwd=init_kwargs.get("enablepwd")) return node, fun_kwargs # ----------------------------------------------------------------------------- # callable functions # ----------------------------------------------------------------------------- def get_connection(**kwargs): """ Return the connection object to the pyeapi Node. .. warning:: This function returns an unserializable object, hence it is not meant to be used on the CLI. This should mainly be used when invoked from other modules for the low level connection with the network device. kwargs Key-value dictionary with the authentication details. USAGE Example: .. code-block:: python conn = __salt__['pyeapi.get_connection'](host='router1.example.com', username='example', password='example') show_ver = conn.run_commands(['show version', 'show interfaces']) """ kwargs = clean_kwargs(**kwargs) if "pyeapi.conn" in __proxy__: return __proxy__["pyeapi.conn"]() conn, kwargs = _prepare_connection(**kwargs) return conn def call(method, *args, **kwargs): """ Invoke an arbitrary pyeapi method. method The name of the pyeapi method to invoke. args A list of arguments to send to the method invoked. kwargs Key-value dictionary to send to the method invoked. transport: ``https`` Specifies the type of connection transport to use. Valid values for the connection are ``socket``, ``http_local``, ``http``, and ``https``. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. host: ``localhost`` The IP address or DNS host name of the connection device. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. username: ``admin`` The username to pass to the device to authenticate the eAPI connection. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. password The password to pass to the device to authenticate the eAPI connection. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. port The TCP port of the endpoint for the eAPI connection. If this keyword is not specified, the default value is automatically determined by the transport type (``80`` for ``http``, or ``443`` for ``https``). .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. enablepwd The enable mode password if required by the destination node. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. CLI Example: .. code-block:: bash salt '*' pyeapi.call run_commands "['show version']" """ kwargs = clean_kwargs(**kwargs) if "pyeapi.call" in __proxy__: return __proxy__["pyeapi.call"](method, *args, **kwargs) conn, kwargs = _prepare_connection(**kwargs) ret = getattr(conn, method)(*args, **kwargs) return ret def run_commands(*commands, **kwargs): """ Sends the commands over the transport to the device. This function sends the commands to the device using the nodes transport. This is a lower layer function that shouldn't normally need to be used, preferring instead to use ``config()`` or ``enable()``. transport: ``https`` Specifies the type of connection transport to use. Valid values for the connection are ``socket``, ``http_local``, ``http``, and ``https``. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. host: ``localhost`` The IP address or DNS host name of the connection device. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. username: ``admin`` The username to pass to the device to authenticate the eAPI connection. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. password The password to pass to the device to authenticate the eAPI connection. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. port The TCP port of the endpoint for the eAPI connection. If this keyword is not specified, the default value is automatically determined by the transport type (``80`` for ``http``, or ``443`` for ``https``). .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. enablepwd The enable mode password if required by the destination node. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. CLI Example: .. code-block:: bash salt '*' pyeapi.run_commands 'show version' salt '*' pyeapi.run_commands 'show version' encoding=text salt '*' pyeapi.run_commands 'show version' encoding=text host=cr1.thn.lon username=example password=weak Output example: .. code-block:: text veos1: |_ ---------- architecture: i386 bootupTimestamp: 1527541728.53 hardwareRevision: internalBuildId: 63d2e89a-220d-4b8a-a9b3-0524fa8f9c5f internalVersion: 4.18.1F-4591672.4181F isIntlVersion: False memFree: 501468 memTotal: 1893316 modelName: vEOS serialNumber: systemMacAddress: 52:54:00:3f:e6:d0 version: 4.18.1F """ encoding = kwargs.pop("encoding", "json") send_enable = kwargs.pop("send_enable", True) output = call( "run_commands", commands, encoding=encoding, send_enable=send_enable, **kwargs ) if encoding == "text": ret = [] for res in output: ret.append(res["output"]) return ret return output def config( commands=None, config_file=None, template_engine="jinja", context=None, defaults=None, saltenv="base", **kwargs ): """ Configures the node with the specified commands. This method is used to send configuration commands to the node. It will take either a string or a list and prepend the necessary commands to put the session into config mode. Returns the diff after the configuration commands are loaded. config_file The source file with the configuration commands to be sent to the device. The file can also be a template that can be rendered using the template engine of choice. This can be specified using the absolute path to the file, or using one of the following URL schemes: - ``salt://``, to fetch the file from the Salt fileserver. - ``http://`` or ``https://`` - ``ftp://`` - ``s3://`` - ``swift://`` commands The commands to send to the node in config mode. If the commands argument is a string it will be cast to a list. The list of commands will also be prepended with the necessary commands to put the session in config mode. .. note:: This argument is ignored when ``config_file`` is specified. template_engine: ``jinja`` The template engine to use when rendering the source file. Default: ``jinja``. To simply fetch the file without attempting to render, set this argument to ``None``. context Variables to add to the template context. defaults Default values of the ``context`` dict. transport: ``https`` Specifies the type of connection transport to use. Valid values for the connection are ``socket``, ``http_local``, ``http``, and ``https``. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. host: ``localhost`` The IP address or DNS host name of the connection device. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. username: ``admin`` The username to pass to the device to authenticate the eAPI connection. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. password The password to pass to the device to authenticate the eAPI connection. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. port The TCP port of the endpoint for the eAPI connection. If this keyword is not specified, the default value is automatically determined by the transport type (``80`` for ``http``, or ``443`` for ``https``). .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. enablepwd The enable mode password if required by the destination node. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. CLI Example: .. code-block:: bash salt '*' pyeapi.config commands="['ntp server 1.2.3.4', 'ntp server 5.6.7.8']" salt '*' pyeapi.config config_file=salt://config.txt salt '*' pyeapi.config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" """ initial_config = get_config(as_string=True, **kwargs) if config_file: file_str = __salt__["cp.get_file_str"](config_file, saltenv=saltenv) if file_str is False: raise CommandExecutionError("Source file {} not found".format(config_file)) log.debug("Fetched from %s", config_file) log.debug(file_str) elif commands: if isinstance(commands, str): commands = [commands] file_str = "\n".join(commands) # unify all the commands in a single file, to render them in a go if template_engine: file_str = __salt__["file.apply_template_on_contents"]( file_str, template_engine, context, defaults, saltenv ) log.debug("Rendered:") log.debug(file_str) # whatever the source of the commands would be, split them line by line commands = [line for line in file_str.splitlines() if line.strip()] # push the commands one by one, removing empty lines configured = call("config", commands, **kwargs) current_config = get_config(as_string=True, **kwargs) diff = difflib.unified_diff( initial_config.splitlines(1)[4:], current_config.splitlines(1)[4:] ) return "".join([x.replace("\r", "") for x in diff]) def get_config(config="running-config", params=None, as_string=False, **kwargs): """ Retrieves the config from the device. This method will retrieve the config from the node as either a string or a list object. The config to retrieve can be specified as either the startup-config or the running-config. config: ``running-config`` Specifies to return either the nodes ``startup-config`` or ``running-config``. The default value is the ``running-config``. params A string of keywords to append to the command for retrieving the config. as_string: ``False`` Flag that determines the response. If ``True``, then the configuration is returned as a raw string. If ``False``, then the configuration is returned as a list. The default value is ``False``. transport: ``https`` Specifies the type of connection transport to use. Valid values for the connection are ``socket``, ``http_local``, ``http``, and ``https``. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. host: ``localhost`` The IP address or DNS host name of the connection device. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. username: ``admin`` The username to pass to the device to authenticate the eAPI connection. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. password The password to pass to the device to authenticate the eAPI connection. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. port The TCP port of the endpoint for the eAPI connection. If this keyword is not specified, the default value is automatically determined by the transport type (``80`` for ``http``, or ``443`` for ``https``). .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. enablepwd The enable mode password if required by the destination node. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. CLI Example: .. code-block:: bash salt '*' pyeapi.get_config salt '*' pyeapi.get_config params='section snmp-server' salt '*' pyeapi.get_config config='startup-config' """ return call( "get_config", config=config, params=params, as_string=as_string, **kwargs ) def section(regex, config="running-config", **kwargs): """ Return a section of the config. regex A valid regular expression used to select sections of configuration to return. config: ``running-config`` The configuration to return. Valid values for config are ``running-config`` or ``startup-config``. The default value is ``running-config``. transport: ``https`` Specifies the type of connection transport to use. Valid values for the connection are ``socket``, ``http_local``, ``http``, and ``https``. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. host: ``localhost`` The IP address or DNS host name of the connection device. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. username: ``admin`` The username to pass to the device to authenticate the eAPI connection. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. password The password to pass to the device to authenticate the eAPI connection. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. port The TCP port of the endpoint for the eAPI connection. If this keyword is not specified, the default value is automatically determined by the transport type (``80`` for ``http``, or ``443`` for ``https``). .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. enablepwd The enable mode password if required by the destination node. .. note:: This argument does not need to be specified when running in a :mod:`pyeapi <salt.proxy.arista_pyeapi>` Proxy Minion. CLI Example: .. code-block:: bash salt '*' """ return call("section", regex, config=config, **kwargs)
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/arista_pyeapi.py
0.75985
0.199211
arista_pyeapi.py
pypi
import logging import re import salt.utils.args import salt.utils.data import salt.utils.decorators import salt.utils.files import salt.utils.path from salt.utils.odict import OrderedDict log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = "zonecfg" # Function aliases __func_alias__ = {"import_": "import"} # Global data _zonecfg_info_resources = [ "rctl", "net", "fs", "device", "dedicated-cpu", "dataset", "attr", ] _zonecfg_info_resources_calculated = [ "capped-cpu", "capped-memory", ] _zonecfg_resource_setters = { "fs": ["dir", "special", "raw", "type", "options"], "net": [ "address", "allowed-address", "global-nic", "mac-addr", "physical", "property", "vlan-id defrouter", ], "device": ["match", "property"], "rctl": ["name", "value"], "attr": ["name", "type", "value"], "dataset": ["name"], "dedicated-cpu": ["ncpus", "importance"], "capped-cpu": ["ncpus"], "capped-memory": ["physical", "swap", "locked"], "admin": ["user", "auths"], } _zonecfg_resource_default_selectors = { "fs": "dir", "net": "mac-addr", "device": "match", "rctl": "name", "attr": "name", "dataset": "name", "admin": "user", } @salt.utils.decorators.memoize def _is_globalzone(): """ Check if we are running in the globalzone """ if not __grains__["kernel"] == "SunOS": return False zonename = __salt__["cmd.run_all"]("zonename") if zonename["retcode"]: return False if zonename["stdout"] == "global": return True return False def __virtual__(): """ We are available if we are have zonecfg and are the global zone on Solaris 10, OmniOS, OpenIndiana, OpenSolaris, or Smartos. """ if _is_globalzone() and salt.utils.path.which("zonecfg"): if __grains__["os"] in ["OpenSolaris", "SmartOS", "OmniOS", "OpenIndiana"]: return __virtualname__ elif ( __grains__["os"] == "Oracle Solaris" and int(__grains__["osmajorrelease"]) == 10 ): return __virtualname__ return ( False, "{} module can only be loaded in a solaris globalzone.".format(__virtualname__), ) def _clean_message(message): """Internal helper to sanitize message output""" message = message.replace("zonecfg: ", "") message = message.splitlines() for line in message: if line.startswith("On line"): message.remove(line) return "\n".join(message) def _parse_value(value): """Internal helper for parsing configuration values into python values""" if isinstance(value, bool): return "true" if value else "false" elif isinstance(value, str): # parse compacted notation to dict listparser = re.compile(r"""((?:[^,"']|"[^"]*"|'[^']*')+)""") value = value.strip() if value.startswith("[") and value.endswith("]"): return listparser.split(value[1:-1])[1::2] elif value.startswith("(") and value.endswith(")"): rval = {} for pair in listparser.split(value[1:-1])[1::2]: pair = pair.split("=") if '"' in pair[1]: pair[1] = pair[1].replace('"', "") if pair[1].isdigit(): rval[pair[0]] = int(pair[1]) elif pair[1] == "true": rval[pair[0]] = True elif pair[1] == "false": rval[pair[0]] = False else: rval[pair[0]] = pair[1] return rval else: if '"' in value: value = value.replace('"', "") if value.isdigit(): return int(value) elif value == "true": return True elif value == "false": return False else: return value else: return value def _sanitize_value(value): """Internal helper for converting pythonic values to configuration file values""" # dump dict into compated if isinstance(value, dict): new_value = [] new_value.append("(") for k, v in value.items(): new_value.append(k) new_value.append("=") new_value.append(v) new_value.append(",") new_value.append(")") return "".join(str(v) for v in new_value).replace(",)", ")") elif isinstance(value, list): new_value = [] new_value.append("(") for item in value: if isinstance(item, OrderedDict): item = dict(item) for k, v in item.items(): new_value.append(k) new_value.append("=") new_value.append(v) else: new_value.append(item) new_value.append(",") new_value.append(")") return "".join(str(v) for v in new_value).replace(",)", ")") else: # note: we can't use shelx or pipes quote here because it makes zonecfg barf return '"{}"'.format(value) if " " in value else value def _dump_cfg(cfg_file): """Internal helper for debugging cfg files""" if __salt__["file.file_exists"](cfg_file): with salt.utils.files.fopen(cfg_file, "r") as fp_: log.debug( "zonecfg - configuration file:\n%s", "".join(salt.utils.data.decode(fp_.readlines())), ) def create(zone, brand, zonepath, force=False): """ Create an in-memory configuration for the specified zone. zone : string name of zone brand : string brand name zonepath : string path of zone force : boolean overwrite configuration CLI Example: .. code-block:: bash salt '*' zonecfg.create deathscythe ipkg /zones/deathscythe """ ret = {"status": True} # write config cfg_file = salt.utils.files.mkstemp() with salt.utils.files.fpopen(cfg_file, "w+", mode=0o600) as fp_: fp_.write("create -b -F\n" if force else "create -b\n") fp_.write("set brand={}\n".format(_sanitize_value(brand))) fp_.write("set zonepath={}\n".format(_sanitize_value(zonepath))) # create if not __salt__["file.directory_exists"](zonepath): __salt__["file.makedirs_perms"]( zonepath if zonepath[-1] == "/" else "{}/".format(zonepath), mode="0700" ) _dump_cfg(cfg_file) res = __salt__["cmd.run_all"]( "zonecfg -z {zone} -f {cfg}".format( zone=zone, cfg=cfg_file, ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] if ret["message"] == "": del ret["message"] else: ret["message"] = _clean_message(ret["message"]) # cleanup config file if __salt__["file.file_exists"](cfg_file): __salt__["file.remove"](cfg_file) return ret def create_from_template(zone, template): """ Create an in-memory configuration from a template for the specified zone. zone : string name of zone template : string name of template .. warning:: existing config will be overwritten! CLI Example: .. code-block:: bash salt '*' zonecfg.create_from_template leo tallgeese """ ret = {"status": True} # create from template _dump_cfg(template) res = __salt__["cmd.run_all"]( "zonecfg -z {zone} create -t {tmpl} -F".format( zone=zone, tmpl=template, ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] if ret["message"] == "": del ret["message"] else: ret["message"] = _clean_message(ret["message"]) return ret def delete(zone): """ Delete the specified configuration from memory and stable storage. zone : string name of zone CLI Example: .. code-block:: bash salt '*' zonecfg.delete epyon """ ret = {"status": True} # delete zone res = __salt__["cmd.run_all"]( "zonecfg -z {zone} delete -F".format( zone=zone, ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] if ret["message"] == "": del ret["message"] else: ret["message"] = _clean_message(ret["message"]) return ret def export(zone, path=None): """ Export the configuration from memory to stable storage. zone : string name of zone path : string path of file to export to CLI Example: .. code-block:: bash salt '*' zonecfg.export epyon salt '*' zonecfg.export epyon /zones/epyon.cfg """ ret = {"status": True} # export zone res = __salt__["cmd.run_all"]( "zonecfg -z {zone} export{path}".format( zone=zone, path=" -f {}".format(path) if path else "", ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] if ret["message"] == "": del ret["message"] else: ret["message"] = _clean_message(ret["message"]) return ret def import_(zone, path): """ Import the configuration to memory from stable storage. zone : string name of zone path : string path of file to export to CLI Example: .. code-block:: bash salt '*' zonecfg.import epyon /zones/epyon.cfg """ ret = {"status": True} # create from file _dump_cfg(path) res = __salt__["cmd.run_all"]( "zonecfg -z {zone} -f {path}".format( zone=zone, path=path, ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] if ret["message"] == "": del ret["message"] else: ret["message"] = _clean_message(ret["message"]) return ret def _property(methode, zone, key, value): """ internal handler for set and clear_property methode : string either set, add, or clear zone : string name of zone key : string name of property value : string value of property """ ret = {"status": True} # generate update script cfg_file = None if methode not in ["set", "clear"]: ret["status"] = False ret["message"] = "unkown methode {}!".format(methode) else: cfg_file = salt.utils.files.mkstemp() with salt.utils.files.fpopen(cfg_file, "w+", mode=0o600) as fp_: if methode == "set": if isinstance(value, dict) or isinstance(value, list): value = _sanitize_value(value) value = str(value).lower() if isinstance(value, bool) else str(value) fp_.write("{} {}={}\n".format(methode, key, _sanitize_value(value))) elif methode == "clear": fp_.write("{} {}\n".format(methode, key)) # update property if cfg_file: _dump_cfg(cfg_file) res = __salt__["cmd.run_all"]( "zonecfg -z {zone} -f {path}".format( zone=zone, path=cfg_file, ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] if ret["message"] == "": del ret["message"] else: ret["message"] = _clean_message(ret["message"]) # cleanup config file if __salt__["file.file_exists"](cfg_file): __salt__["file.remove"](cfg_file) return ret def set_property(zone, key, value): """ Set a property zone : string name of zone key : string name of property value : string value of property CLI Example: .. code-block:: bash salt '*' zonecfg.set_property deathscythe cpu-shares 100 """ return _property( "set", zone, key, value, ) def clear_property(zone, key): """ Clear a property zone : string name of zone key : string name of property CLI Example: .. code-block:: bash salt '*' zonecfg.clear_property deathscythe cpu-shares """ return _property( "clear", zone, key, None, ) def _resource(methode, zone, resource_type, resource_selector, **kwargs): """ internal resource hanlder methode : string add or update zone : string name of zone resource_type : string type of resource resource_selector : string unique resource identifier **kwargs : string|int|... resource properties """ ret = {"status": True} # parse kwargs kwargs = salt.utils.args.clean_kwargs(**kwargs) for k in kwargs: if isinstance(kwargs[k], dict) or isinstance(kwargs[k], list): kwargs[k] = _sanitize_value(kwargs[k]) if methode not in ["add", "update"]: ret["status"] = False ret["message"] = "unknown methode {}".format(methode) return ret if methode in ["update"] and resource_selector and resource_selector not in kwargs: ret["status"] = False ret["message"] = "resource selector {} not found in parameters".format( resource_selector ) return ret # generate update script cfg_file = salt.utils.files.mkstemp() with salt.utils.files.fpopen(cfg_file, "w+", mode=0o600) as fp_: if methode in ["add"]: fp_.write("add {}\n".format(resource_type)) elif methode in ["update"]: if resource_selector: value = kwargs[resource_selector] if isinstance(value, dict) or isinstance(value, list): value = _sanitize_value(value) value = str(value).lower() if isinstance(value, bool) else str(value) fp_.write( "select {} {}={}\n".format( resource_type, resource_selector, _sanitize_value(value) ) ) else: fp_.write("select {}\n".format(resource_type)) for k, v in kwargs.items(): if methode in ["update"] and k == resource_selector: continue if isinstance(v, dict) or isinstance(v, list): value = _sanitize_value(value) value = str(v).lower() if isinstance(v, bool) else str(v) if k in _zonecfg_resource_setters[resource_type]: fp_.write("set {}={}\n".format(k, _sanitize_value(value))) else: fp_.write("add {} {}\n".format(k, _sanitize_value(value))) fp_.write("end\n") # update property if cfg_file: _dump_cfg(cfg_file) res = __salt__["cmd.run_all"]( "zonecfg -z {zone} -f {path}".format( zone=zone, path=cfg_file, ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] if ret["message"] == "": del ret["message"] else: ret["message"] = _clean_message(ret["message"]) # cleanup config file if __salt__["file.file_exists"](cfg_file): __salt__["file.remove"](cfg_file) return ret def add_resource(zone, resource_type, **kwargs): """ Add a resource zone : string name of zone resource_type : string type of resource kwargs : string|int|... resource properties CLI Example: .. code-block:: bash salt '*' zonecfg.add_resource tallgeese rctl name=zone.max-locked-memory value='(priv=privileged,limit=33554432,action=deny)' """ return _resource("add", zone, resource_type, None, **kwargs) def update_resource(zone, resource_type, resource_selector, **kwargs): """ Add a resource zone : string name of zone resource_type : string type of resource resource_selector : string unique resource identifier kwargs : string|int|... resource properties .. note:: Set resource_selector to None for resource that do not require one. CLI Example: .. code-block:: bash salt '*' zonecfg.update_resource tallgeese rctl name name=zone.max-locked-memory value='(priv=privileged,limit=33554432,action=deny)' """ return _resource("update", zone, resource_type, resource_selector, **kwargs) def remove_resource(zone, resource_type, resource_key, resource_value): """ Remove a resource zone : string name of zone resource_type : string type of resource resource_key : string key for resource selection resource_value : string value for resource selection .. note:: Set resource_selector to None for resource that do not require one. CLI Example: .. code-block:: bash salt '*' zonecfg.remove_resource tallgeese rctl name zone.max-locked-memory """ ret = {"status": True} # generate update script cfg_file = salt.utils.files.mkstemp() with salt.utils.files.fpopen(cfg_file, "w+", mode=0o600) as fp_: if resource_key: fp_.write( "remove {} {}={}\n".format( resource_type, resource_key, _sanitize_value(resource_value) ) ) else: fp_.write("remove {}\n".format(resource_type)) # update property if cfg_file: _dump_cfg(cfg_file) res = __salt__["cmd.run_all"]( "zonecfg -z {zone} -f {path}".format( zone=zone, path=cfg_file, ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] if ret["message"] == "": del ret["message"] else: ret["message"] = _clean_message(ret["message"]) # cleanup config file if __salt__["file.file_exists"](cfg_file): __salt__["file.remove"](cfg_file) return ret def info(zone, show_all=False): """ Display the configuration from memory zone : string name of zone show_all : boolean also include calculated values like capped-cpu, cpu-shares, ... CLI Example: .. code-block:: bash salt '*' zonecfg.info tallgeese """ ret = {} # dump zone res = __salt__["cmd.run_all"]( "zonecfg -z {zone} info".format( zone=zone, ) ) if res["retcode"] == 0: # parse output resname = None resdata = {} for line in res["stdout"].split("\n"): # skip some bad data if ":" not in line: continue # skip calculated values (if requested) if line.startswith("["): if not show_all: continue line = line.rstrip()[1:-1] # extract key key = line.strip().split(":")[0] if "[" in key: key = key[1:] # parse calculated resource (if requested) if key in _zonecfg_info_resources_calculated: if resname: ret[resname].append(resdata) if show_all: resname = key resdata = {} if key not in ret: ret[key] = [] else: resname = None resdata = {} # parse resources elif key in _zonecfg_info_resources: if resname: ret[resname].append(resdata) resname = key resdata = {} if key not in ret: ret[key] = [] # store resource property elif line.startswith("\t"): # ship calculated values (if requested) if line.strip().startswith("["): if not show_all: continue line = line.strip()[1:-1] if key == "property": # handle special 'property' keys if "property" not in resdata: resdata[key] = {} kv = _parse_value(line.strip()[line.strip().index(":") + 1 :]) if "name" in kv and "value" in kv: resdata[key][kv["name"]] = kv["value"] else: log.warning("zonecfg.info - not sure how to deal with: %s", kv) else: resdata[key] = _parse_value( line.strip()[line.strip().index(":") + 1 :] ) # store property else: if resname: ret[resname].append(resdata) resname = None resdata = {} if key == "property": # handle special 'property' keys if "property" not in ret: ret[key] = {} kv = _parse_value(line.strip()[line.strip().index(":") + 1 :]) if "name" in kv and "value" in kv: res[key][kv["name"]] = kv["value"] else: log.warning("zonecfg.info - not sure how to deal with: %s", kv) else: ret[key] = _parse_value(line.strip()[line.strip().index(":") + 1 :]) # store hanging resource if resname: ret[resname].append(resdata) return ret # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/zonecfg.py
0.4917
0.166947
zonecfg.py
pypi
import glob import logging import os import tempfile import time import salt.crypt import salt.utils.path # Set up logging log = logging.getLogger(__name__) def __virtual__(): """ Only load if qemu-img and qemu-nbd are installed """ if salt.utils.path.which("qemu-nbd"): return "qemu_nbd" return ( False, "The qemu_nbd execution module cannot be loaded: the qemu-nbd binary is not in" " the path.", ) def connect(image): """ Activate nbd for an image file. CLI Example: .. code-block:: bash salt '*' qemu_nbd.connect /tmp/image.raw """ if not os.path.isfile(image): log.warning("Could not connect image: %s does not exist", image) return "" if salt.utils.path.which("sfdisk"): fdisk = "sfdisk -d" else: fdisk = "fdisk -l" __salt__["cmd.run"]("modprobe nbd max_part=63") for nbd in glob.glob("/dev/nbd?"): if __salt__["cmd.retcode"]("{} {}".format(fdisk, nbd)): while True: # Sometimes nbd does not "take hold", loop until we can verify __salt__["cmd.run"]( "qemu-nbd -c {} {}".format(nbd, image), python_shell=False, ) if not __salt__["cmd.retcode"]("{} {}".format(fdisk, nbd)): break return nbd log.warning("Could not connect image: %s", image) return "" def mount(nbd, root=None): """ Pass in the nbd connection device location, mount all partitions and return a dict of mount points CLI Example: .. code-block:: bash salt '*' qemu_nbd.mount /dev/nbd0 """ __salt__["cmd.run"]( "partprobe {}".format(nbd), python_shell=False, ) ret = {} if root is None: root = os.path.join(tempfile.gettempdir(), "nbd", os.path.basename(nbd)) for part in glob.glob("{}p*".format(nbd)): m_pt = os.path.join(root, os.path.basename(part)) time.sleep(1) mnt = __salt__["mount.mount"](m_pt, part, True) if mnt is not True: continue ret[m_pt] = part return ret def init(image, root=None): """ Mount the named image via qemu-nbd and return the mounted roots CLI Example: .. code-block:: bash salt '*' qemu_nbd.init /srv/image.qcow2 """ nbd = connect(image) if not nbd: return "" return mount(nbd, root) def clear(mnt): """ Pass in the mnt dict returned from nbd_mount to unmount and disconnect the image from nbd. If all of the partitions are unmounted return an empty dict, otherwise return a dict containing the still mounted partitions CLI Example: .. code-block:: bash salt '*' qemu_nbd.clear '{"/mnt/foo": "/dev/nbd0p1"}' """ ret = {} nbds = set() for m_pt, dev in mnt.items(): mnt_ret = __salt__["mount.umount"](m_pt) if mnt_ret is not True: ret[m_pt] = dev nbds.add(dev[: dev.rindex("p")]) if ret: return ret for nbd in nbds: __salt__["cmd.run"]("qemu-nbd -d {}".format(nbd), python_shell=False) return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/qemu_nbd.py
0.418578
0.201794
qemu_nbd.py
pypi
import logging import salt.utils.decorators import salt.utils.path log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = "zoneadm" # Function aliases __func_alias__ = {"list_zones": "list"} @salt.utils.decorators.memoize def _is_globalzone(): """ Check if we are running in the globalzone """ if not __grains__["kernel"] == "SunOS": return False zonename = __salt__["cmd.run_all"]("zonename") if zonename["retcode"]: return False if zonename["stdout"] == "global": return True return False def _is_uuid(zone): """ Check if zone is actually a UUID """ return len(zone) == 36 and zone.index("-") == 8 def __virtual__(): """ We are available if we are have zoneadm and are the global zone on Solaris 10, OmniOS, OpenIndiana, OpenSolaris, or Smartos. """ if _is_globalzone() and salt.utils.path.which("zoneadm"): if __grains__["os"] in ["OpenSolaris", "SmartOS", "OmniOS", "OpenIndiana"]: return __virtualname__ elif ( __grains__["os"] == "Oracle Solaris" and int(__grains__["osmajorrelease"]) == 10 ): return __virtualname__ return ( False, "{} module can only be loaded in a solaris globalzone.".format(__virtualname__), ) def list_zones(verbose=True, installed=False, configured=False, hide_global=True): """ List all zones verbose : boolean display additional zone information installed : boolean include installed zones in output configured : boolean include configured zones in output hide_global : boolean do not include global zone CLI Example: .. code-block:: bash salt '*' zoneadm.list """ zones = {} ## fetch zones header = "zoneid:zonename:state:zonepath:uuid:brand:ip-type".split(":") zone_data = __salt__["cmd.run_all"]("zoneadm list -p -c") if zone_data["retcode"] == 0: for zone in zone_data["stdout"].splitlines(): zone = zone.split(":") # create zone_t zone_t = {} for num, val in enumerate(header): zone_t[val] = zone[num] # skip if global and hide_global if hide_global and zone_t["zonename"] == "global": continue # skip installed and configured if not installed and zone_t["state"] == "installed": continue if not configured and zone_t["state"] == "configured": continue # update dict zones[zone_t["zonename"]] = zone_t del zones[zone_t["zonename"]]["zonename"] return zones if verbose else sorted(zones.keys()) def boot(zone, single=False, altinit=None, smf_options=None): """ Boot (or activate) the specified zone. zone : string name or uuid of the zone single : boolean boots only to milestone svc:/milestone/single-user:default. altinit : string valid path to an alternative executable to be the primordial process. smf_options : string include two categories of options to control booting behavior of the service management facility: recovery options and messages options. CLI Example: .. code-block:: bash salt '*' zoneadm.boot clementine salt '*' zoneadm.boot maeve single=True salt '*' zoneadm.boot teddy single=True smf_options=verbose """ ret = {"status": True} ## build boot_options boot_options = "" if single: boot_options = "-s {}".format(boot_options) if altinit: # note: we cannot validate the path, as this is local to the zonepath. boot_options = "-i {} {}".format(altinit, boot_options) if smf_options: boot_options = "-m {} {}".format(smf_options, boot_options) if boot_options != "": boot_options = " -- {}".format(boot_options.strip()) ## execute boot res = __salt__["cmd.run_all"]( "zoneadm {zone} boot{boot_opts}".format( zone="-u {}".format(zone) if _is_uuid(zone) else "-z {}".format(zone), boot_opts=boot_options, ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] ret["message"] = ret["message"].replace("zoneadm: ", "") if ret["message"] == "": del ret["message"] return ret def reboot(zone, single=False, altinit=None, smf_options=None): """ Restart the zone. This is equivalent to a halt boot sequence. zone : string name or uuid of the zone single : boolean boots only to milestone svc:/milestone/single-user:default. altinit : string valid path to an alternative executable to be the primordial process. smf_options : string include two categories of options to control booting behavior of the service management facility: recovery options and messages options. CLI Example: .. code-block:: bash salt '*' zoneadm.reboot dolores salt '*' zoneadm.reboot teddy single=True """ ret = {"status": True} ## build boot_options boot_options = "" if single: boot_options = "-s {}".format(boot_options) if altinit: # note: we cannot validate the path, as this is local to the zonepath. boot_options = "-i {} {}".format(altinit, boot_options) if smf_options: boot_options = "-m {} {}".format(smf_options, boot_options) if boot_options != "": boot_options = " -- {}".format(boot_options.strip()) ## execute reboot res = __salt__["cmd.run_all"]( "zoneadm {zone} reboot{boot_opts}".format( zone="-u {}".format(zone) if _is_uuid(zone) else "-z {}".format(zone), boot_opts=boot_options, ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] ret["message"] = ret["message"].replace("zoneadm: ", "") if ret["message"] == "": del ret["message"] return ret def halt(zone): """ Halt the specified zone. zone : string name or uuid of the zone .. note:: To cleanly shutdown the zone use the shutdown function. CLI Example: .. code-block:: bash salt '*' zoneadm.halt hector """ ret = {"status": True} ## halt zone res = __salt__["cmd.run_all"]( "zoneadm {zone} halt".format( zone="-u {}".format(zone) if _is_uuid(zone) else "-z {}".format(zone), ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] ret["message"] = ret["message"].replace("zoneadm: ", "") if ret["message"] == "": del ret["message"] return ret def shutdown(zone, reboot=False, single=False, altinit=None, smf_options=None): """ Gracefully shutdown the specified zone. zone : string name or uuid of the zone reboot : boolean reboot zone after shutdown (equivalent of shutdown -i6 -g0 -y) single : boolean boots only to milestone svc:/milestone/single-user:default. altinit : string valid path to an alternative executable to be the primordial process. smf_options : string include two categories of options to control booting behavior of the service management facility: recovery options and messages options. CLI Example: .. code-block:: bash salt '*' zoneadm.shutdown peter salt '*' zoneadm.shutdown armistice reboot=True """ ret = {"status": True} ## build boot_options boot_options = "" if single: boot_options = "-s {}".format(boot_options) if altinit: # note: we cannot validate the path, as this is local to the zonepath. boot_options = "-i {} {}".format(altinit, boot_options) if smf_options: boot_options = "-m {} {}".format(smf_options, boot_options) if boot_options != "": boot_options = " -- {}".format(boot_options.strip()) ## shutdown zone res = __salt__["cmd.run_all"]( "zoneadm {zone} shutdown{reboot}{boot_opts}".format( zone="-u {}".format(zone) if _is_uuid(zone) else "-z {}".format(zone), reboot=" -r" if reboot else "", boot_opts=boot_options, ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] ret["message"] = ret["message"].replace("zoneadm: ", "") if ret["message"] == "": del ret["message"] return ret def detach(zone): """ Detach the specified zone. zone : string name or uuid of the zone CLI Example: .. code-block:: bash salt '*' zoneadm.detach kissy """ ret = {"status": True} ## detach zone res = __salt__["cmd.run_all"]( "zoneadm {zone} detach".format( zone="-u {}".format(zone) if _is_uuid(zone) else "-z {}".format(zone), ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] ret["message"] = ret["message"].replace("zoneadm: ", "") if ret["message"] == "": del ret["message"] return ret def attach(zone, force=False, brand_opts=None): """ Attach the specified zone. zone : string name of the zone force : boolean force the zone into the "installed" state with no validation brand_opts : string brand specific options to pass CLI Example: .. code-block:: bash salt '*' zoneadm.attach lawrence salt '*' zoneadm.attach lawrence True """ ret = {"status": True} ## attach zone res = __salt__["cmd.run_all"]( "zoneadm -z {zone} attach{force}{brand_opts}".format( zone=zone, force=" -F" if force else "", brand_opts=" {}".format(brand_opts) if brand_opts else "", ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] ret["message"] = ret["message"].replace("zoneadm: ", "") if ret["message"] == "": del ret["message"] return ret def ready(zone): """ Prepares a zone for running applications. zone : string name or uuid of the zone CLI Example: .. code-block:: bash salt '*' zoneadm.ready clementine """ ret = {"status": True} ## ready zone res = __salt__["cmd.run_all"]( "zoneadm {zone} ready".format( zone="-u {}".format(zone) if _is_uuid(zone) else "-z {}".format(zone), ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] ret["message"] = ret["message"].replace("zoneadm: ", "") if ret["message"] == "": del ret["message"] return ret def verify(zone): """ Check to make sure the configuration of the specified zone can safely be installed on the machine. zone : string name of the zone CLI Example: .. code-block:: bash salt '*' zoneadm.verify dolores """ ret = {"status": True} ## verify zone res = __salt__["cmd.run_all"]( "zoneadm -z {zone} verify".format( zone=zone, ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] ret["message"] = ret["message"].replace("zoneadm: ", "") if ret["message"] == "": del ret["message"] return ret def move(zone, zonepath): """ Move zone to new zonepath. zone : string name or uuid of the zone zonepath : string new zonepath CLI Example: .. code-block:: bash salt '*' zoneadm.move meave /sweetwater/meave """ ret = {"status": True} ## verify zone res = __salt__["cmd.run_all"]( "zoneadm {zone} move {path}".format( zone="-u {}".format(zone) if _is_uuid(zone) else "-z {}".format(zone), path=zonepath, ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] ret["message"] = ret["message"].replace("zoneadm: ", "") if ret["message"] == "": del ret["message"] return ret def uninstall(zone): """ Uninstall the specified zone from the system. zone : string name or uuid of the zone .. warning:: The -F flag is always used to avoid the prompts when uninstalling. CLI Example: .. code-block:: bash salt '*' zoneadm.uninstall teddy """ ret = {"status": True} ## uninstall zone res = __salt__["cmd.run_all"]( "zoneadm {zone} uninstall -F".format( zone="-u {}".format(zone) if _is_uuid(zone) else "-z {}".format(zone), ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] ret["message"] = ret["message"].replace("zoneadm: ", "") if ret["message"] == "": del ret["message"] return ret def install(zone, nodataset=False, brand_opts=None): """ Install the specified zone from the system. zone : string name of the zone nodataset : boolean do not create a ZFS file system brand_opts : string brand specific options to pass CLI Example: .. code-block:: bash salt '*' zoneadm.install dolores salt '*' zoneadm.install teddy True """ ret = {"status": True} ## install zone res = __salt__["cmd.run_all"]( "zoneadm -z {zone} install{nodataset}{brand_opts}".format( zone=zone, nodataset=" -x nodataset" if nodataset else "", brand_opts=" {}".format(brand_opts) if brand_opts else "", ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] ret["message"] = ret["message"].replace("zoneadm: ", "") if ret["message"] == "": del ret["message"] return ret def clone(zone, source, snapshot=None): """ Install a zone by copying an existing installed zone. zone : string name of the zone source : string zone to clone from snapshot : string optional name of snapshot to use as source CLI Example: .. code-block:: bash salt '*' zoneadm.clone clementine dolores """ ret = {"status": True} ## install zone res = __salt__["cmd.run_all"]( "zoneadm -z {zone} clone {snapshot}{source}".format( zone=zone, source=source, snapshot="-s {} ".format(snapshot) if snapshot else "", ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] ret["message"] = ret["message"].replace("zoneadm: ", "") if ret["message"] == "": del ret["message"] return ret # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/zoneadm.py
0.636692
0.17515
zoneadm.py
pypi
import logging import salt.utils.compat import salt.utils.versions log = logging.getLogger(__name__) # pylint: disable=import-error try: # pylint: disable=unused-import import boto import boto3 # pylint: enable=unused-import from botocore.exceptions import ClientError logging.getLogger("boto3").setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=import-error def __virtual__(): """ Only load if boto libraries exist and if boto libraries are greater than a given version. """ # the boto_lambda execution module relies on the connect_to_region() method # which was added in boto 2.8.0 # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12 return salt.utils.versions.check_boto_reqs(boto3_ver="1.2.5") def __init__(opts): if HAS_BOTO: __utils__["boto3.assign_funcs"](__name__, "cloudtrail") def exists(Name, region=None, key=None, keyid=None, profile=None): """ Given a trail name, check to see if the given trail exists. Returns True if the given trail exists and returns False if the given trail does not exist. CLI Example: .. code-block:: bash salt myminion boto_cloudtrail.exists mytrail """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.get_trail_status(Name=Name) return {"exists": True} except ClientError as e: err = __utils__["boto3.get_error"](e) if e.response.get("Error", {}).get("Code") == "TrailNotFoundException": return {"exists": False} return {"error": err} def create( Name, S3BucketName, S3KeyPrefix=None, SnsTopicName=None, IncludeGlobalServiceEvents=None, IsMultiRegionTrail=None, EnableLogFileValidation=None, CloudWatchLogsLogGroupArn=None, CloudWatchLogsRoleArn=None, KmsKeyId=None, region=None, key=None, keyid=None, profile=None, ): """ Given a valid config, create a trail. Returns {created: true} if the trail was created and returns {created: False} if the trail was not created. CLI Example: .. code-block:: bash salt myminion boto_cloudtrail.create my_trail my_bucket """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) kwargs = {} for arg in ( "S3KeyPrefix", "SnsTopicName", "IncludeGlobalServiceEvents", "IsMultiRegionTrail", "EnableLogFileValidation", "CloudWatchLogsLogGroupArn", "CloudWatchLogsRoleArn", "KmsKeyId", ): if locals()[arg] is not None: kwargs[arg] = locals()[arg] trail = conn.create_trail(Name=Name, S3BucketName=S3BucketName, **kwargs) if trail: log.info("The newly created trail name is %s", trail["Name"]) return {"created": True, "name": trail["Name"]} else: log.warning("Trail was not created") return {"created": False} except ClientError as e: return {"created": False, "error": __utils__["boto3.get_error"](e)} def delete(Name, region=None, key=None, keyid=None, profile=None): """ Given a trail name, delete it. Returns {deleted: true} if the trail was deleted and returns {deleted: false} if the trail was not deleted. CLI Example: .. code-block:: bash salt myminion boto_cloudtrail.delete mytrail """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_trail(Name=Name) return {"deleted": True} except ClientError as e: return {"deleted": False, "error": __utils__["boto3.get_error"](e)} def describe(Name, region=None, key=None, keyid=None, profile=None): """ Given a trail name describe its properties. Returns a dictionary of interesting properties. CLI Example: .. code-block:: bash salt myminion boto_cloudtrail.describe mytrail """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) trails = conn.describe_trails(trailNameList=[Name]) if trails and trails.get("trailList"): keys = ( "Name", "S3BucketName", "S3KeyPrefix", "SnsTopicName", "IncludeGlobalServiceEvents", "IsMultiRegionTrail", "HomeRegion", "TrailARN", "LogFileValidationEnabled", "CloudWatchLogsLogGroupArn", "CloudWatchLogsRoleArn", "KmsKeyId", ) trail = trails["trailList"].pop() return {"trail": {k: trail.get(k) for k in keys}} else: return {"trail": None} except ClientError as e: err = __utils__["boto3.get_error"](e) if e.response.get("Error", {}).get("Code") == "TrailNotFoundException": return {"trail": None} return {"error": __utils__["boto3.get_error"](e)} def status(Name, region=None, key=None, keyid=None, profile=None): """ Given a trail name describe its properties. Returns a dictionary of interesting properties. CLI Example: .. code-block:: bash salt myminion boto_cloudtrail.describe mytrail """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) trail = conn.get_trail_status(Name=Name) if trail: keys = ( "IsLogging", "LatestDeliveryError", "LatestNotificationError", "LatestDeliveryTime", "LatestNotificationTime", "StartLoggingTime", "StopLoggingTime", "LatestCloudWatchLogsDeliveryError", "LatestCloudWatchLogsDeliveryTime", "LatestDigestDeliveryTime", "LatestDigestDeliveryError", "LatestDeliveryAttemptTime", "LatestNotificationAttemptTime", "LatestNotificationAttemptSucceeded", "LatestDeliveryAttemptSucceeded", "TimeLoggingStarted", "TimeLoggingStopped", ) return {"trail": {k: trail.get(k) for k in keys}} else: return {"trail": None} except ClientError as e: err = __utils__["boto3.get_error"](e) if e.response.get("Error", {}).get("Code") == "TrailNotFoundException": return {"trail": None} return {"error": __utils__["boto3.get_error"](e)} def list(region=None, key=None, keyid=None, profile=None): """ List all trails Returns list of trails CLI Example: .. code-block:: yaml policies: - {...} - {...} """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) trails = conn.describe_trails() if not bool(trails.get("trailList")): log.warning("No trails found") return {"trails": trails.get("trailList", [])} except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} def update( Name, S3BucketName, S3KeyPrefix=None, SnsTopicName=None, IncludeGlobalServiceEvents=None, IsMultiRegionTrail=None, EnableLogFileValidation=None, CloudWatchLogsLogGroupArn=None, CloudWatchLogsRoleArn=None, KmsKeyId=None, region=None, key=None, keyid=None, profile=None, ): """ Given a valid config, update a trail. Returns {created: true} if the trail was created and returns {created: False} if the trail was not created. CLI Example: .. code-block:: bash salt myminion boto_cloudtrail.update my_trail my_bucket """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) kwargs = {} for arg in ( "S3KeyPrefix", "SnsTopicName", "IncludeGlobalServiceEvents", "IsMultiRegionTrail", "EnableLogFileValidation", "CloudWatchLogsLogGroupArn", "CloudWatchLogsRoleArn", "KmsKeyId", ): if locals()[arg] is not None: kwargs[arg] = locals()[arg] trail = conn.update_trail(Name=Name, S3BucketName=S3BucketName, **kwargs) if trail: log.info("The updated trail name is %s", trail["Name"]) return {"updated": True, "name": trail["Name"]} else: log.warning("Trail was not created") return {"updated": False} except ClientError as e: return {"updated": False, "error": __utils__["boto3.get_error"](e)} def start_logging(Name, region=None, key=None, keyid=None, profile=None): """ Start logging for a trail Returns {started: true} if the trail was started and returns {started: False} if the trail was not started. CLI Example: .. code-block:: bash salt myminion boto_cloudtrail.start_logging my_trail """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.start_logging(Name=Name) return {"started": True} except ClientError as e: return {"started": False, "error": __utils__["boto3.get_error"](e)} def stop_logging(Name, region=None, key=None, keyid=None, profile=None): """ Stop logging for a trail Returns {stopped: true} if the trail was stopped and returns {stopped: False} if the trail was not stopped. CLI Example: .. code-block:: bash salt myminion boto_cloudtrail.stop_logging my_trail """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.stop_logging(Name=Name) return {"stopped": True} except ClientError as e: return {"stopped": False, "error": __utils__["boto3.get_error"](e)} def _get_trail_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith("arn:aws:cloudtrail:"): return name account_id = __salt__["boto_iam.get_account_id"]( region=region, key=key, keyid=keyid, profile=profile ) if profile and "region" in profile: region = profile["region"] if region is None: region = "us-east-1" return "arn:aws:cloudtrail:{}:{}:trail/{}".format(region, account_id, name) def add_tags(Name, region=None, key=None, keyid=None, profile=None, **kwargs): """ Add tags to a trail Returns {tagged: true} if the trail was tagged and returns {tagged: False} if the trail was not tagged. CLI Example: .. code-block:: bash salt myminion boto_cloudtrail.add_tags my_trail tag_a=tag_value tag_b=tag_value """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) tagslist = [] for k, v in kwargs.items(): if str(k).startswith("__"): continue tagslist.append({"Key": str(k), "Value": str(v)}) conn.add_tags( ResourceId=_get_trail_arn( Name, region=region, key=key, keyid=keyid, profile=profile ), TagsList=tagslist, ) return {"tagged": True} except ClientError as e: return {"tagged": False, "error": __utils__["boto3.get_error"](e)} def remove_tags(Name, region=None, key=None, keyid=None, profile=None, **kwargs): """ Remove tags from a trail Returns {tagged: true} if the trail was tagged and returns {tagged: False} if the trail was not tagged. CLI Example: .. code-block:: bash salt myminion boto_cloudtrail.remove_tags my_trail tag_a=tag_value tag_b=tag_value """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) tagslist = [] for k, v in kwargs.items(): if str(k).startswith("__"): continue tagslist.append({"Key": str(k), "Value": str(v)}) conn.remove_tags( ResourceId=_get_trail_arn( Name, region=region, key=key, keyid=keyid, profile=profile ), TagsList=tagslist, ) return {"tagged": True} except ClientError as e: return {"tagged": False, "error": __utils__["boto3.get_error"](e)} def list_tags(Name, region=None, key=None, keyid=None, profile=None): """ List tags of a trail Returns: tags: - {...} - {...} CLI Example: .. code-block:: bash salt myminion boto_cloudtrail.list_tags my_trail """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) rid = _get_trail_arn(Name, region=region, key=key, keyid=keyid, profile=profile) ret = conn.list_tags(ResourceIdList=[rid]) tlist = ret.get("ResourceTagList", []).pop().get("TagsList") tagdict = {} for tag in tlist: tagdict[tag.get("Key")] = tag.get("Value") return {"tags": tagdict} except ClientError as e: return {"error": __utils__["boto3.get_error"](e)}
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/modules/boto_cloudtrail.py
0.578448
0.164097
boto_cloudtrail.py
pypi
import logging import re try: import pymongo HAS_PYMONGO = True except ImportError: HAS_PYMONGO = False __opts__ = { "mongo.db": "salt", "mongo.host": "salt", "mongo.password": "", "mongo.port": 27017, "mongo.user": "", } def __virtual__(): if not HAS_PYMONGO: return False return "mongo" # Set up logging log = logging.getLogger(__name__) def top(**kwargs): """ Connect to a mongo database and read per-node tops data. Parameters: * `collection`: The mongodb collection to read data from. Defaults to ``'tops'``. * `id_field`: The field in the collection that represents an individual minion id. Defaults to ``'_id'``. * `re_pattern`: If your naming convention in the collection is shorter than the minion id, you can use this to trim the name. `re_pattern` will be used to match the name, and `re_replace` will be used to replace it. Backrefs are supported as they are in the Python standard library. If ``None``, no mangling of the name will be performed - the collection will be searched with the entire minion id. Defaults to ``None``. * `re_replace`: Use as the replacement value in node ids matched with `re_pattern`. Defaults to ''. Feel free to use backreferences here. * `states_field`: The name of the field providing a list of states. * `environment_field`: The name of the field providing the environment. Defaults to ``environment``. """ host = __opts__["mongo.host"] port = __opts__["mongo.port"] collection = __opts__["master_tops"]["mongo"].get("collection", "tops") id_field = __opts__["master_tops"]["mongo"].get("id_field", "_id") re_pattern = __opts__["master_tops"]["mongo"].get("re_pattern", "") re_replace = __opts__["master_tops"]["mongo"].get("re_replace", "") states_field = __opts__["master_tops"]["mongo"].get("states_field", "states") environment_field = __opts__["master_tops"]["mongo"].get( "environment_field", "environment" ) log.info("connecting to %s:%s for mongo ext_tops", host, port) conn = pymongo.MongoClient(host, port) log.debug("using database '%s'", __opts__["mongo.db"]) mdb = conn[__opts__["mongo.db"]] user = __opts__.get("mongo.user") password = __opts__.get("mongo.password") if user and password: log.debug("authenticating as '%s'", user) mdb.authenticate(user, password) # Do the regex string replacement on the minion id minion_id = kwargs["opts"]["id"] if re_pattern: minion_id = re.sub(re_pattern, re_replace, minion_id) log.info( "ext_tops.mongo: looking up tops def for {'%s': '%s'} in mongo", id_field, minion_id, ) result = mdb[collection].find_one( {id_field: minion_id}, projection=[states_field, environment_field] ) if result and states_field in result: if environment_field in result: environment = result[environment_field] else: environment = "base" log.debug("ext_tops.mongo: found document, returning states") return {environment: result[states_field]} else: # If we can't find the minion the database it's not necessarily an # error. log.debug("ext_tops.mongo: no document found in collection %s", collection) return {}
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/tops/mongo.py
0.591015
0.308385
mongo.py
pypi
from salt.utils.schema import ( ArrayItem, BooleanItem, ComplexSchemaItem, DefinitionsSchema, IntegerItem, OneOfItem, Schema, StringItem, ) class VMwareScsiAddressItem(StringItem): pattern = r"vmhba\d+:C\d+:T\d+:L\d+" class DiskGroupDiskScsiAddressItem(ComplexSchemaItem): """ Schema item of a ESXi host disk group containing disk SCSI addresses """ title = "Diskgroup Disk Scsi Address Item" description = "ESXi host diskgroup item containing disk SCSI addresses" cache_scsi_addr = VMwareScsiAddressItem( title="Cache Disk Scsi Address", description="Specifies the SCSI address of the cache disk", required=True, ) capacity_scsi_addrs = ArrayItem( title="Capacity Scsi Addresses", description="Array with the SCSI addresses of the capacity disks", items=VMwareScsiAddressItem(), min_items=1, ) class DiskGroupDiskIdItem(ComplexSchemaItem): """ Schema item of a ESXi host disk group containg disk ids """ title = "Diskgroup Disk Id Item" description = "ESXi host diskgroup item containing disk ids" cache_id = StringItem( title="Cache Disk Id", description="Specifies the id of the cache disk", pattern=r"[^\s]+", ) capacity_ids = ArrayItem( title="Capacity Disk Ids", description="Array with the ids of the capacity disks", items=StringItem(pattern=r"[^\s]+"), min_items=1, ) class DiskGroupsDiskScsiAddressSchema(DefinitionsSchema): """ Schema of ESXi host diskgroups containing disk SCSI addresses """ title = "Diskgroups Disk Scsi Address Schema" description = "ESXi host diskgroup schema containing disk SCSI addresses" diskgroups = ArrayItem( title="Diskgroups", description="List of diskgroups in an ESXi host", min_items=1, items=DiskGroupDiskScsiAddressItem(), required=True, ) erase_disks = BooleanItem(title="Erase Diskgroup Disks", required=True) class DiskGroupsDiskIdSchema(DefinitionsSchema): """ Schema of ESXi host diskgroups containing disk ids """ title = "Diskgroups Disk Id Schema" description = "ESXi host diskgroup schema containing disk ids" diskgroups = ArrayItem( title="DiskGroups", description="List of disk groups in an ESXi host", min_items=1, items=DiskGroupDiskIdItem(), required=True, ) class VmfsDatastoreDiskIdItem(ComplexSchemaItem): """ Schema item of a VMFS datastore referencing a backing disk id """ title = "VMFS Datastore Disk Id Item" description = "VMFS datastore item referencing a backing disk id" name = StringItem( title="Name", description="Specifies the name of the VMFS datastore", required=True, ) backing_disk_id = StringItem( title="Backing Disk Id", description="Specifies the id of the disk backing the VMFS datastore", pattern=r"[^\s]+", required=True, ) vmfs_version = IntegerItem( title="VMFS Version", description="VMFS version", enum=[1, 2, 3, 5] ) class VmfsDatastoreDiskScsiAddressItem(ComplexSchemaItem): """ Schema item of a VMFS datastore referencing a backing disk SCSI address """ title = "VMFS Datastore Disk Scsi Address Item" description = "VMFS datastore item referencing a backing disk SCSI address" name = StringItem( title="Name", description="Specifies the name of the VMFS datastore", required=True, ) backing_disk_scsi_addr = VMwareScsiAddressItem( title="Backing Disk Scsi Address", description="Specifies the SCSI address of the disk backing the VMFS datastore", required=True, ) vmfs_version = IntegerItem( title="VMFS Version", description="VMFS version", enum=[1, 2, 3, 5] ) class VmfsDatastoreSchema(DefinitionsSchema): """ Schema of a VMFS datastore """ title = "VMFS Datastore Schema" description = "Schema of a VMFS datastore" datastore = OneOfItem( items=[VmfsDatastoreDiskScsiAddressItem(), VmfsDatastoreDiskIdItem()], required=True, ) class HostCacheSchema(DefinitionsSchema): """ Schema of ESXi host cache """ title = "Host Cache Schema" description = "Schema of the ESXi host cache" enabled = BooleanItem(title="Enabled", required=True) datastore = VmfsDatastoreDiskScsiAddressItem(required=True) swap_size = StringItem( title="Host cache swap size (in GB or %)", pattern=r"(\d+GiB)|(([0-9]|([1-9][0-9])|100)%)", required=True, ) erase_backing_disk = BooleanItem(title="Erase Backup Disk", required=True) class SimpleHostCacheSchema(Schema): """ Simplified Schema of ESXi host cache """ title = "Simple Host Cache Schema" description = "Simplified schema of the ESXi host cache" enabled = BooleanItem(title="Enabled", required=True) datastore_name = StringItem(title="Datastore Name", required=True) swap_size_MiB = IntegerItem(title="Host cache swap size in MiB", minimum=1) class EsxiProxySchema(Schema): """ Schema of the esxi proxy input """ title = "Esxi Proxy Schema" description = "Esxi proxy schema" additional_properties = False proxytype = StringItem(required=True, enum=["esxi"]) host = StringItem(pattern=r"[^\s]+") # Used when connecting directly vcenter = StringItem(pattern=r"[^\s]+") # Used when connecting via a vCenter esxi_host = StringItem() username = StringItem() passwords = ArrayItem(min_items=1, items=StringItem(), unique_items=True) mechanism = StringItem(enum=["userpass", "sspi"]) # TODO Should be changed when anyOf is supported for schemas domain = StringItem() principal = StringItem() protocol = StringItem() port = IntegerItem(minimum=1)
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/config/schemas/esxi.py
0.600071
0.223462
esxi.py
pypi
from salt.utils.schema import ( AnyOfItem, ArrayItem, BooleanItem, ComplexSchemaItem, DefinitionsSchema, DictItem, IntegerItem, Schema, StringItem, ) class OptionValueItem(ComplexSchemaItem): """Sechma item of the OptionValue""" title = "OptionValue" key = StringItem(title="Key", required=True) value = AnyOfItem(items=[StringItem(), BooleanItem(), IntegerItem()]) class AdmissionControlPolicyItem(ComplexSchemaItem): """ Schema item of the HA admission control policy """ title = "Admission Control Policy" cpu_failover_percent = IntegerItem( title="CPU Failover Percent", minimum=0, maximum=100 ) memory_failover_percent = IntegerItem( title="Memory Failover Percent", minimum=0, maximum=100 ) class DefaultVmSettingsItem(ComplexSchemaItem): """ Schema item of the HA default vm settings """ title = "Default VM Settings" isolation_response = StringItem( title="Isolation Response", enum=["clusterIsolationResponse", "none", "powerOff", "shutdown"], ) restart_priority = StringItem( title="Restart Priority", enum=["clusterRestartPriority", "disabled", "high", "low", "medium"], ) class HAConfigItem(ComplexSchemaItem): """ Schema item of ESX cluster high availability """ title = "HA Configuration" description = "ESX cluster HA configuration json schema item" enabled = BooleanItem( title="Enabled", description="Specifies if HA should be enabled" ) admission_control_enabled = BooleanItem(title="Admission Control Enabled") admission_control_policy = AdmissionControlPolicyItem() default_vm_settings = DefaultVmSettingsItem() hb_ds_candidate_policy = StringItem( title="Heartbeat Datastore Candidate Policy", enum=["allFeasibleDs", "allFeasibleDsWithUserPreference", "userSelectedDs"], ) host_monitoring = StringItem( title="Host Monitoring", choices=["enabled", "disabled"] ) options = ArrayItem(min_items=1, items=OptionValueItem()) vm_monitoring = StringItem( title="Vm Monitoring", choices=["vmMonitoringDisabled", "vmAndAppMonitoring", "vmMonitoringOnly"], ) class vSANClusterConfigItem(ComplexSchemaItem): """ Schema item of the ESX cluster vSAN configuration """ title = "vSAN Configuration" description = "ESX cluster vSAN configurationi item" enabled = BooleanItem( title="Enabled", description="Specifies if vSAN should be enabled" ) auto_claim_storage = BooleanItem( title="Auto Claim Storage", description=( "Specifies whether the storage of member ESXi hosts should " "be automatically claimed for vSAN" ), ) dedup_enabled = BooleanItem( title="Enabled", description="Specifies dedup should be enabled" ) compression_enabled = BooleanItem( title="Enabled", description="Specifies if compression should be enabled" ) class DRSConfigItem(ComplexSchemaItem): """ Schema item of the ESX cluster DRS configuration """ title = "DRS Configuration" description = "ESX cluster DRS configuration item" enabled = BooleanItem( title="Enabled", description="Specifies if DRS should be enabled" ) vmotion_rate = IntegerItem( title="vMotion rate", description=( "Aggressiveness to do automatic vMotions: " "1 (least aggressive) - 5 (most aggressive)" ), minimum=1, maximum=5, ) default_vm_behavior = StringItem( title="Default VM DRS Behavior", description="Specifies the default VM DRS behavior", enum=["fullyAutomated", "partiallyAutomated", "manual"], ) class ESXClusterConfigSchema(DefinitionsSchema): """ Schema of the ESX cluster config """ title = "ESX Cluster Configuration Schema" description = "ESX cluster configuration schema" ha = HAConfigItem() vsan = vSANClusterConfigItem() drs = DRSConfigItem() vm_swap_placement = StringItem(title="VM Swap Placement") class ESXClusterEntitySchema(Schema): """Schema of the ESX cluster entity""" title = "ESX Cluster Entity Schema" description = "ESX cluster entity schema" type = StringItem( title="Type", description="Specifies the entity type", required=True, enum=["cluster"], ) datacenter = StringItem( title="Datacenter", description="Specifies the cluster datacenter", required=True, pattern=r"\w+", ) cluster = StringItem( title="Cluster", description="Specifies the cluster name", required=True, pattern=r"\w+", ) class LicenseSchema(Schema): """ Schema item of the ESX cluster vSAN configuration """ title = "Licenses schema" description = "License configuration schema" licenses = DictItem( title="Licenses", description="Dictionary containing the license name to key mapping", required=True, additional_properties=StringItem( title="License Key", description="Specifies the license key", pattern=r"^(\w{5}-\w{5}-\w{5}-\w{5}-\w{5})$", ), ) class EsxclusterProxySchema(Schema): """ Schema of the esxcluster proxy input """ title = "Esxcluster Proxy Schema" description = "Esxcluster proxy schema" additional_properties = False proxytype = StringItem(required=True, enum=["esxcluster"]) vcenter = StringItem(required=True, pattern=r"[^\s]+") datacenter = StringItem(required=True) cluster = StringItem(required=True) mechanism = StringItem(required=True, enum=["userpass", "sspi"]) username = StringItem() passwords = ArrayItem(min_items=1, items=StringItem(), unique_items=True) # TODO Should be changed when anyOf is supported for schemas domain = StringItem() principal = StringItem() protocol = StringItem() port = IntegerItem(minimum=1)
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/config/schemas/esxcluster.py
0.73782
0.204005
esxcluster.py
pypi
from salt.utils.schema import ( AnyOfItem, ArrayItem, BooleanItem, ComplexSchemaItem, DefinitionsSchema, IntegerItem, IPv4Item, NullItem, NumberItem, StringItem, ) class ESXVirtualMachineSerialBackingItem(ComplexSchemaItem): """ Configuration Schema Item for ESX Virtual Machine Serial Port Backing """ title = "ESX Virtual Machine Serial Port Backing" description = "ESX virtual machine serial port backing" required = True uri = StringItem() direction = StringItem(enum=("client", "server")) filename = StringItem() class ESXVirtualMachineDeviceConnectionItem(ComplexSchemaItem): """ Configuration Schema Item for ESX Virtual Machine Serial Port Connection """ title = "ESX Virtual Machine Serial Port Connection" description = "ESX virtual machine serial port connection" required = True allow_guest_control = BooleanItem(default=True) start_connected = BooleanItem(default=True) class ESXVirtualMachinePlacementSchemaItem(ComplexSchemaItem): """ Configuration Schema Item for ESX Virtual Machine Placement """ title = "ESX Virtual Machine Placement Information" description = "ESX virtual machine placement property" required = True cluster = StringItem( title="Virtual Machine Cluster", description="Cluster of the virtual machine if it is placed to a cluster", ) host = StringItem( title="Virtual Machine Host", description="Host of the virtual machine if it is placed to a standalone host", ) resourcepool = StringItem( title="Virtual Machine Resource Pool", description=( "Resource pool of the virtual machine if it is placed to a resource pool" ), ) folder = StringItem( title="Virtual Machine Folder", description=( "Folder of the virtual machine where it should be deployed, default is the" " datacenter vmFolder" ), ) class ESXVirtualMachineCdDriveClientSchemaItem(ComplexSchemaItem): """ Configuration Schema Item for ESX Virtual Machine CD Drive Client """ title = "ESX Virtual Machine Serial CD Client" description = "ESX virtual machine CD/DVD drive client properties" mode = StringItem(required=True, enum=("passthrough", "atapi")) class ESXVirtualMachineCdDriveIsoSchemaItem(ComplexSchemaItem): """ Configuration Schema Item for ESX Virtual Machine CD Drive ISO """ title = "ESX Virtual Machine Serial CD ISO" description = "ESX virtual machine CD/DVD drive ISO properties" path = StringItem(required=True) class ESXVirtualMachineCdDriveSchemaItem(ComplexSchemaItem): """ Configuration Schema Item for ESX Virtual Machine CD Drives """ title = "ESX Virtual Machine Serial CD" description = "ESX virtual machine CD/DVD drive properties" adapter = StringItem( title="Virtual Machine CD/DVD Adapter", description="Unique adapter name for virtual machine cd/dvd drive", required=True, ) controller = StringItem(required=True) device_type = StringItem( title="Virtual Machine Device Type", description="CD/DVD drive of the virtual machine if it is placed to a cluster", required=True, default="client_device", enum=("datastore_iso_file", "client_device"), ) client_device = ESXVirtualMachineCdDriveClientSchemaItem() datastore_iso_file = ESXVirtualMachineCdDriveIsoSchemaItem() connectable = ESXVirtualMachineDeviceConnectionItem() class ESXVirtualMachineSerialSchemaItem(ComplexSchemaItem): """ Configuration Schema Item for ESX Virtual Machine Serial Port """ title = "ESX Virtual Machine Serial Port Configuration" description = "ESX virtual machine serial port properties" type = StringItem( title="Virtual Machine Serial Port Type", required=True, enum=("network", "pipe", "file", "device"), ) adapter = StringItem( title="Virtual Machine Serial Port Name", description=( "Unique adapter name for virtual machine serial port " "for creation an arbitrary value should be specified" ), required=True, ) backing = ESXVirtualMachineSerialBackingItem() connectable = ESXVirtualMachineDeviceConnectionItem() yield_port = BooleanItem( title="Serial Port Yield", description="Serial port yield", default=False ) class ESXVirtualMachineScsiSchemaItem(ComplexSchemaItem): """ Configuration Schema Item for ESX Virtual Machine SCSI Controller """ title = "ESX Virtual Machine SCSI Controller Configuration" description = "ESX virtual machine scsi controller properties" required = True adapter = StringItem( title="Virtual Machine SCSI Controller Name", description=( "Unique SCSI controller name " "for creation an arbitrary value should be specified" ), required=True, ) type = StringItem( title="Virtual Machine SCSI type", description="Type of the SCSI controller", required=True, enum=("lsilogic", "lsilogic_sas", "paravirtual", "buslogic"), ) bus_sharing = StringItem( title="Virtual Machine SCSI bus sharing", description="Sharing type of the SCSI bus", required=True, enum=("virtual_sharing", "physical_sharing", "no_sharing"), ) bus_number = NumberItem( title="Virtual Machine SCSI bus number", description="Unique bus number of the SCSI device", required=True, ) class ESXVirtualMachineSataSchemaItem(ComplexSchemaItem): """ Configuration Schema Item for ESX Virtual Machine SATA Controller """ title = "ESX Virtual Machine SATA Controller Configuration" description = "ESX virtual machine SATA controller properties" required = False adapter = StringItem( title="Virtual Machine SATA Controller Name", description=( "Unique SATA controller name " "for creation an arbitrary value should be specified" ), required=True, ) bus_number = NumberItem( title="Virtual Machine SATA bus number", description="Unique bus number of the SATA device", required=True, ) class ESXVirtualMachineDiskSchemaItem(ComplexSchemaItem): """ Configuration Schema Item for ESX Virtual Machine Disk """ title = "ESX Virtual Machine Disk Configuration" description = "ESX virtual machine disk properties" required = True size = NumberItem( title="Disk size", description="Size of the disk in GB", required=True ) unit = StringItem( title="Disk size unit", description=( "Unit of the disk size, to VMware a GB is the same as GiB = 1024MiB" ), required=False, default="GB", enum=("KB", "MB", "GB"), ) adapter = StringItem( title="Virtual Machine Adapter Name", description=( "Unique adapter name for virtual machine " "for creation an arbitrary value should be specified" ), required=True, ) filename = StringItem( title="Virtual Machine Disk File", description="File name of the virtual machine vmdk", ) datastore = StringItem( title="Virtual Machine Disk Datastore", description="Disk datastore where the virtual machine files will be placed", required=True, ) address = StringItem( title="Virtual Machine SCSI Address", description="Address of the SCSI adapter for the virtual machine", pattern=r"\d:\d", ) thin_provision = BooleanItem( title="Virtual Machine Disk Provision Type", description="Provision type of the disk", default=True, required=False, ) eagerly_scrub = AnyOfItem(required=False, items=[BooleanItem(), NullItem()]) controller = StringItem( title="Virtual Machine SCSI Adapter", description="Name of the SCSI adapter where the disk will be connected", required=True, ) class ESXVirtualMachineNicMapSchemaItem(ComplexSchemaItem): """ Configuration Schema Item for ESX Virtual Machine Nic Map """ title = "ESX Virtual Machine Nic Configuration" description = "ESX Virtual Machine nic properties" required = False domain = StringItem() gateway = IPv4Item() ip_addr = IPv4Item() subnet_mask = IPv4Item() class ESXVirtualMachineInterfaceSchemaItem(ComplexSchemaItem): """ Configuration Schema Item for ESX Virtual Machine Network Interface """ title = "ESX Virtual Machine Network Interface Configuration" description = "ESX Virtual Machine network adapter properties" required = True name = StringItem( title="Virtual Machine Port Group", description="Specifies the port group name for the virtual machine connection", required=True, ) adapter = StringItem( title="Virtual Machine Network Adapter", description=( "Unique name of the network adapter, " "for creation an arbitrary value should be specified" ), required=True, ) adapter_type = StringItem( title="Virtual Machine Adapter Type", description="Network adapter type of the virtual machine", required=True, enum=("vmxnet", "vmxnet2", "vmxnet3", "e1000", "e1000e"), default="vmxnet3", ) switch_type = StringItem( title="Virtual Machine Switch Type", description=( "Specifies the type of the virtual switch for the virtual machine" " connection" ), required=True, default="standard", enum=("standard", "distributed"), ) mac = StringItem( title="Virtual Machine MAC Address", description="Mac address of the virtual machine", required=False, pattern="^([0-9a-f]{1,2}[:]){5}([0-9a-f]{1,2})$", ) mapping = ESXVirtualMachineNicMapSchemaItem() connectable = ESXVirtualMachineDeviceConnectionItem() class ESXVirtualMachineMemorySchemaItem(ComplexSchemaItem): """ Configurtation Schema Item for ESX Virtual Machine Memory """ title = "ESX Virtual Machine Memory Configuration" description = "ESX Virtual Machine memory property" required = True size = IntegerItem( title="Memory size", description="Size of the memory", required=True ) unit = StringItem( title="Memory unit", description="Unit of the memory, to VMware a GB is the same as GiB = 1024MiB", required=False, default="MB", enum=("MB", "GB"), ) hotadd = BooleanItem(required=False, default=False) reservation_max = BooleanItem(required=False, default=False) class ESXVirtualMachineCpuSchemaItem(ComplexSchemaItem): """ Configurtation Schema Item for ESX Virtual Machine CPU """ title = "ESX Virtual Machine Memory Configuration" description = "ESX Virtual Machine memory property" required = True count = IntegerItem( title="CPU core count", description="CPU core count", required=True ) cores_per_socket = IntegerItem( title="CPU cores per socket", description="CPU cores per socket count", required=False, ) nested = BooleanItem( title="Virtual Machine Nested Property", description="Nested virtualization support", default=False, ) hotadd = BooleanItem( title="Virtual Machine CPU hot add", description="CPU hot add", default=False ) hotremove = BooleanItem( title="Virtual Machine CPU hot remove", description="CPU hot remove", default=False, ) class ESXVirtualMachineConfigSchema(DefinitionsSchema): """ Configuration Schema for ESX Virtual Machines """ title = "ESX Virtual Machine Configuration Schema" description = "ESX Virtual Machine configuration schema" vm_name = StringItem( title="Virtual Machine name", description="Name of the virtual machine", required=True, ) cpu = ESXVirtualMachineCpuSchemaItem() memory = ESXVirtualMachineMemorySchemaItem() image = StringItem( title="Virtual Machine guest OS", description="Guest OS type", required=True ) version = StringItem( title="Virtual Machine hardware version", description="Container hardware version property", required=True, ) interfaces = ArrayItem( items=ESXVirtualMachineInterfaceSchemaItem(), min_items=1, required=False, unique_items=True, ) disks = ArrayItem( items=ESXVirtualMachineDiskSchemaItem(), min_items=1, required=False, unique_items=True, ) scsi_devices = ArrayItem( items=ESXVirtualMachineScsiSchemaItem(), min_items=1, required=False, unique_items=True, ) serial_ports = ArrayItem( items=ESXVirtualMachineSerialSchemaItem(), min_items=0, required=False, unique_items=True, ) cd_dvd_drives = ArrayItem( items=ESXVirtualMachineCdDriveSchemaItem(), min_items=0, required=False, unique_items=True, ) sata_controllers = ArrayItem( items=ESXVirtualMachineSataSchemaItem(), min_items=0, required=False, unique_items=True, ) datacenter = StringItem( title="Virtual Machine Datacenter", description="Datacenter of the virtual machine", required=True, ) datastore = StringItem( title="Virtual Machine Datastore", description="Datastore of the virtual machine", required=True, ) placement = ESXVirtualMachinePlacementSchemaItem() template = BooleanItem( title="Virtual Machine Template", description="Template to create the virtual machine from", default=False, ) tools = BooleanItem( title="Virtual Machine VMware Tools", description="Install VMware tools on the guest machine", default=False, ) power_on = BooleanItem( title="Virtual Machine Power", description="Power on virtual machine afret creation", default=False, ) deploy = BooleanItem( title="Virtual Machine Deploy Salt", description="Deploy salt after successful installation", default=False, ) class ESXVirtualMachineRemoveSchema(DefinitionsSchema): """ Remove Schema for ESX Virtual Machines to delete or unregister virtual machines """ name = StringItem( title="Virtual Machine name", description="Name of the virtual machine", required=True, ) datacenter = StringItem( title="Virtual Machine Datacenter", description="Datacenter of the virtual machine", required=True, ) placement = AnyOfItem( required=False, items=[ESXVirtualMachinePlacementSchemaItem(), NullItem()] ) power_off = BooleanItem( title="Power off vm", description="Power off vm before delete operation", required=False, ) class ESXVirtualMachineDeleteSchema(ESXVirtualMachineRemoveSchema): """ Deletion Schema for ESX Virtual Machines """ class ESXVirtualMachineUnregisterSchema(ESXVirtualMachineRemoveSchema): """ Unregister Schema for ESX Virtual Machines """
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/config/schemas/esxvm.py
0.810816
0.232147
esxvm.py
pypi
from salt.config.schemas.minion import MinionConfiguration from salt.utils.schema import ( AnyOfItem, BooleanItem, DictItem, IntegerItem, PortItem, RequirementsItem, Schema, SecretItem, StringItem, ) class RosterEntryConfig(Schema): """ Schema definition of a Salt SSH Roster entry """ title = "Roster Entry" description = "Salt SSH roster entry definition" host = StringItem( title="Host", description="The IP address or DNS name of the remote host", # Pretty naive pattern matching pattern=r"^((\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|([A-Za-z0-9][A-Za-z0-9\.\-]{1,255}))$", min_length=1, required=True, ) port = PortItem( title="Port", description="The target system's ssh port number", default=22 ) user = StringItem( title="User", description="The user to log in as. Defaults to root", default="root", min_length=1, required=True, ) passwd = SecretItem( title="Password", description="The password to log in with", min_length=1 ) priv = StringItem( title="Private Key", description="File path to ssh private key, defaults to salt-ssh.rsa", min_length=1, ) priv_passwd = SecretItem( title="Private Key passphrase", description="Passphrase for private key file", min_length=1, ) passwd_or_priv_requirement = AnyOfItem( items=( RequirementsItem(requirements=["passwd"]), RequirementsItem(requirements=["priv"]), ) )(flatten=True) sudo = BooleanItem( title="Sudo", description="run command via sudo. Defaults to False", default=False, ) timeout = IntegerItem( title="Timeout", description=( "Number of seconds to wait for response when establishing an SSH connection" ), ) thin_dir = StringItem( title="Thin Directory", description=( "The target system's storage directory for Salt " "components. Defaults to /tmp/salt-<hash>." ), ) minion_opts = DictItem( title="Minion Options", description="Dictionary of minion options", properties=MinionConfiguration(), ) class RosterItem(Schema): title = "Roster Configuration" description = "Roster entries definition" roster_entries = DictItem(pattern_properties={r"^([^:]+)$": RosterEntryConfig()})( flatten=True )
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/config/schemas/ssh.py
0.57821
0.1811
ssh.py
pypi
import os def __virtual__(): """ Only load if the snapper module is available in __salt__ """ if "snapper.diff" in __salt__: return "snapper" return (False, "snapper module could not be loaded") def _get_baseline_from_tag(config, tag): """ Returns the last created baseline snapshot marked with `tag` """ last_snapshot = None for snapshot in __salt__["snapper.list_snapshots"](config): if tag == snapshot["userdata"].get("baseline_tag"): if not last_snapshot or last_snapshot["timestamp"] < snapshot["timestamp"]: last_snapshot = snapshot return last_snapshot def baseline_snapshot( name, number=None, tag=None, include_diff=True, config="root", ignore=None ): """ Enforces that no file is modified comparing against a previously defined snapshot identified by number. number Number of selected baseline snapshot. tag Tag of the selected baseline snapshot. Most recent baseline baseline snapshot is used in case of multiple snapshots with the same tag. (`tag` and `number` cannot be used at the same time) include_diff Include a diff in the response (Default: True) config Snapper config name (Default: root) ignore List of files to ignore. (Default: None) """ if not ignore: ignore = [] ret = {"changes": {}, "comment": "", "name": name, "result": True} if number is None and tag is None: ret.update( {"result": False, "comment": "Snapshot tag or number must be specified"} ) return ret if number and tag: ret.update( { "result": False, "comment": "Cannot use snapshot tag and number at the same time", } ) return ret if tag: snapshot = _get_baseline_from_tag(config, tag) if not snapshot: ret.update( {"result": False, "comment": 'Baseline tag "{}" not found'.format(tag)} ) return ret number = snapshot["id"] status = __salt__["snapper.status"](config, num_pre=0, num_post=number) for target in ignore: if os.path.isfile(target): status.pop(target, None) elif os.path.isdir(target): for target_file in [ target_file for target_file in status.keys() if target_file.startswith(target) ]: status.pop(target_file, None) for file in status: # Only include diff for modified files if "modified" in status[file]["status"] and include_diff: status[file].pop("status") status[file].update( __salt__["snapper.diff"]( config, num_pre=0, num_post=number, filename=file ).get(file, {}) ) if __opts__["test"] and status: ret["changes"] = status ret["comment"] = "{} files changes are set to be undone".format( len(status.keys()) ) ret["result"] = None elif __opts__["test"] and not status: ret["changes"] = {} ret["comment"] = "Nothing to be done" ret["result"] = True elif not __opts__["test"] and status: undo = __salt__["snapper.undo"]( config, num_pre=number, num_post=0, files=status.keys() ) ret["changes"]["sumary"] = undo ret["changes"]["files"] = status ret["result"] = True else: ret["comment"] = "No changes were done" ret["result"] = True return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/states/snapper.py
0.695441
0.210442
snapper.py
pypi
import logging import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = "certutil" def __virtual__(): """ Only work on Windows """ if salt.utils.platform.is_windows(): return __virtualname__ return (False, "Only Windows supported") def add_store(name, store, saltenv="base"): """ Store a certificate to the given certificate store Args: name (str): The path to the certificate to add to the store. This is either the path to a local file or a file from the file server in the form of ``salt://path/to/file`` store (str): The certificate store to add the certificate to saltenv (str): The salt environment to use. This is ignored if the path is local Returns: dict: A dictionary containing the results CLI Example: .. code-block:: yaml add_certificate: certutil.add_store: name: salt://web_cert.cer store: TrustedPublisher """ ret = {"name": name, "result": True, "comment": "", "changes": {}} cert_file = __salt__["cp.cache_file"](name, saltenv) if cert_file is False: ret["comment"] = "Certificate file not found: {}".format(name) ret["result"] = False return ret cert_serial = __salt__["certutil.get_cert_serial"](name) if cert_serial is None: ret["comment"] = "Invalid certificate file: {}".format(name) ret["result"] = False return ret old_serials = __salt__["certutil.get_stored_cert_serials"](store=store) if cert_serial in old_serials: ret["comment"] = "Certificate already present: {}".format(name) return ret if __opts__["test"]: ret["comment"] = "Certificate will be added: {}".format(name) ret["result"] = None return ret retcode = __salt__["certutil.add_store"](name, store, retcode=True) if retcode != 0: ret["comment"] = "Error adding certificate: {}".format(name) ret["result"] = False return ret new_serials = __salt__["certutil.get_stored_cert_serials"](store=store) if cert_serial in new_serials: ret["changes"]["added"] = name ret["comment"] = "Added certificate: {}".format(name) else: ret["comment"] = "Failed to add certificate: {}".format(name) ret["result"] = False return ret def del_store(name, store, saltenv="base"): """ Remove a certificate from the given certificate store Args: name (str): The path to the certificate to remove from the store. This is either the path to a local file or a file from the file server in the form of ``salt://path/to/file`` store (str): The certificate store to remove the certificate from saltenv (str): The salt environment to use. This is ignored if the path is local Returns: dict: A dictionary containing the results CLI Example: .. code-block:: yaml remove_certificate: certutil.del_store: name: salt://web_cert.cer store: TrustedPublisher """ ret = {"name": name, "result": True, "comment": "", "changes": {}} cert_file = __salt__["cp.cache_file"](name, saltenv) if cert_file is False: ret["comment"] = "Certificate file not found: {}".format(name) ret["result"] = False return ret cert_serial = __salt__["certutil.get_cert_serial"](name) if cert_serial is None: ret["comment"] = "Invalid certificate file: {}".format(name) ret["result"] = False return ret old_serials = __salt__["certutil.get_stored_cert_serials"](store=store) if cert_serial not in old_serials: ret["comment"] = "Certificate already absent: {}".format(name) return ret if __opts__["test"]: ret["comment"] = "Certificate will be removed: {}".format(name) ret["result"] = None return ret retcode = __salt__["certutil.del_store"](name, store, retcode=True) if retcode != 0: ret["comment"] = "Error removing certificate: {}".format(name) ret["result"] = False return ret new_serials = __salt__["certutil.get_stored_cert_serials"](store=store) if cert_serial not in new_serials: ret["changes"]["removed"] = name ret["comment"] = "Removed certificate: {}".format(name) else: ret["comment"] = "Failed to remove certificate: {}".format(name) ret["result"] = False return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/states/win_certutil.py
0.763043
0.221319
win_certutil.py
pypi
import salt.utils.json def alias(name, collections, **kwargs): """ Create alias and enforce collection list. Use the solrcloud module to get alias members and set them. You can pass additional arguments that will be forwarded to http.query name The collection name collections list of collections to include in the alias """ ret = { "name": name, "changes": {}, "result": False, "comment": "", } if __salt__["solrcloud.alias_exists"](name, **kwargs): alias_content = __salt__["solrcloud.alias_get_collections"](name, **kwargs) diff = set(alias_content).difference(set(collections)) if len(diff) == 0: ret["result"] = True ret["comment"] = "Alias is in desired state" return ret if __opts__["test"]: ret["comment"] = 'The alias "{}" will be updated.'.format(name) ret["result"] = None else: __salt__["solrcloud.alias_set_collections"](name, collections, **kwargs) ret["comment"] = 'The alias "{}" has been updated.'.format(name) ret["result"] = True ret["changes"] = { "old": ",".join(alias_content), "new": ",".join(collections), } else: if __opts__["test"]: ret["comment"] = 'The alias "{}" will be created.'.format(name) ret["result"] = None else: __salt__["solrcloud.alias_set_collections"](name, collections, **kwargs) ret["comment"] = 'The alias "{}" has been created.'.format(name) ret["result"] = True ret["changes"] = { "old": None, "new": ",".join(collections), } return ret def collection(name, options=None, **kwargs): """ Create collection and enforce options. Use the solrcloud module to get collection parameters. You can pass additional arguments that will be forwarded to http.query name The collection name options : {} options to ensure """ ret = { "name": name, "changes": {}, "result": False, "comment": "", } if options is None: options = {} if __salt__["solrcloud.collection_exists"](name, **kwargs): diff = {} current_options = __salt__["solrcloud.collection_get_options"](name, **kwargs) # Filter options that can be updated updatable_options = [ "maxShardsPerNode", "replicationFactor", "autoAddReplicas", "collection.configName", "rule", "snitch", ] options = [k for k in options.items() if k in updatable_options] for key, value in options: if key not in current_options or current_options[key] != value: diff[key] = value if len(diff) == 0: ret["result"] = True ret["comment"] = "Collection options are in desired state" return ret else: if __opts__["test"]: ret["comment"] = 'Collection options "{}" will be changed.'.format(name) ret["result"] = None else: __salt__["solrcloud.collection_set_options"](name, diff, **kwargs) ret["comment"] = 'Parameters were updated for collection "{}".'.format( name ) ret["result"] = True ret["changes"] = { "old": salt.utils.json.dumps( current_options, sort_keys=True, indent=4, separators=(",", ": ") ), "new": salt.utils.json.dumps( options, sort_keys=True, indent=4, separators=(",", ": ") ), } return ret else: new_changes = salt.utils.json.dumps( options, sort_keys=True, indent=4, separators=(",", ": ") ) if __opts__["test"]: ret["comment"] = 'The collection "{}" will be created.'.format(name) ret["result"] = None else: __salt__["solrcloud.collection_create"](name, options, **kwargs) ret["comment"] = 'The collection "{}" has been created.'.format(name) ret["result"] = True ret["changes"] = { "old": None, "new": "options=" + new_changes, } return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/states/solrcloud.py
0.661595
0.288106
solrcloud.py
pypi
import logging log = logging.getLogger(__name__) def __virtual__(): """ Only load if cyg module is available in __salt__. """ if "cyg.list" in __salt__: return True return (False, "cyg module could not be loaded") def installed(name, cyg_arch="x86_64", mirrors=None): """ Make sure that a package is installed. name The name of the package to install cyg_arch : x86_64 The cygwin architecture to install the package into. Current options are x86 and x86_64 mirrors : None List of mirrors to check. None will use a default mirror (kernel.org) CLI Example: .. code-block:: yaml rsync: cyg.installed: - mirrors: - http://mirror/without/public/key: "" - http://mirror/with/public/key: http://url/of/public/key """ ret = {"name": name, "result": None, "comment": "", "changes": {}} if cyg_arch not in ["x86", "x86_64"]: ret["result"] = False ret["comment"] = "The 'cyg_arch' argument must be one of 'x86' or 'x86_64'" return ret log.debug("Installed State: Initial Mirror list: %s", mirrors) if not __salt__["cyg.check_valid_package"]( name, cyg_arch=cyg_arch, mirrors=mirrors ): ret["result"] = False ret["comment"] = "Invalid package name." return ret pkgs = __salt__["cyg.list"](name, cyg_arch) if name in pkgs: ret["result"] = True ret["comment"] = "Package is already installed." return ret if __opts__["test"]: ret["comment"] = "The package {} would have been installed".format(name) return ret if __salt__["cyg.install"](name, cyg_arch=cyg_arch, mirrors=mirrors): ret["result"] = True ret["changes"][name] = "Installed" ret["comment"] = "Package was successfully installed" else: ret["result"] = False ret["comment"] = "Could not install package." return ret def removed(name, cyg_arch="x86_64", mirrors=None): """ Make sure that a package is not installed. name The name of the package to uninstall cyg_arch : x86_64 The cygwin architecture to remove the package from. Current options are x86 and x86_64 mirrors : None List of mirrors to check. None will use a default mirror (kernel.org) CLI Example: .. code-block:: yaml rsync: cyg.removed: - mirrors: - http://mirror/without/public/key: "" - http://mirror/with/public/key: http://url/of/public/key """ ret = {"name": name, "result": None, "comment": "", "changes": {}} if cyg_arch not in ["x86", "x86_64"]: ret["result"] = False ret["comment"] = "The 'cyg_arch' argument must be one of 'x86' or 'x86_64'" return ret if not __salt__["cyg.check_valid_package"]( name, cyg_arch=cyg_arch, mirrors=mirrors ): ret["result"] = False ret["comment"] = "Invalid package name." return ret if name not in __salt__["cyg.list"](name, cyg_arch): ret["result"] = True ret["comment"] = "Package is not installed." return ret if __opts__["test"]: ret["comment"] = "The package {} would have been removed".format(name) return ret if __salt__["cyg.uninstall"](name, cyg_arch): ret["result"] = True ret["changes"][name] = "Removed" ret["comment"] = "Package was successfully removed." else: ret["result"] = False ret["comment"] = "Could not remove package." return ret def updated(name=None, cyg_arch="x86_64", mirrors=None): """ Make sure all packages are up to date. name : None No affect, salt fails poorly without the arg available cyg_arch : x86_64 The cygwin architecture to update. Current options are x86 and x86_64 mirrors : None List of mirrors to check. None will use a default mirror (kernel.org) CLI Example: .. code-block:: yaml rsync: cyg.updated: - mirrors: - http://mirror/without/public/key: "" - http://mirror/with/public/key: http://url/of/public/key """ ret = {"name": "cyg.updated", "result": None, "comment": "", "changes": {}} if cyg_arch not in ["x86", "x86_64"]: ret["result"] = False ret["comment"] = "The 'cyg_arch' argument must be one of 'x86' or 'x86_64'" return ret if __opts__["test"]: ret["comment"] = "All packages would have been updated" return ret if not mirrors: log.warning("No mirror given, using the default.") before = __salt__["cyg.list"](cyg_arch=cyg_arch) if __salt__["cyg.update"](cyg_arch, mirrors=mirrors): after = __salt__["cyg.list"](cyg_arch=cyg_arch) differ = DictDiffer(after, before) ret["result"] = True if differ.same(): ret["comment"] = "Nothing to update." else: ret["changes"]["added"] = list(differ.added()) ret["changes"]["removed"] = list(differ.removed()) ret["changes"]["changed"] = list(differ.changed()) ret["comment"] = "All packages successfully updated." else: ret["result"] = False ret["comment"] = "Could not update packages." return ret # https://github.com/hughdbrown/dictdiffer # DictDiffer is licensed as MIT code # A dictionary difference calculator # Originally posted as: # http://stackoverflow.com/a/1165552 class DictDiffer: """ Calculate the difference between two dictionaries. (1) items added (2) items removed (3) keys same in both but changed values (4) keys same in both and unchanged values """ def __init__(self, current_dict, past_dict): """ Iitialize the differ. """ self.current_dict, self.past_dict = current_dict, past_dict self.current_keys, self.past_keys = ( set(d.keys()) for d in (current_dict, past_dict) ) self.intersect = self.current_keys.intersection(self.past_keys) def same(self): """ True if the two dicts are the same. """ return self.current_dict == self.past_dict def added(self): """ Return a set of additions to past_dict. """ return self.current_keys - self.intersect def removed(self): """ Return a set of things removed from past_dict. """ return self.past_keys - self.intersect def changed(self): """ Return a set of the keys with changed values. """ return {o for o in self.intersect if self.past_dict[o] != self.current_dict[o]} def unchanged(self): """ Return a set of the keys with unchanged values. """ return {o for o in self.intersect if self.past_dict[o] == self.current_dict[o]}
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/states/cyg.py
0.75037
0.17266
cyg.py
pypi
def present(name=None, ipv4addr=None, data=None, ensure_data=True, **api_opts): """ Ensure infoblox A record. When you wish to update a hostname ensure `name` is set to the hostname of the current record. You can give a new name in the `data.name`. State example: .. code-block:: yaml infoblox_a.present: - name: example-ha-0.domain.com - data: name: example-ha-0.domain.com ipv4addr: 123.0.31.2 view: Internal """ ret = {"name": name, "result": False, "comment": "", "changes": {}} if not data: data = {} if "name" not in data: data.update({"name": name}) if "ipv4addr" not in data: data.update({"ipv4addr": ipv4addr}) obj = __salt__["infoblox.get_a"]( name=name, ipv4addr=ipv4addr, allow_array=False, **api_opts ) if obj is None: # perhaps the user updated the name obj = __salt__["infoblox.get_a"]( name=data["name"], ipv4addr=data["ipv4addr"], allow_array=False, **api_opts ) if obj: # warn user that the data was updated and does not match ret["result"] = False ret[ "comment" ] = "** please update the name: {} to equal the updated data name {}".format( name, data["name"] ) return ret if obj: obj = obj[0] if not ensure_data: ret["result"] = True ret[ "comment" ] = "infoblox record already created (supplied fields not ensured to match)" return ret diff = __salt__["infoblox.diff_objects"](data, obj) if not diff: ret["result"] = True ret["comment"] = ( "supplied fields already updated (note: removing fields might not" " update)" ) return ret if diff: ret["changes"] = {"diff": diff} if __opts__["test"]: ret["result"] = None ret["comment"] = "would attempt to update infoblox record" return ret ## TODO: perhaps need to review the output of new_obj new_obj = __salt__["infoblox.update_object"]( obj["_ref"], data=data, **api_opts ) ret["result"] = True ret["comment"] = ( "infoblox record fields updated (note: removing fields might not" " update)" ) return ret if __opts__["test"]: ret["result"] = None ret["comment"] = "would attempt to create infoblox record {}".format( data["name"] ) return ret new_obj_ref = __salt__["infoblox.create_a"](data=data, **api_opts) new_obj = __salt__["infoblox.get_a"]( name=name, ipv4addr=ipv4addr, allow_array=False, **api_opts ) ret["result"] = True ret["comment"] = "infoblox record created" ret["changes"] = {"old": "None", "new": {"_ref": new_obj_ref, "data": new_obj}} return ret def absent(name=None, ipv4addr=None, **api_opts): """ Ensure infoblox A record is removed. State example: .. code-block:: yaml infoblox_a.absent: - name: example-ha-0.domain.com infoblox_a.absent: - name: - ipv4addr: 127.0.23.23 """ ret = {"name": name, "result": False, "comment": "", "changes": {}} obj = __salt__["infoblox.get_a"]( name=name, ipv4addr=ipv4addr, allow_array=False, **api_opts ) if not obj: ret["result"] = True ret["comment"] = "infoblox already removed" return ret if __opts__["test"]: ret["result"] = None ret["changes"] = {"old": obj, "new": "absent"} return ret if __salt__["infoblox.delete_a"](name=name, ipv4addr=ipv4addr, **api_opts): ret["result"] = True ret["changes"] = {"old": obj, "new": "absent"} return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/states/infoblox_a.py
0.600774
0.343012
infoblox_a.py
pypi
import logging import salt.utils.dictdiffer log = logging.getLogger(__name__) def __virtual__(): """ Only work when the ACME module agrees """ if "acme.cert" in __salt__: return True return (False, "acme module could not be loaded") def cert( name, aliases=None, email=None, webroot=None, test_cert=False, renew=None, keysize=None, server=None, owner="root", group="root", mode="0640", certname=None, preferred_challenges=None, tls_sni_01_port=None, tls_sni_01_address=None, http_01_port=None, http_01_address=None, dns_plugin=None, dns_plugin_credentials=None, ): """ Obtain/renew a certificate from an ACME CA, probably Let's Encrypt. :param name: Common Name of the certificate (DNS name of certificate) :param aliases: subjectAltNames (Additional DNS names on certificate) :param email: e-mail address for interaction with ACME provider :param webroot: True or a full path to webroot. Otherwise use standalone mode :param test_cert: Request a certificate from the Happy Hacker Fake CA (mutually exclusive with 'server') :param renew: True/'force' to force a renewal, or a window of renewal before expiry in days :param keysize: RSA key bits :param server: API endpoint to talk to :param owner: owner of the private key file :param group: group of the private key file :param mode: mode of the private key file :param certname: Name of the certificate to save :param preferred_challenges: A sorted, comma delimited list of the preferred challenge to use during authorization with the most preferred challenge listed first. :param tls_sni_01_port: Port used during tls-sni-01 challenge. This only affects the port Certbot listens on. A conforming ACME server will still attempt to connect on port 443. :param tls_sni_01_address: The address the server listens to during tls-sni-01 challenge. :param http_01_port: Port used in the http-01 challenge. This only affects the port Certbot listens on. A conforming ACME server will still attempt to connect on port 80. :param https_01_address: The address the server listens to during http-01 challenge. :param dns_plugin: Name of a DNS plugin to use (currently only 'cloudflare') :param dns_plugin_credentials: Path to the credentials file if required by the specified DNS plugin """ if certname is None: certname = name ret = {"name": certname, "result": "changeme", "comment": [], "changes": {}} action = None current_certificate = {} new_certificate = {} if not __salt__["acme.has"](certname): action = "obtain" elif __salt__["acme.needs_renewal"](certname, renew): action = "renew" current_certificate = __salt__["acme.info"](certname) else: ret["result"] = True ret["comment"].append( "Certificate {} exists and does not need renewal.".format(certname) ) if action: if __opts__["test"]: ret["result"] = None ret["comment"].append( "Certificate {} would have been {}ed.".format(certname, action) ) ret["changes"] = {"old": "current certificate", "new": "new certificate"} else: res = __salt__["acme.cert"]( name, aliases=aliases, email=email, webroot=webroot, certname=certname, test_cert=test_cert, renew=renew, keysize=keysize, server=server, owner=owner, group=group, mode=mode, preferred_challenges=preferred_challenges, tls_sni_01_port=tls_sni_01_port, tls_sni_01_address=tls_sni_01_address, http_01_port=http_01_port, http_01_address=http_01_address, dns_plugin=dns_plugin, dns_plugin_credentials=dns_plugin_credentials, ) ret["result"] = res["result"] ret["comment"].append(res["comment"]) if ret["result"]: new_certificate = __salt__["acme.info"](certname) ret["changes"] = salt.utils.dictdiffer.deep_diff( current_certificate, new_certificate ) return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/states/acme.py
0.619126
0.173009
acme.py
pypi
__virtualname__ = "zookeeper" def __virtual__(): if "zookeeper.create" in __salt__: return __virtualname__ return (False, "zookeeper module could not be loaded") def _check_acls(left, right): first = not bool(set(left) - set(right)) second = not bool(set(right) - set(left)) return first and second def present( name, value, acls=None, ephemeral=False, sequence=False, makepath=False, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None, ): """ Make sure znode is present in the correct state with the correct acls name path to znode value value znode should be set to acls list of acl dictionaries to set on znode (make sure the ones salt is connected with are included) Default: None ephemeral Boolean to indicate if ephemeral znode should be created Default: False sequence Boolean to indicate if znode path is suffixed with a unique index Default: False makepath Boolean to indicate if the parent paths should be created Default: False version For updating, specify the version which should be updated Default: -1 (always match) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) .. code-block:: yaml add znode: zookeeper.present: - name: /test/name - value: gtmanfred - makepath: True update znode: zookeeper.present: - name: /test/name - value: daniel - acls: - username: daniel password: test read: true - username: gtmanfred password: test read: true write: true create: true delete: true admin: true - makepath: True """ ret = { "name": name, "result": False, "comment": "Failed to setup znode {}".format(name), "changes": {}, } connkwargs = { "profile": profile, "hosts": hosts, "scheme": scheme, "username": username, "password": password, "default_acl": default_acl, } if acls is None: chk_acls = [] else: chk_acls = [__salt__["zookeeper.make_digest_acl"](**acl) for acl in acls] if __salt__["zookeeper.exists"](name, **connkwargs): cur_value = __salt__["zookeeper.get"](name, **connkwargs) cur_acls = __salt__["zookeeper.get_acls"](name, **connkwargs) if cur_value == value and _check_acls(cur_acls, chk_acls): ret["result"] = True ret[ "comment" ] = "Znode {} is already set to the correct value with the correct acls".format( name ) return ret elif __opts__["test"] is True: ret["result"] = None ret["comment"] = "Znode {} is will be updated".format(name) ret["changes"]["old"] = {} ret["changes"]["new"] = {} if value != cur_value: ret["changes"]["old"]["value"] = cur_value ret["changes"]["new"]["value"] = value if not _check_acls(chk_acls, cur_acls): ret["changes"]["old"]["acls"] = cur_acls ret["changes"]["new"]["acls"] = chk_acls return ret else: value_result, acl_result = True, True changes = {} if value != cur_value: __salt__["zookeeper.set"](name, value, version, **connkwargs) new_value = __salt__["zookeeper.get"](name, **connkwargs) value_result = new_value == value changes.setdefault("new", {}).setdefault("value", new_value) changes.setdefault("old", {}).setdefault("value", cur_value) if chk_acls and not _check_acls(chk_acls, cur_acls): __salt__["zookeeper.set_acls"](name, acls, version, **connkwargs) new_acls = __salt__["zookeeper.get_acls"](name, **connkwargs) acl_result = _check_acls(new_acls, chk_acls) changes.setdefault("new", {}).setdefault("acls", new_acls) changes.setdefault("old", {}).setdefault("value", cur_acls) ret["changes"] = changes if value_result and acl_result: ret["result"] = True ret["comment"] = "Znode {} successfully updated".format(name) return ret if __opts__["test"] is True: ret["result"] = None ret["comment"] = "{} is will be created".format(name) ret["changes"]["old"] = {} ret["changes"]["new"] = {} ret["changes"]["new"]["acls"] = chk_acls ret["changes"]["new"]["value"] = value return ret __salt__["zookeeper.create"]( name, value, acls, ephemeral, sequence, makepath, **connkwargs ) value_result, acl_result = True, True changes = {"old": {}} new_value = __salt__["zookeeper.get"](name, **connkwargs) value_result = new_value == value changes.setdefault("new", {}).setdefault("value", new_value) new_acls = __salt__["zookeeper.get_acls"](name, **connkwargs) acl_result = acls is None or _check_acls(new_acls, chk_acls) changes.setdefault("new", {}).setdefault("acls", new_acls) ret["changes"] = changes if value_result and acl_result: ret["result"] = True ret["comment"] = "Znode {} successfully created".format(name) return ret def absent( name, version=-1, recursive=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None, ): """ Make sure znode is absent name path to znode version Specify the version which should be deleted Default: -1 (always match) recursive Boolean to indicate if children should be recursively deleted Default: False profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) .. code-block:: yaml delete znode: zookeeper.absent: - name: /test - recursive: True """ ret = { "name": name, "result": False, "comment": "Failed to delete znode {}".format(name), "changes": {}, } connkwargs = { "profile": profile, "hosts": hosts, "scheme": scheme, "username": username, "password": password, "default_acl": default_acl, } if __salt__["zookeeper.exists"](name, **connkwargs) is False: ret["result"] = True ret["comment"] = "Znode {} does not exist".format(name) return ret changes = {} changes["value"] = __salt__["zookeeper.get"](name, **connkwargs) changes["acls"] = __salt__["zookeeper.get_acls"](name, **connkwargs) if recursive is True: changes["children"] = __salt__["zookeeper.get_children"](name, **connkwargs) if __opts__["test"] is True: ret["result"] = None ret["comment"] = "Znode {} will be removed".format(name) ret["changes"]["old"] = changes return ret __salt__["zookeeper.delete"](name, version, recursive, **connkwargs) if __salt__["zookeeper.exists"](name, **connkwargs) is False: ret["result"] = True ret["comment"] = "Znode {} has been removed".format(name) ret["changes"]["old"] = changes return ret def acls( name, acls, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None, ): """ Update acls on a znode name path to znode acls list of acl dictionaries to set on znode version Specify the version which should be deleted Default: -1 (always match) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) .. code-block:: yaml update acls: zookeeper.acls: - name: /test/name - acls: - username: daniel password: test all: True - username: gtmanfred password: test all: True """ ret = { "name": name, "result": False, "comment": "Failed to set acls on znode {}".format(name), "changes": {}, } connkwargs = { "profile": profile, "hosts": hosts, "scheme": scheme, "username": username, "password": password, "default_acl": default_acl, } if isinstance(acls, dict): acls = [acls] chk_acls = [__salt__["zookeeper.make_digest_acl"](**acl) for acl in acls] if not __salt__["zookeeper.exists"](name, **connkwargs): ret["comment"] += ": Znode does not exist" return ret cur_acls = __salt__["zookeeper.get_acls"](name, **connkwargs) if _check_acls(cur_acls, chk_acls): ret["result"] = True ret["comment"] = "Znode {} acls already set".format(name) return ret if __opts__["test"] is True: ret["result"] = None ret["comment"] = "Znode {} acls will be updated".format(name) ret["changes"]["old"] = cur_acls ret["changes"]["new"] = chk_acls return ret __salt__["zookeeper.set_acls"](name, acls, version, **connkwargs) new_acls = __salt__["zookeeper.get_acls"](name, **connkwargs) ret["changes"] = {"old": cur_acls, "new": new_acls} if _check_acls(new_acls, chk_acls): ret["result"] = True ret["comment"] = "Znode {} acls updated".format(name) return ret ret["comment"] = "Znode {} acls failed to update".format(name) return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/states/zookeeper.py
0.688887
0.256681
zookeeper.py
pypi
import os.path import salt.utils.files import salt.utils.stringutils from salt.utils.icinga2 import get_certs_path def __virtual__(): """ Only load if the icinga2 module is available in __salt__ """ if "icinga2.generate_ticket" in __salt__: return True return (False, "icinga2 module could not be loaded") def generate_ticket(name, output=None, grain=None, key=None, overwrite=True): """ Generate an icinga2 ticket on the master. name The domain name for which this ticket will be generated output grain: output in a grain other: the file to store results None: output to the result comment (default) grain: grain to store the output (need output=grain) key: the specified grain will be treated as a dictionary, the result of this state will be stored under the specified key. overwrite: The file or grain will be overwritten if it already exists (default) """ ret = {"name": name, "changes": {}, "result": True, "comment": ""} # Checking if execution is needed. if output == "grain": if grain and not key: if not overwrite and grain in __salt__["grains.ls"](): ret["comment"] = "No execution needed. Grain {} already set".format( grain ) return ret elif __opts__["test"]: ret["result"] = None ret[ "comment" ] = "Ticket generation would be executed, storing result in grain: {}".format( grain ) return ret elif grain: if grain in __salt__["grains.ls"](): grain_value = __salt__["grains.get"](grain) else: grain_value = {} if not overwrite and key in grain_value: ret["comment"] = "No execution needed. Grain {}:{} already set".format( grain, key ) return ret elif __opts__["test"]: ret["result"] = None ret["comment"] = ( "Ticket generation would be executed, storing result in grain:" " {}:{}".format(grain, key) ) return ret else: ret["result"] = False ret["comment"] = "Error: output type 'grain' needs the grain parameter\n" return ret elif output: if not overwrite and os.path.isfile(output): ret["comment"] = "No execution needed. File {} already set".format(output) return ret elif __opts__["test"]: ret["result"] = None ret[ "comment" ] = "Ticket generation would be executed, storing result in file: {}".format( output ) return ret elif __opts__["test"]: ret["result"] = None ret["comment"] = "Ticket generation would be executed, not storing result" return ret # Executing the command. ticket_res = __salt__["icinga2.generate_ticket"](name) ticket = ticket_res["stdout"] if not ticket_res["retcode"]: ret["comment"] = str(ticket) if output == "grain": if grain and not key: __salt__["grains.setval"](grain, ticket) ret["changes"]["ticket"] = "Executed. Output into grain: {}".format(grain) elif grain: if grain in __salt__["grains.ls"](): grain_value = __salt__["grains.get"](grain) else: grain_value = {} grain_value[key] = ticket __salt__["grains.setval"](grain, grain_value) ret["changes"]["ticket"] = "Executed. Output into grain: {}:{}".format( grain, key ) elif output: ret["changes"]["ticket"] = "Executed. Output into {}".format(output) with salt.utils.files.fopen(output, "w") as output_file: output_file.write(salt.utils.stringutils.to_str(ticket)) else: ret["changes"]["ticket"] = "Executed" return ret def generate_cert(name): """ Generate an icinga2 certificate and key on the client. name The domain name for which this certificate and key will be generated """ ret = {"name": name, "changes": {}, "result": True, "comment": ""} cert = "{}{}.crt".format(get_certs_path(), name) key = "{}{}.key".format(get_certs_path(), name) # Checking if execution is needed. if os.path.isfile(cert) and os.path.isfile(key): ret[ "comment" ] = "No execution needed. Cert: {} and key: {} already generated.".format( cert, key ) return ret if __opts__["test"]: ret["result"] = None ret["comment"] = "Certificate and key generation would be executed" return ret # Executing the command. cert_save = __salt__["icinga2.generate_cert"](name) if not cert_save["retcode"]: ret["comment"] = "Certificate and key generated" ret["changes"]["cert"] = "Executed. Certificate saved: {}".format(cert) ret["changes"]["key"] = "Executed. Key saved: {}".format(key) return ret def save_cert(name, master): """ Save the certificate on master icinga2 node. name The domain name for which this certificate will be saved master Icinga2 master node for which this certificate will be saved """ ret = {"name": name, "changes": {}, "result": True, "comment": ""} cert = "{}trusted-master.crt".format(get_certs_path()) # Checking if execution is needed. if os.path.isfile(cert): ret["comment"] = "No execution needed. Cert: {} already saved.".format(cert) return ret if __opts__["test"]: ret["result"] = None ret["comment"] = "Certificate save for icinga2 master would be executed" return ret # Executing the command. cert_save = __salt__["icinga2.save_cert"](name, master) if not cert_save["retcode"]: ret["comment"] = "Certificate for icinga2 master saved" ret["changes"]["cert"] = "Executed. Certificate saved: {}".format(cert) return ret def request_cert(name, master, ticket, port="5665"): """ Request CA certificate from master icinga2 node. name The domain name for which this certificate will be saved master Icinga2 master node for which this certificate will be saved ticket Authentication ticket generated on icinga2 master port Icinga2 port, defaults to 5665 """ ret = {"name": name, "changes": {}, "result": True, "comment": ""} cert = "{}ca.crt".format(get_certs_path()) # Checking if execution is needed. if os.path.isfile(cert): ret["comment"] = "No execution needed. Cert: {} already exists.".format(cert) return ret if __opts__["test"]: ret["result"] = None ret["comment"] = "Certificate request from icinga2 master would be executed" return ret # Executing the command. cert_request = __salt__["icinga2.request_cert"](name, master, ticket, port) if not cert_request["retcode"]: ret["comment"] = "Certificate request from icinga2 master executed" ret["changes"]["cert"] = "Executed. Certificate requested: {}".format(cert) return ret ret["comment"] = "FAILED. Certificate requested failed with output: {}".format( cert_request["stdout"] ) ret["result"] = False return ret def node_setup(name, master, ticket): """ Setup the icinga2 node. name The domain name for which this certificate will be saved master Icinga2 master node for which this certificate will be saved ticket Authentication ticket generated on icinga2 master """ ret = {"name": name, "changes": {}, "result": True, "comment": ""} cert = "{}{}.crt.orig".format(get_certs_path(), name) key = "{}{}.key.orig".format(get_certs_path(), name) # Checking if execution is needed. if os.path.isfile(cert) and os.path.isfile(cert): ret["comment"] = "No execution needed. Node already configured." return ret if __opts__["test"]: ret["result"] = None ret["comment"] = "Node setup will be executed." return ret # Executing the command. node_setup = __salt__["icinga2.node_setup"](name, master, ticket) if not node_setup["retcode"]: ret["comment"] = "Node setup executed." ret["changes"]["cert"] = "Node setup finished successfully." return ret ret["comment"] = "FAILED. Node setup failed with outpu: {}".format( node_setup["stdout"] ) ret["result"] = False return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/states/icinga2.py
0.4917
0.229255
icinga2.py
pypi
from salt.exceptions import CommandExecutionError, SaltInvocationError def __virtual__(): """ Load if the module firewall is loaded """ if "firewall.get_config" in __salt__: return "win_firewall" return (False, "firewall module could not be loaded") def disabled(name="allprofiles"): """ Disable all the firewall profiles (Windows only) Args: profile (Optional[str]): The name of the profile to disable. Default is ``allprofiles``. Valid options are: - allprofiles - domainprofile - privateprofile - publicprofile Example: .. code-block:: yaml # To disable the domain profile disable_domain: win_firewall.disabled: - name: domainprofile # To disable all profiles disable_all: win_firewall.disabled: - name: allprofiles """ ret = {"name": name, "result": True, "changes": {}, "comment": ""} profile_map = { "domainprofile": "Domain", "privateprofile": "Private", "publicprofile": "Public", "allprofiles": "All", } # Make sure the profile name is valid if name not in profile_map: raise SaltInvocationError("Invalid profile name: {}".format(name)) current_config = __salt__["firewall.get_config"]() if name != "allprofiles" and profile_map[name] not in current_config: ret["result"] = False ret["comment"] = "Profile {} does not exist in firewall.get_config".format(name) return ret for key in current_config: if current_config[key]: if name == "allprofiles" or key == profile_map[name]: ret["changes"][key] = "disabled" if __opts__["test"]: ret["result"] = not ret["changes"] or None ret["comment"] = ret["changes"] ret["changes"] = {} return ret # Disable it if ret["changes"]: try: ret["result"] = __salt__["firewall.disable"](name) except CommandExecutionError: ret["comment"] = "Firewall Profile {} could not be disabled".format( profile_map[name] ) else: if name == "allprofiles": msg = "All the firewall profiles are disabled" else: msg = "Firewall profile {} is disabled".format(name) ret["comment"] = msg return ret def add_rule(name, localport, protocol="tcp", action="allow", dir="in", remoteip="any"): """ Add a new inbound or outbound rule to the firewall policy Args: name (str): The name of the rule. Must be unique and cannot be "all". Required. localport (int): The port the rule applies to. Must be a number between 0 and 65535. Can be a range. Can specify multiple ports separated by commas. Required. protocol (Optional[str]): The protocol. Can be any of the following: - A number between 0 and 255 - icmpv4 - icmpv6 - tcp - udp - any action (Optional[str]): The action the rule performs. Can be any of the following: - allow - block - bypass dir (Optional[str]): The direction. Can be ``in`` or ``out``. remoteip (Optional [str]): The remote IP. Can be any of the following: - any - localsubnet - dns - dhcp - wins - defaultgateway - Any valid IPv4 address (192.168.0.12) - Any valid IPv6 address (2002:9b3b:1a31:4:208:74ff:fe39:6c43) - Any valid subnet (192.168.1.0/24) - Any valid range of IP addresses (192.168.0.1-192.168.0.12) - A list of valid IP addresses Can be combinations of the above separated by commas. .. versionadded:: 2016.11.6 Example: .. code-block:: yaml open_smb_port: win_firewall.add_rule: - name: SMB (445) - localport: 445 - protocol: tcp - action: allow """ ret = {"name": name, "result": True, "changes": {}, "comment": ""} # Check if rule exists if not __salt__["firewall.rule_exists"](name): ret["changes"] = {"new rule": name} else: ret["comment"] = "A rule with that name already exists" return ret if __opts__["test"]: ret["result"] = not ret["changes"] or None ret["comment"] = ret["changes"] ret["changes"] = {} return ret # Add rule try: __salt__["firewall.add_rule"](name, localport, protocol, action, dir, remoteip) except CommandExecutionError: ret["comment"] = "Could not add rule" return ret def enabled(name="allprofiles"): """ Enable all the firewall profiles (Windows only) Args: profile (Optional[str]): The name of the profile to enable. Default is ``allprofiles``. Valid options are: - allprofiles - domainprofile - privateprofile - publicprofile Example: .. code-block:: yaml # To enable the domain profile enable_domain: win_firewall.enabled: - name: domainprofile # To enable all profiles enable_all: win_firewall.enabled: - name: allprofiles """ ret = {"name": name, "result": True, "changes": {}, "comment": ""} profile_map = { "domainprofile": "Domain", "privateprofile": "Private", "publicprofile": "Public", "allprofiles": "All", } # Make sure the profile name is valid if name not in profile_map: raise SaltInvocationError("Invalid profile name: {}".format(name)) current_config = __salt__["firewall.get_config"]() if name != "allprofiles" and profile_map[name] not in current_config: ret["result"] = False ret["comment"] = "Profile {} does not exist in firewall.get_config".format(name) return ret for key in current_config: if not current_config[key]: if name == "allprofiles" or key == profile_map[name]: ret["changes"][key] = "enabled" if __opts__["test"]: ret["result"] = not ret["changes"] or None ret["comment"] = ret["changes"] ret["changes"] = {} return ret # Enable it if ret["changes"]: try: ret["result"] = __salt__["firewall.enable"](name) except CommandExecutionError: ret["comment"] = "Firewall Profile {} could not be enabled".format( profile_map[name] ) else: if name == "allprofiles": msg = "All the firewall profiles are enabled" else: msg = "Firewall profile {} is enabled".format(name) ret["comment"] = msg return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/states/win_firewall.py
0.822332
0.165559
win_firewall.py
pypi
import salt.utils.data def __virtual__(): """ Only load if boto is available. """ if "boto_cloudwatch.get_alarm" in __salt__: return "boto_cloudwatch_alarm" return (False, "boto_cloudwatch module could not be loaded") def present(name, attributes, region=None, key=None, keyid=None, profile=None): """ Ensure the cloudwatch alarm exists. name Name of the alarm attributes A dict of key/value cloudwatch alarm attributes. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. """ ret = {"name": name, "result": True, "comment": "", "changes": {}} alarm_details = __salt__["boto_cloudwatch.get_alarm"]( name, region, key, keyid, profile ) # Convert to arn's for k in ["alarm_actions", "insufficient_data_actions", "ok_actions"]: if k in attributes: attributes[k] = __salt__["boto_cloudwatch.convert_to_arn"]( attributes[k], region, key, keyid, profile ) # Diff the alarm_details with the passed-in attributes, allowing for the # AWS type transformations difference = [] if alarm_details: for k, v in attributes.items(): if k not in alarm_details: difference.append("{}={} (new)".format(k, v)) continue v = salt.utils.data.decode(v) v2 = salt.utils.data.decode(alarm_details[k]) if v == v2: continue if isinstance(v, str) and v == v2: continue if isinstance(v, float) and v == float(v2): continue if isinstance(v, int) and v == int(v2): continue if isinstance(v, list) and sorted(v) == sorted(v2): continue difference.append("{}='{}' was: '{}'".format(k, v, v2)) else: difference.append("new alarm") create_or_update_alarm_args = { "name": name, "region": region, "key": key, "keyid": keyid, "profile": profile, } create_or_update_alarm_args.update(attributes) if alarm_details: # alarm is present. update, or do nothing # check to see if attributes matches is_present. If so, do nothing. if len(difference) == 0: ret["comment"] = "alarm {} present and matching".format(name) return ret if __opts__["test"]: msg = "alarm {} is to be created/updated.".format(name) ret["comment"] = msg ret["result"] = None return ret result = __salt__["boto_cloudwatch.create_or_update_alarm"]( **create_or_update_alarm_args ) if result: ret["changes"]["diff"] = difference else: ret["result"] = False ret["comment"] = "Failed to create {} alarm".format(name) else: # alarm is absent. create it. if __opts__["test"]: msg = "alarm {} is to be created/updated.".format(name) ret["comment"] = msg ret["result"] = None return ret result = __salt__["boto_cloudwatch.create_or_update_alarm"]( **create_or_update_alarm_args ) if result: ret["changes"]["new"] = attributes else: ret["result"] = False ret["comment"] = "Failed to create {} alarm".format(name) return ret def absent(name, region=None, key=None, keyid=None, profile=None): """ Ensure the named cloudwatch alarm is deleted. name Name of the alarm. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. """ ret = {"name": name, "result": True, "comment": "", "changes": {}} is_present = __salt__["boto_cloudwatch.get_alarm"]( name, region, key, keyid, profile ) if is_present: if __opts__["test"]: ret["comment"] = "alarm {} is set to be removed.".format(name) ret["result"] = None return ret deleted = __salt__["boto_cloudwatch.delete_alarm"]( name, region, key, keyid, profile ) if deleted: ret["changes"]["old"] = name ret["changes"]["new"] = None else: ret["result"] = False ret["comment"] = "Failed to delete {} alarm.".format(name) else: ret["comment"] = "{} does not exist in {}.".format(name, region) return ret
/salt-ssh-9000.tar.gz/salt-ssh-9000/salt/states/boto_cloudwatch_alarm.py
0.537284
0.184694
boto_cloudwatch_alarm.py
pypi