repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
saltstack/salt
salt/modules/cassandra_cql.py
list_users
python
def list_users(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List existing users in this Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param port: The Cassandra cluster port, defaults to None. :type port: int :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :return: The list of existing users. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_users salt 'minion1' cassandra_cql.list_users contact_points=minion1 ''' query = "list users;" ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list users.') raise except BaseException as e: log.critical('Unexpected error while listing users: %s', e) raise return ret
List existing users in this Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param port: The Cassandra cluster port, defaults to None. :type port: int :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :return: The list of existing users. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_users salt 'minion1' cassandra_cql.list_users contact_points=minion1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cassandra_cql.py#L797-L833
[ "def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None):\n '''\n Run a query on a Cassandra cluster and return a dictionary.\n\n :param query: The query to execute.\n :type query: str\n :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs.\n :type contact_points: str | list[str]\n :param cql_user: The Cassandra user if authentication is turned on.\n :type cql_user: str\n :param cql_pass: The Cassandra user password if authentication is turned on.\n :type cql_pass: str\n :param port: The Cassandra cluster port, defaults to None.\n :type port: int\n :param params: The parameters for the query, optional.\n :type params: str\n :return: A dictionary from the return values of the query\n :rtype: list[dict]\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'cassandra-server' cassandra_cql.cql_query \"SELECT * FROM users_by_name WHERE first_name = 'jane'\"\n '''\n try:\n cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass)\n except CommandExecutionError:\n log.critical('Could not get Cassandra cluster session.')\n raise\n except BaseException as e:\n log.critical('Unexpected error while getting Cassandra cluster session: %s', e)\n raise\n\n session.row_factory = dict_factory\n ret = []\n\n # Cassandra changed their internal schema from v2 to v3\n # If the query contains a dictionary sorted by versions\n # Find the query for the current cluster version.\n # https://issues.apache.org/jira/browse/CASSANDRA-6717\n if isinstance(query, dict):\n cluster_version = version(contact_points=contact_points,\n port=port,\n cql_user=cql_user,\n cql_pass=cql_pass)\n match = re.match(r'^(\\d+)\\.(\\d+)(?:\\.(\\d+))?', cluster_version)\n major, minor, point = match.groups()\n # try to find the specific version in the query dictionary\n # then try the major version\n # otherwise default to the highest version number\n try:\n query = query[cluster_version]\n except KeyError:\n query = query.get(major, max(query))\n log.debug('New query is: %s', query)\n\n try:\n results = session.execute(query)\n except BaseException as e:\n log.error('Failed to execute query: %s\\n reason: %s', query, e)\n msg = \"ERROR: Cassandra query failed: {0} reason: {1}\".format(query, e)\n raise CommandExecutionError(msg)\n\n if results:\n for result in results:\n values = {}\n for key, value in six.iteritems(result):\n # Salt won't return dictionaries with odd types like uuid.UUID\n if not isinstance(value, six.text_type):\n # Must support Cassandra collection types.\n # Namely, Cassandras set, list, and map collections.\n if not isinstance(value, (set, list, dict)):\n value = six.text_type(value)\n values[key] = value\n ret.append(values)\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Cassandra Database Module .. versionadded:: 2015.5.0 This module works with Cassandra v2 and v3 and hence generates queries based on the internal schema of said version. :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :referenced by: Salt's cassandra_cql returner :configuration: The Cassandra cluster members and connection port can either be specified in the master or minion config, the minion's pillar or be passed to the module. Example configuration in the config for a single node: .. code-block:: yaml cassandra: cluster: 192.168.50.10 port: 9000 Example configuration in the config for a cluster: .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin .. versionchanged:: 2016.11.0 Added support for ``ssl_options`` and ``protocol_version``. Example configuration with `ssl options <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_: If ``ssl_options`` are present in cassandra config the cassandra_cql returner will use SSL. SSL isn't used if ``ssl_options`` isn't specified. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin ssl_options: ca_certs: /etc/ssl/certs/ca-bundle.trust.crt # SSL version should be one from the ssl module # This is an optional parameter ssl_version: PROTOCOL_TLSv1 Additionally you can also specify the ``protocol_version`` to `use <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin # defaults to 4, if not set protocol_version: 3 ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import logging import re import ssl # Import Salt Libs import salt.utils.json from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.versions SSL_VERSION = 'ssl_version' log = logging.getLogger(__name__) __virtualname__ = 'cassandra_cql' HAS_DRIVER = False try: # pylint: disable=import-error,no-name-in-module from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, \ ConnectionShutdown, OperationTimedOut from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=import-error,no-name-in-module HAS_DRIVER = True except ImportError: pass def __virtual__(): ''' Return virtual name of the module only if the python driver can be loaded. :return: The virtual name of the module. :rtype: str ''' if HAS_DRIVER: return __virtualname__ return (False, 'Cannot load cassandra_cql module: python driver not found') def _async_log_errors(errors): log.error('Cassandra_cql asynchronous call returned: %s', errors) def _load_properties(property_name, config_option, set_default=False, default=None): ''' Load properties for the cassandra module from config or pillar. :param property_name: The property to load. :type property_name: str or list of str :param config_option: The name of the config option. :type config_option: str :param set_default: Should a default be set if not found in config. :type set_default: bool :param default: The default value to be set. :type default: str or int :return: The property fetched from the configuration or default. :rtype: str or list of str ''' if not property_name: log.debug("No property specified in function, trying to load from salt configuration") try: options = __salt__['config.option']('cassandra') except BaseException as e: log.error("Failed to get cassandra config options. Reason: %s", e) raise loaded_property = options.get(config_option) if not loaded_property: if set_default: log.debug('Setting default Cassandra %s to %s', config_option, default) loaded_property = default else: log.error('No cassandra %s specified in the configuration or passed to the module.', config_option) raise CommandExecutionError("ERROR: Cassandra {0} cannot be empty.".format(config_option)) return loaded_property return property_name def _get_ssl_opts(): ''' Parse out ssl_options for Cassandra cluster connection. Make sure that the ssl_version (if any specified) is valid. ''' sslopts = __salt__['config.option']('cassandra').get('ssl_options', None) ssl_opts = {} if sslopts: ssl_opts['ca_certs'] = sslopts['ca_certs'] if SSL_VERSION in sslopts: if not sslopts[SSL_VERSION].startswith('PROTOCOL_'): valid_opts = ', '.join( [x for x in dir(ssl) if x.startswith('PROTOCOL_')] ) raise CommandExecutionError('Invalid protocol_version ' 'specified! ' 'Please make sure ' 'that the ssl protocol' 'version is one from the SSL' 'module. ' 'Valid options are ' '{0}'.format(valid_opts)) else: ssl_opts[SSL_VERSION] = \ getattr(ssl, sslopts[SSL_VERSION]) return ssl_opts else: return None def _connect(contact_points=None, port=None, cql_user=None, cql_pass=None, protocol_version=None): ''' Connect to a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str or list of str :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param protocol_version: Cassandra protocol version to use. :type port: int :return: The session and cluster objects. :rtype: cluster object, session object ''' # Lazy load the Cassandra cluster and session for this module by creating a # cluster and session when cql_query is called the first time. Get the # Cassandra cluster and session from this module's __context__ after it is # loaded the first time cql_query is called. # # TODO: Call cluster.shutdown() when the module is unloaded on # master/minion shutdown. Currently, Master.shutdown() and Minion.shutdown() # do nothing to allow loaded modules to gracefully handle resources stored # in __context__ (i.e. connection pools). This means that the connection # pool is orphaned and Salt relies on Cassandra to reclaim connections. # Perhaps if Master/Minion daemons could be enhanced to call an "__unload__" # function, or something similar for each loaded module, connection pools # and the like can be gracefully reclaimed/shutdown. if (__context__ and 'cassandra_cql_returner_cluster' in __context__ and 'cassandra_cql_returner_session' in __context__): return __context__['cassandra_cql_returner_cluster'], __context__['cassandra_cql_returner_session'] else: contact_points = _load_properties(property_name=contact_points, config_option='cluster') contact_points = contact_points if isinstance(contact_points, list) else contact_points.split(',') port = _load_properties(property_name=port, config_option='port', set_default=True, default=9042) cql_user = _load_properties(property_name=cql_user, config_option='username', set_default=True, default="cassandra") cql_pass = _load_properties(property_name=cql_pass, config_option='password', set_default=True, default="cassandra") protocol_version = _load_properties(property_name=protocol_version, config_option='protocol_version', set_default=True, default=4) try: auth_provider = PlainTextAuthProvider(username=cql_user, password=cql_pass) ssl_opts = _get_ssl_opts() if ssl_opts: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, ssl_options=ssl_opts, protocol_version=protocol_version, compression=True) else: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, protocol_version=protocol_version, compression=True) for recontimes in range(1, 4): try: session = cluster.connect() break except OperationTimedOut: log.warning('Cassandra cluster.connect timed out, try %s', recontimes) if recontimes >= 3: raise # TODO: Call cluster.shutdown() when the module is unloaded on shutdown. __context__['cassandra_cql_returner_cluster'] = cluster __context__['cassandra_cql_returner_session'] = session __context__['cassandra_cql_prepared'] = {} log.debug('Successfully connected to Cassandra cluster at %s', contact_points) return cluster, session except TypeError: pass except (ConnectionException, ConnectionShutdown, NoHostAvailable): log.error('Could not connect to Cassandra cluster at %s', contact_points) raise CommandExecutionError('ERROR: Could not connect to Cassandra cluster.') def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Run a query on a Cassandra cluster and return a dictionary. :param query: The query to execute. :type query: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash salt 'cassandra-server' cassandra_cql.cql_query "SELECT * FROM users_by_name WHERE first_name = 'jane'" ''' try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise session.row_factory = dict_factory ret = [] # Cassandra changed their internal schema from v2 to v3 # If the query contains a dictionary sorted by versions # Find the query for the current cluster version. # https://issues.apache.org/jira/browse/CASSANDRA-6717 if isinstance(query, dict): cluster_version = version(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) match = re.match(r'^(\d+)\.(\d+)(?:\.(\d+))?', cluster_version) major, minor, point = match.groups() # try to find the specific version in the query dictionary # then try the major version # otherwise default to the highest version number try: query = query[cluster_version] except KeyError: query = query.get(major, max(query)) log.debug('New query is: %s', query) try: results = session.execute(query) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) return ret def cql_query_with_prepare(query, statement_name, statement_arguments, callback_errors=None, contact_points=None, port=None, cql_user=None, cql_pass=None, **kwargs): ''' Run a query on a Cassandra cluster and return a dictionary. This function should not be used asynchronously for SELECTs -- it will not return anything and we don't currently have a mechanism for handling a future that will return results. :param query: The query to execute. :type query: str :param statement_name: Name to assign the prepared statement in the __context__ dictionary :type statement_name: str :param statement_arguments: Bind parameters for the SQL statement :type statement_arguments: list[str] :param async: Run this query in asynchronous mode :type async: bool :param callback_errors: Function to call after query runs if there is an error :type callback_errors: Function callable :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash # Insert data asynchronously salt this-node cassandra_cql.cql_query_with_prepare "name_insert" "INSERT INTO USERS (first_name, last_name) VALUES (?, ?)" \ statement_arguments=['John','Doe'], asynchronous=True # Select data, should not be asynchronous because there is not currently a facility to return data from a future salt this-node cassandra_cql.cql_query_with_prepare "name_select" "SELECT * FROM USERS WHERE first_name=?" \ statement_arguments=['John'] ''' # Backward-compatibility with Python 3.7: "async" is a reserved word asynchronous = kwargs.get('async', False) try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise if statement_name not in __context__['cassandra_cql_prepared']: try: bound_statement = session.prepare(query) __context__['cassandra_cql_prepared'][statement_name] = bound_statement except BaseException as e: log.critical('Unexpected error while preparing SQL statement: %s', e) raise else: bound_statement = __context__['cassandra_cql_prepared'][statement_name] session.row_factory = dict_factory ret = [] try: if asynchronous: future_results = session.execute_async(bound_statement.bind(statement_arguments)) # future_results.add_callbacks(_async_log_errors) else: results = session.execute(bound_statement.bind(statement_arguments)) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if not asynchronous and results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) # If this was a synchronous call, then we either have an empty list # because there was no return, or we have a return # If this was an asynchronous call we only return the empty list return ret def version(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra version. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The version for this Cassandra cluster. :rtype: str CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.version salt 'minion1' cassandra_cql.version contact_points=minion1 ''' query = '''select release_version from system.local limit 1;''' try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra version.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra version: %s', e) raise return ret[0].get('release_version') def info(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra information for this cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The information for this Cassandra cluster. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.info salt 'minion1' cassandra_cql.info contact_points=minion1 ''' query = '''select cluster_name, data_center, partitioner, host_id, rack, release_version, cql_version, schema_version, thrift_version from system.local limit 1;''' ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list Cassandra info.') raise except BaseException as e: log.critical('Unexpected error while listing Cassandra info: %s', e) raise return ret def list_keyspaces(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List keyspaces in a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The keyspaces in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_keyspaces salt 'minion1' cassandra_cql.list_keyspaces contact_points=minion1 port=9000 ''' query = { '2': 'select keyspace_name from system.schema_keyspaces;', '3': 'select keyspace_name from system_schema.keyspaces;', } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list keyspaces.') raise except BaseException as e: log.critical('Unexpected error while listing keyspaces: %s', e) raise return ret def list_column_families(keyspace=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List column families in a Cassandra cluster for all keyspaces or just the provided one. :param keyspace: The keyspace to provide the column families for, optional. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The column families in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_column_families salt 'minion1' cassandra_cql.list_column_families contact_points=minion1 salt 'minion1' cassandra_cql.list_column_families keyspace=system ''' where_clause = "where keyspace_name = '{0}'".format(keyspace) if keyspace else "" query = { '2': '''select columnfamily_name from system.schema_columnfamilies {0};'''.format(where_clause), '3': '''select column_name from system_schema.columns {0};'''.format(where_clause), } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list column families.') raise except BaseException as e: log.critical('Unexpected error while listing column families: %s', e) raise return ret def keyspace_exists(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Check if a keyspace exists in a Cassandra cluster. :param keyspace The keyspace name to check for. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.keyspace_exists keyspace=system ''' query = { '2': '''select keyspace_name from system.schema_keyspaces where keyspace_name = '{0}';'''.format(keyspace), '3': '''select keyspace_name from system_schema.keyspaces where keyspace_name = '{0}';'''.format(keyspace), } try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not determine if keyspace exists.') raise except BaseException as e: log.critical('Unexpected error while determining if keyspace exists: %s', e) raise return True if ret else False def create_keyspace(keyspace, replication_strategy='SimpleStrategy', replication_factor=1, replication_datacenters=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new keyspace in Cassandra. :param keyspace: The keyspace name :type keyspace: str :param replication_strategy: either `SimpleStrategy` or `NetworkTopologyStrategy` :type replication_strategy: str :param replication_factor: number of replicas of data on multiple nodes. not used if using NetworkTopologyStrategy :type replication_factor: int :param replication_datacenters: string or dict of datacenter names to replication factors, required if using NetworkTopologyStrategy (will be a dict if coming from state file). :type replication_datacenters: str | dict[str, int] :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash # CLI Example: salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace replication_strategy=NetworkTopologyStrategy \ replication_datacenters='{"datacenter_1": 3, "datacenter_2": 2}' ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if not existing_keyspace: # Add the strategy, replication_factor, etc. replication_map = { 'class': replication_strategy } if replication_datacenters: if isinstance(replication_datacenters, six.string_types): try: replication_datacenter_map = salt.utils.json.loads(replication_datacenters) replication_map.update(**replication_datacenter_map) except BaseException: # pylint: disable=W0703 log.error("Could not load json replication_datacenters.") return False else: replication_map.update(**replication_datacenters) else: replication_map['replication_factor'] = replication_factor query = '''create keyspace {0} with replication = {1} and durable_writes = true;'''.format(keyspace, replication_map) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create keyspace.') raise except BaseException as e: log.critical('Unexpected error while creating keyspace: %s', e) raise def drop_keyspace(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Drop a keyspace if it exists in a Cassandra cluster. :param keyspace: The keyspace to drop. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.drop_keyspace keyspace=test salt 'minion1' cassandra_cql.drop_keyspace keyspace=test contact_points=minion1 ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if existing_keyspace: query = '''drop keyspace {0};'''.format(keyspace) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not drop keyspace.') raise except BaseException as e: log.critical('Unexpected error while dropping keyspace: %s', e) raise return True def create_user(username, password, superuser=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra user with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new user going to be a superuser? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_user username=joe password=secret salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True contact_points=minion1 ''' superuser_cql = 'superuser' if superuser else 'nosuperuser' query = '''create user if not exists {0} with password '{1}' {2};'''.format(username, password, superuser_cql) log.debug("Attempting to create a new user with username=%s superuser=%s", username, superuser_cql) # The create user query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create user.') raise except BaseException as e: log.critical('Unexpected error while creating user: %s', e) raise return True def create_role(username, password, superuser=False, login=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra role with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new role going to be a superuser? default: False :type superuser: bool :param login: Is the new role going to be allowed to log in? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_role username=joe password=secret salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True contact_points=minion1 ''' superuser_cql = 'superuser = true' if superuser else 'superuser = false' login_cql = 'login = true' if login else 'login = false' query = '''create role if not exists {0} with password '{1}' and {2} and {3} ;'''.format(username, password, superuser_cql, login_cql) log.debug("Attempting to create a new role with username=%s superuser=%s login=%s", username, superuser, login) # The create role query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create role.') raise except BaseException as e: log.critical('Unexpected error while creating role: %s', e) raise return True def list_permissions(username=None, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List permissions. :param username: The name of the user to list permissions for. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are listed. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are listed. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: Dictionary of permissions. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_permissions salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' keyspace_cql = "{0} {1}".format(resource_type, resource) if resource else "all keyspaces" permission_cql = "{0} permission".format(permission) if permission else "all permissions" query = "list {0} on {1}".format(permission_cql, keyspace_cql) if username: query = "{0} of {1}".format(query, username) log.debug("Attempting to list permissions with query '%s'", query) ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list permissions.') raise except BaseException as e: log.critical('Unexpected error while listing permissions: %s', e) raise return ret def grant_permission(username, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Grant permissions to a user. :param username: The name of the user to grant permissions to. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are granted. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are granted. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.grant_permission salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' permission_cql = "grant {0}".format(permission) if permission else "grant all permissions" resource_cql = "on {0} {1}".format(resource_type, resource) if resource else "on all keyspaces" query = "{0} {1} to {2}".format(permission_cql, resource_cql, username) log.debug("Attempting to grant permissions with query '%s'", query) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not grant permissions.') raise except BaseException as e: log.critical('Unexpected error while granting permissions: %s', e) raise return True
saltstack/salt
salt/modules/cassandra_cql.py
create_user
python
def create_user(username, password, superuser=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra user with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new user going to be a superuser? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_user username=joe password=secret salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True contact_points=minion1 ''' superuser_cql = 'superuser' if superuser else 'nosuperuser' query = '''create user if not exists {0} with password '{1}' {2};'''.format(username, password, superuser_cql) log.debug("Attempting to create a new user with username=%s superuser=%s", username, superuser_cql) # The create user query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create user.') raise except BaseException as e: log.critical('Unexpected error while creating user: %s', e) raise return True
Create a new cassandra user with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new user going to be a superuser? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_user username=joe password=secret salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True contact_points=minion1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cassandra_cql.py#L836-L882
[ "def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None):\n '''\n Run a query on a Cassandra cluster and return a dictionary.\n\n :param query: The query to execute.\n :type query: str\n :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs.\n :type contact_points: str | list[str]\n :param cql_user: The Cassandra user if authentication is turned on.\n :type cql_user: str\n :param cql_pass: The Cassandra user password if authentication is turned on.\n :type cql_pass: str\n :param port: The Cassandra cluster port, defaults to None.\n :type port: int\n :param params: The parameters for the query, optional.\n :type params: str\n :return: A dictionary from the return values of the query\n :rtype: list[dict]\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'cassandra-server' cassandra_cql.cql_query \"SELECT * FROM users_by_name WHERE first_name = 'jane'\"\n '''\n try:\n cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass)\n except CommandExecutionError:\n log.critical('Could not get Cassandra cluster session.')\n raise\n except BaseException as e:\n log.critical('Unexpected error while getting Cassandra cluster session: %s', e)\n raise\n\n session.row_factory = dict_factory\n ret = []\n\n # Cassandra changed their internal schema from v2 to v3\n # If the query contains a dictionary sorted by versions\n # Find the query for the current cluster version.\n # https://issues.apache.org/jira/browse/CASSANDRA-6717\n if isinstance(query, dict):\n cluster_version = version(contact_points=contact_points,\n port=port,\n cql_user=cql_user,\n cql_pass=cql_pass)\n match = re.match(r'^(\\d+)\\.(\\d+)(?:\\.(\\d+))?', cluster_version)\n major, minor, point = match.groups()\n # try to find the specific version in the query dictionary\n # then try the major version\n # otherwise default to the highest version number\n try:\n query = query[cluster_version]\n except KeyError:\n query = query.get(major, max(query))\n log.debug('New query is: %s', query)\n\n try:\n results = session.execute(query)\n except BaseException as e:\n log.error('Failed to execute query: %s\\n reason: %s', query, e)\n msg = \"ERROR: Cassandra query failed: {0} reason: {1}\".format(query, e)\n raise CommandExecutionError(msg)\n\n if results:\n for result in results:\n values = {}\n for key, value in six.iteritems(result):\n # Salt won't return dictionaries with odd types like uuid.UUID\n if not isinstance(value, six.text_type):\n # Must support Cassandra collection types.\n # Namely, Cassandras set, list, and map collections.\n if not isinstance(value, (set, list, dict)):\n value = six.text_type(value)\n values[key] = value\n ret.append(values)\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Cassandra Database Module .. versionadded:: 2015.5.0 This module works with Cassandra v2 and v3 and hence generates queries based on the internal schema of said version. :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :referenced by: Salt's cassandra_cql returner :configuration: The Cassandra cluster members and connection port can either be specified in the master or minion config, the minion's pillar or be passed to the module. Example configuration in the config for a single node: .. code-block:: yaml cassandra: cluster: 192.168.50.10 port: 9000 Example configuration in the config for a cluster: .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin .. versionchanged:: 2016.11.0 Added support for ``ssl_options`` and ``protocol_version``. Example configuration with `ssl options <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_: If ``ssl_options`` are present in cassandra config the cassandra_cql returner will use SSL. SSL isn't used if ``ssl_options`` isn't specified. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin ssl_options: ca_certs: /etc/ssl/certs/ca-bundle.trust.crt # SSL version should be one from the ssl module # This is an optional parameter ssl_version: PROTOCOL_TLSv1 Additionally you can also specify the ``protocol_version`` to `use <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin # defaults to 4, if not set protocol_version: 3 ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import logging import re import ssl # Import Salt Libs import salt.utils.json from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.versions SSL_VERSION = 'ssl_version' log = logging.getLogger(__name__) __virtualname__ = 'cassandra_cql' HAS_DRIVER = False try: # pylint: disable=import-error,no-name-in-module from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, \ ConnectionShutdown, OperationTimedOut from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=import-error,no-name-in-module HAS_DRIVER = True except ImportError: pass def __virtual__(): ''' Return virtual name of the module only if the python driver can be loaded. :return: The virtual name of the module. :rtype: str ''' if HAS_DRIVER: return __virtualname__ return (False, 'Cannot load cassandra_cql module: python driver not found') def _async_log_errors(errors): log.error('Cassandra_cql asynchronous call returned: %s', errors) def _load_properties(property_name, config_option, set_default=False, default=None): ''' Load properties for the cassandra module from config or pillar. :param property_name: The property to load. :type property_name: str or list of str :param config_option: The name of the config option. :type config_option: str :param set_default: Should a default be set if not found in config. :type set_default: bool :param default: The default value to be set. :type default: str or int :return: The property fetched from the configuration or default. :rtype: str or list of str ''' if not property_name: log.debug("No property specified in function, trying to load from salt configuration") try: options = __salt__['config.option']('cassandra') except BaseException as e: log.error("Failed to get cassandra config options. Reason: %s", e) raise loaded_property = options.get(config_option) if not loaded_property: if set_default: log.debug('Setting default Cassandra %s to %s', config_option, default) loaded_property = default else: log.error('No cassandra %s specified in the configuration or passed to the module.', config_option) raise CommandExecutionError("ERROR: Cassandra {0} cannot be empty.".format(config_option)) return loaded_property return property_name def _get_ssl_opts(): ''' Parse out ssl_options for Cassandra cluster connection. Make sure that the ssl_version (if any specified) is valid. ''' sslopts = __salt__['config.option']('cassandra').get('ssl_options', None) ssl_opts = {} if sslopts: ssl_opts['ca_certs'] = sslopts['ca_certs'] if SSL_VERSION in sslopts: if not sslopts[SSL_VERSION].startswith('PROTOCOL_'): valid_opts = ', '.join( [x for x in dir(ssl) if x.startswith('PROTOCOL_')] ) raise CommandExecutionError('Invalid protocol_version ' 'specified! ' 'Please make sure ' 'that the ssl protocol' 'version is one from the SSL' 'module. ' 'Valid options are ' '{0}'.format(valid_opts)) else: ssl_opts[SSL_VERSION] = \ getattr(ssl, sslopts[SSL_VERSION]) return ssl_opts else: return None def _connect(contact_points=None, port=None, cql_user=None, cql_pass=None, protocol_version=None): ''' Connect to a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str or list of str :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param protocol_version: Cassandra protocol version to use. :type port: int :return: The session and cluster objects. :rtype: cluster object, session object ''' # Lazy load the Cassandra cluster and session for this module by creating a # cluster and session when cql_query is called the first time. Get the # Cassandra cluster and session from this module's __context__ after it is # loaded the first time cql_query is called. # # TODO: Call cluster.shutdown() when the module is unloaded on # master/minion shutdown. Currently, Master.shutdown() and Minion.shutdown() # do nothing to allow loaded modules to gracefully handle resources stored # in __context__ (i.e. connection pools). This means that the connection # pool is orphaned and Salt relies on Cassandra to reclaim connections. # Perhaps if Master/Minion daemons could be enhanced to call an "__unload__" # function, or something similar for each loaded module, connection pools # and the like can be gracefully reclaimed/shutdown. if (__context__ and 'cassandra_cql_returner_cluster' in __context__ and 'cassandra_cql_returner_session' in __context__): return __context__['cassandra_cql_returner_cluster'], __context__['cassandra_cql_returner_session'] else: contact_points = _load_properties(property_name=contact_points, config_option='cluster') contact_points = contact_points if isinstance(contact_points, list) else contact_points.split(',') port = _load_properties(property_name=port, config_option='port', set_default=True, default=9042) cql_user = _load_properties(property_name=cql_user, config_option='username', set_default=True, default="cassandra") cql_pass = _load_properties(property_name=cql_pass, config_option='password', set_default=True, default="cassandra") protocol_version = _load_properties(property_name=protocol_version, config_option='protocol_version', set_default=True, default=4) try: auth_provider = PlainTextAuthProvider(username=cql_user, password=cql_pass) ssl_opts = _get_ssl_opts() if ssl_opts: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, ssl_options=ssl_opts, protocol_version=protocol_version, compression=True) else: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, protocol_version=protocol_version, compression=True) for recontimes in range(1, 4): try: session = cluster.connect() break except OperationTimedOut: log.warning('Cassandra cluster.connect timed out, try %s', recontimes) if recontimes >= 3: raise # TODO: Call cluster.shutdown() when the module is unloaded on shutdown. __context__['cassandra_cql_returner_cluster'] = cluster __context__['cassandra_cql_returner_session'] = session __context__['cassandra_cql_prepared'] = {} log.debug('Successfully connected to Cassandra cluster at %s', contact_points) return cluster, session except TypeError: pass except (ConnectionException, ConnectionShutdown, NoHostAvailable): log.error('Could not connect to Cassandra cluster at %s', contact_points) raise CommandExecutionError('ERROR: Could not connect to Cassandra cluster.') def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Run a query on a Cassandra cluster and return a dictionary. :param query: The query to execute. :type query: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash salt 'cassandra-server' cassandra_cql.cql_query "SELECT * FROM users_by_name WHERE first_name = 'jane'" ''' try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise session.row_factory = dict_factory ret = [] # Cassandra changed their internal schema from v2 to v3 # If the query contains a dictionary sorted by versions # Find the query for the current cluster version. # https://issues.apache.org/jira/browse/CASSANDRA-6717 if isinstance(query, dict): cluster_version = version(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) match = re.match(r'^(\d+)\.(\d+)(?:\.(\d+))?', cluster_version) major, minor, point = match.groups() # try to find the specific version in the query dictionary # then try the major version # otherwise default to the highest version number try: query = query[cluster_version] except KeyError: query = query.get(major, max(query)) log.debug('New query is: %s', query) try: results = session.execute(query) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) return ret def cql_query_with_prepare(query, statement_name, statement_arguments, callback_errors=None, contact_points=None, port=None, cql_user=None, cql_pass=None, **kwargs): ''' Run a query on a Cassandra cluster and return a dictionary. This function should not be used asynchronously for SELECTs -- it will not return anything and we don't currently have a mechanism for handling a future that will return results. :param query: The query to execute. :type query: str :param statement_name: Name to assign the prepared statement in the __context__ dictionary :type statement_name: str :param statement_arguments: Bind parameters for the SQL statement :type statement_arguments: list[str] :param async: Run this query in asynchronous mode :type async: bool :param callback_errors: Function to call after query runs if there is an error :type callback_errors: Function callable :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash # Insert data asynchronously salt this-node cassandra_cql.cql_query_with_prepare "name_insert" "INSERT INTO USERS (first_name, last_name) VALUES (?, ?)" \ statement_arguments=['John','Doe'], asynchronous=True # Select data, should not be asynchronous because there is not currently a facility to return data from a future salt this-node cassandra_cql.cql_query_with_prepare "name_select" "SELECT * FROM USERS WHERE first_name=?" \ statement_arguments=['John'] ''' # Backward-compatibility with Python 3.7: "async" is a reserved word asynchronous = kwargs.get('async', False) try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise if statement_name not in __context__['cassandra_cql_prepared']: try: bound_statement = session.prepare(query) __context__['cassandra_cql_prepared'][statement_name] = bound_statement except BaseException as e: log.critical('Unexpected error while preparing SQL statement: %s', e) raise else: bound_statement = __context__['cassandra_cql_prepared'][statement_name] session.row_factory = dict_factory ret = [] try: if asynchronous: future_results = session.execute_async(bound_statement.bind(statement_arguments)) # future_results.add_callbacks(_async_log_errors) else: results = session.execute(bound_statement.bind(statement_arguments)) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if not asynchronous and results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) # If this was a synchronous call, then we either have an empty list # because there was no return, or we have a return # If this was an asynchronous call we only return the empty list return ret def version(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra version. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The version for this Cassandra cluster. :rtype: str CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.version salt 'minion1' cassandra_cql.version contact_points=minion1 ''' query = '''select release_version from system.local limit 1;''' try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra version.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra version: %s', e) raise return ret[0].get('release_version') def info(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra information for this cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The information for this Cassandra cluster. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.info salt 'minion1' cassandra_cql.info contact_points=minion1 ''' query = '''select cluster_name, data_center, partitioner, host_id, rack, release_version, cql_version, schema_version, thrift_version from system.local limit 1;''' ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list Cassandra info.') raise except BaseException as e: log.critical('Unexpected error while listing Cassandra info: %s', e) raise return ret def list_keyspaces(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List keyspaces in a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The keyspaces in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_keyspaces salt 'minion1' cassandra_cql.list_keyspaces contact_points=minion1 port=9000 ''' query = { '2': 'select keyspace_name from system.schema_keyspaces;', '3': 'select keyspace_name from system_schema.keyspaces;', } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list keyspaces.') raise except BaseException as e: log.critical('Unexpected error while listing keyspaces: %s', e) raise return ret def list_column_families(keyspace=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List column families in a Cassandra cluster for all keyspaces or just the provided one. :param keyspace: The keyspace to provide the column families for, optional. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The column families in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_column_families salt 'minion1' cassandra_cql.list_column_families contact_points=minion1 salt 'minion1' cassandra_cql.list_column_families keyspace=system ''' where_clause = "where keyspace_name = '{0}'".format(keyspace) if keyspace else "" query = { '2': '''select columnfamily_name from system.schema_columnfamilies {0};'''.format(where_clause), '3': '''select column_name from system_schema.columns {0};'''.format(where_clause), } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list column families.') raise except BaseException as e: log.critical('Unexpected error while listing column families: %s', e) raise return ret def keyspace_exists(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Check if a keyspace exists in a Cassandra cluster. :param keyspace The keyspace name to check for. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.keyspace_exists keyspace=system ''' query = { '2': '''select keyspace_name from system.schema_keyspaces where keyspace_name = '{0}';'''.format(keyspace), '3': '''select keyspace_name from system_schema.keyspaces where keyspace_name = '{0}';'''.format(keyspace), } try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not determine if keyspace exists.') raise except BaseException as e: log.critical('Unexpected error while determining if keyspace exists: %s', e) raise return True if ret else False def create_keyspace(keyspace, replication_strategy='SimpleStrategy', replication_factor=1, replication_datacenters=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new keyspace in Cassandra. :param keyspace: The keyspace name :type keyspace: str :param replication_strategy: either `SimpleStrategy` or `NetworkTopologyStrategy` :type replication_strategy: str :param replication_factor: number of replicas of data on multiple nodes. not used if using NetworkTopologyStrategy :type replication_factor: int :param replication_datacenters: string or dict of datacenter names to replication factors, required if using NetworkTopologyStrategy (will be a dict if coming from state file). :type replication_datacenters: str | dict[str, int] :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash # CLI Example: salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace replication_strategy=NetworkTopologyStrategy \ replication_datacenters='{"datacenter_1": 3, "datacenter_2": 2}' ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if not existing_keyspace: # Add the strategy, replication_factor, etc. replication_map = { 'class': replication_strategy } if replication_datacenters: if isinstance(replication_datacenters, six.string_types): try: replication_datacenter_map = salt.utils.json.loads(replication_datacenters) replication_map.update(**replication_datacenter_map) except BaseException: # pylint: disable=W0703 log.error("Could not load json replication_datacenters.") return False else: replication_map.update(**replication_datacenters) else: replication_map['replication_factor'] = replication_factor query = '''create keyspace {0} with replication = {1} and durable_writes = true;'''.format(keyspace, replication_map) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create keyspace.') raise except BaseException as e: log.critical('Unexpected error while creating keyspace: %s', e) raise def drop_keyspace(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Drop a keyspace if it exists in a Cassandra cluster. :param keyspace: The keyspace to drop. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.drop_keyspace keyspace=test salt 'minion1' cassandra_cql.drop_keyspace keyspace=test contact_points=minion1 ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if existing_keyspace: query = '''drop keyspace {0};'''.format(keyspace) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not drop keyspace.') raise except BaseException as e: log.critical('Unexpected error while dropping keyspace: %s', e) raise return True def list_users(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List existing users in this Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param port: The Cassandra cluster port, defaults to None. :type port: int :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :return: The list of existing users. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_users salt 'minion1' cassandra_cql.list_users contact_points=minion1 ''' query = "list users;" ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list users.') raise except BaseException as e: log.critical('Unexpected error while listing users: %s', e) raise return ret def create_role(username, password, superuser=False, login=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra role with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new role going to be a superuser? default: False :type superuser: bool :param login: Is the new role going to be allowed to log in? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_role username=joe password=secret salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True contact_points=minion1 ''' superuser_cql = 'superuser = true' if superuser else 'superuser = false' login_cql = 'login = true' if login else 'login = false' query = '''create role if not exists {0} with password '{1}' and {2} and {3} ;'''.format(username, password, superuser_cql, login_cql) log.debug("Attempting to create a new role with username=%s superuser=%s login=%s", username, superuser, login) # The create role query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create role.') raise except BaseException as e: log.critical('Unexpected error while creating role: %s', e) raise return True def list_permissions(username=None, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List permissions. :param username: The name of the user to list permissions for. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are listed. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are listed. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: Dictionary of permissions. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_permissions salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' keyspace_cql = "{0} {1}".format(resource_type, resource) if resource else "all keyspaces" permission_cql = "{0} permission".format(permission) if permission else "all permissions" query = "list {0} on {1}".format(permission_cql, keyspace_cql) if username: query = "{0} of {1}".format(query, username) log.debug("Attempting to list permissions with query '%s'", query) ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list permissions.') raise except BaseException as e: log.critical('Unexpected error while listing permissions: %s', e) raise return ret def grant_permission(username, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Grant permissions to a user. :param username: The name of the user to grant permissions to. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are granted. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are granted. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.grant_permission salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' permission_cql = "grant {0}".format(permission) if permission else "grant all permissions" resource_cql = "on {0} {1}".format(resource_type, resource) if resource else "on all keyspaces" query = "{0} {1} to {2}".format(permission_cql, resource_cql, username) log.debug("Attempting to grant permissions with query '%s'", query) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not grant permissions.') raise except BaseException as e: log.critical('Unexpected error while granting permissions: %s', e) raise return True
saltstack/salt
salt/modules/cassandra_cql.py
list_permissions
python
def list_permissions(username=None, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List permissions. :param username: The name of the user to list permissions for. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are listed. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are listed. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: Dictionary of permissions. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_permissions salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' keyspace_cql = "{0} {1}".format(resource_type, resource) if resource else "all keyspaces" permission_cql = "{0} permission".format(permission) if permission else "all permissions" query = "list {0} on {1}".format(permission_cql, keyspace_cql) if username: query = "{0} of {1}".format(query, username) log.debug("Attempting to list permissions with query '%s'", query) ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list permissions.') raise except BaseException as e: log.critical('Unexpected error while listing permissions: %s', e) raise return ret
List permissions. :param username: The name of the user to list permissions for. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are listed. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are listed. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: Dictionary of permissions. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_permissions salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cassandra_cql.py#L939-L994
[ "def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None):\n '''\n Run a query on a Cassandra cluster and return a dictionary.\n\n :param query: The query to execute.\n :type query: str\n :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs.\n :type contact_points: str | list[str]\n :param cql_user: The Cassandra user if authentication is turned on.\n :type cql_user: str\n :param cql_pass: The Cassandra user password if authentication is turned on.\n :type cql_pass: str\n :param port: The Cassandra cluster port, defaults to None.\n :type port: int\n :param params: The parameters for the query, optional.\n :type params: str\n :return: A dictionary from the return values of the query\n :rtype: list[dict]\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'cassandra-server' cassandra_cql.cql_query \"SELECT * FROM users_by_name WHERE first_name = 'jane'\"\n '''\n try:\n cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass)\n except CommandExecutionError:\n log.critical('Could not get Cassandra cluster session.')\n raise\n except BaseException as e:\n log.critical('Unexpected error while getting Cassandra cluster session: %s', e)\n raise\n\n session.row_factory = dict_factory\n ret = []\n\n # Cassandra changed their internal schema from v2 to v3\n # If the query contains a dictionary sorted by versions\n # Find the query for the current cluster version.\n # https://issues.apache.org/jira/browse/CASSANDRA-6717\n if isinstance(query, dict):\n cluster_version = version(contact_points=contact_points,\n port=port,\n cql_user=cql_user,\n cql_pass=cql_pass)\n match = re.match(r'^(\\d+)\\.(\\d+)(?:\\.(\\d+))?', cluster_version)\n major, minor, point = match.groups()\n # try to find the specific version in the query dictionary\n # then try the major version\n # otherwise default to the highest version number\n try:\n query = query[cluster_version]\n except KeyError:\n query = query.get(major, max(query))\n log.debug('New query is: %s', query)\n\n try:\n results = session.execute(query)\n except BaseException as e:\n log.error('Failed to execute query: %s\\n reason: %s', query, e)\n msg = \"ERROR: Cassandra query failed: {0} reason: {1}\".format(query, e)\n raise CommandExecutionError(msg)\n\n if results:\n for result in results:\n values = {}\n for key, value in six.iteritems(result):\n # Salt won't return dictionaries with odd types like uuid.UUID\n if not isinstance(value, six.text_type):\n # Must support Cassandra collection types.\n # Namely, Cassandras set, list, and map collections.\n if not isinstance(value, (set, list, dict)):\n value = six.text_type(value)\n values[key] = value\n ret.append(values)\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Cassandra Database Module .. versionadded:: 2015.5.0 This module works with Cassandra v2 and v3 and hence generates queries based on the internal schema of said version. :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :referenced by: Salt's cassandra_cql returner :configuration: The Cassandra cluster members and connection port can either be specified in the master or minion config, the minion's pillar or be passed to the module. Example configuration in the config for a single node: .. code-block:: yaml cassandra: cluster: 192.168.50.10 port: 9000 Example configuration in the config for a cluster: .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin .. versionchanged:: 2016.11.0 Added support for ``ssl_options`` and ``protocol_version``. Example configuration with `ssl options <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_: If ``ssl_options`` are present in cassandra config the cassandra_cql returner will use SSL. SSL isn't used if ``ssl_options`` isn't specified. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin ssl_options: ca_certs: /etc/ssl/certs/ca-bundle.trust.crt # SSL version should be one from the ssl module # This is an optional parameter ssl_version: PROTOCOL_TLSv1 Additionally you can also specify the ``protocol_version`` to `use <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin # defaults to 4, if not set protocol_version: 3 ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import logging import re import ssl # Import Salt Libs import salt.utils.json from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.versions SSL_VERSION = 'ssl_version' log = logging.getLogger(__name__) __virtualname__ = 'cassandra_cql' HAS_DRIVER = False try: # pylint: disable=import-error,no-name-in-module from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, \ ConnectionShutdown, OperationTimedOut from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=import-error,no-name-in-module HAS_DRIVER = True except ImportError: pass def __virtual__(): ''' Return virtual name of the module only if the python driver can be loaded. :return: The virtual name of the module. :rtype: str ''' if HAS_DRIVER: return __virtualname__ return (False, 'Cannot load cassandra_cql module: python driver not found') def _async_log_errors(errors): log.error('Cassandra_cql asynchronous call returned: %s', errors) def _load_properties(property_name, config_option, set_default=False, default=None): ''' Load properties for the cassandra module from config or pillar. :param property_name: The property to load. :type property_name: str or list of str :param config_option: The name of the config option. :type config_option: str :param set_default: Should a default be set if not found in config. :type set_default: bool :param default: The default value to be set. :type default: str or int :return: The property fetched from the configuration or default. :rtype: str or list of str ''' if not property_name: log.debug("No property specified in function, trying to load from salt configuration") try: options = __salt__['config.option']('cassandra') except BaseException as e: log.error("Failed to get cassandra config options. Reason: %s", e) raise loaded_property = options.get(config_option) if not loaded_property: if set_default: log.debug('Setting default Cassandra %s to %s', config_option, default) loaded_property = default else: log.error('No cassandra %s specified in the configuration or passed to the module.', config_option) raise CommandExecutionError("ERROR: Cassandra {0} cannot be empty.".format(config_option)) return loaded_property return property_name def _get_ssl_opts(): ''' Parse out ssl_options for Cassandra cluster connection. Make sure that the ssl_version (if any specified) is valid. ''' sslopts = __salt__['config.option']('cassandra').get('ssl_options', None) ssl_opts = {} if sslopts: ssl_opts['ca_certs'] = sslopts['ca_certs'] if SSL_VERSION in sslopts: if not sslopts[SSL_VERSION].startswith('PROTOCOL_'): valid_opts = ', '.join( [x for x in dir(ssl) if x.startswith('PROTOCOL_')] ) raise CommandExecutionError('Invalid protocol_version ' 'specified! ' 'Please make sure ' 'that the ssl protocol' 'version is one from the SSL' 'module. ' 'Valid options are ' '{0}'.format(valid_opts)) else: ssl_opts[SSL_VERSION] = \ getattr(ssl, sslopts[SSL_VERSION]) return ssl_opts else: return None def _connect(contact_points=None, port=None, cql_user=None, cql_pass=None, protocol_version=None): ''' Connect to a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str or list of str :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param protocol_version: Cassandra protocol version to use. :type port: int :return: The session and cluster objects. :rtype: cluster object, session object ''' # Lazy load the Cassandra cluster and session for this module by creating a # cluster and session when cql_query is called the first time. Get the # Cassandra cluster and session from this module's __context__ after it is # loaded the first time cql_query is called. # # TODO: Call cluster.shutdown() when the module is unloaded on # master/minion shutdown. Currently, Master.shutdown() and Minion.shutdown() # do nothing to allow loaded modules to gracefully handle resources stored # in __context__ (i.e. connection pools). This means that the connection # pool is orphaned and Salt relies on Cassandra to reclaim connections. # Perhaps if Master/Minion daemons could be enhanced to call an "__unload__" # function, or something similar for each loaded module, connection pools # and the like can be gracefully reclaimed/shutdown. if (__context__ and 'cassandra_cql_returner_cluster' in __context__ and 'cassandra_cql_returner_session' in __context__): return __context__['cassandra_cql_returner_cluster'], __context__['cassandra_cql_returner_session'] else: contact_points = _load_properties(property_name=contact_points, config_option='cluster') contact_points = contact_points if isinstance(contact_points, list) else contact_points.split(',') port = _load_properties(property_name=port, config_option='port', set_default=True, default=9042) cql_user = _load_properties(property_name=cql_user, config_option='username', set_default=True, default="cassandra") cql_pass = _load_properties(property_name=cql_pass, config_option='password', set_default=True, default="cassandra") protocol_version = _load_properties(property_name=protocol_version, config_option='protocol_version', set_default=True, default=4) try: auth_provider = PlainTextAuthProvider(username=cql_user, password=cql_pass) ssl_opts = _get_ssl_opts() if ssl_opts: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, ssl_options=ssl_opts, protocol_version=protocol_version, compression=True) else: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, protocol_version=protocol_version, compression=True) for recontimes in range(1, 4): try: session = cluster.connect() break except OperationTimedOut: log.warning('Cassandra cluster.connect timed out, try %s', recontimes) if recontimes >= 3: raise # TODO: Call cluster.shutdown() when the module is unloaded on shutdown. __context__['cassandra_cql_returner_cluster'] = cluster __context__['cassandra_cql_returner_session'] = session __context__['cassandra_cql_prepared'] = {} log.debug('Successfully connected to Cassandra cluster at %s', contact_points) return cluster, session except TypeError: pass except (ConnectionException, ConnectionShutdown, NoHostAvailable): log.error('Could not connect to Cassandra cluster at %s', contact_points) raise CommandExecutionError('ERROR: Could not connect to Cassandra cluster.') def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Run a query on a Cassandra cluster and return a dictionary. :param query: The query to execute. :type query: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash salt 'cassandra-server' cassandra_cql.cql_query "SELECT * FROM users_by_name WHERE first_name = 'jane'" ''' try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise session.row_factory = dict_factory ret = [] # Cassandra changed their internal schema from v2 to v3 # If the query contains a dictionary sorted by versions # Find the query for the current cluster version. # https://issues.apache.org/jira/browse/CASSANDRA-6717 if isinstance(query, dict): cluster_version = version(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) match = re.match(r'^(\d+)\.(\d+)(?:\.(\d+))?', cluster_version) major, minor, point = match.groups() # try to find the specific version in the query dictionary # then try the major version # otherwise default to the highest version number try: query = query[cluster_version] except KeyError: query = query.get(major, max(query)) log.debug('New query is: %s', query) try: results = session.execute(query) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) return ret def cql_query_with_prepare(query, statement_name, statement_arguments, callback_errors=None, contact_points=None, port=None, cql_user=None, cql_pass=None, **kwargs): ''' Run a query on a Cassandra cluster and return a dictionary. This function should not be used asynchronously for SELECTs -- it will not return anything and we don't currently have a mechanism for handling a future that will return results. :param query: The query to execute. :type query: str :param statement_name: Name to assign the prepared statement in the __context__ dictionary :type statement_name: str :param statement_arguments: Bind parameters for the SQL statement :type statement_arguments: list[str] :param async: Run this query in asynchronous mode :type async: bool :param callback_errors: Function to call after query runs if there is an error :type callback_errors: Function callable :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash # Insert data asynchronously salt this-node cassandra_cql.cql_query_with_prepare "name_insert" "INSERT INTO USERS (first_name, last_name) VALUES (?, ?)" \ statement_arguments=['John','Doe'], asynchronous=True # Select data, should not be asynchronous because there is not currently a facility to return data from a future salt this-node cassandra_cql.cql_query_with_prepare "name_select" "SELECT * FROM USERS WHERE first_name=?" \ statement_arguments=['John'] ''' # Backward-compatibility with Python 3.7: "async" is a reserved word asynchronous = kwargs.get('async', False) try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise if statement_name not in __context__['cassandra_cql_prepared']: try: bound_statement = session.prepare(query) __context__['cassandra_cql_prepared'][statement_name] = bound_statement except BaseException as e: log.critical('Unexpected error while preparing SQL statement: %s', e) raise else: bound_statement = __context__['cassandra_cql_prepared'][statement_name] session.row_factory = dict_factory ret = [] try: if asynchronous: future_results = session.execute_async(bound_statement.bind(statement_arguments)) # future_results.add_callbacks(_async_log_errors) else: results = session.execute(bound_statement.bind(statement_arguments)) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if not asynchronous and results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) # If this was a synchronous call, then we either have an empty list # because there was no return, or we have a return # If this was an asynchronous call we only return the empty list return ret def version(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra version. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The version for this Cassandra cluster. :rtype: str CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.version salt 'minion1' cassandra_cql.version contact_points=minion1 ''' query = '''select release_version from system.local limit 1;''' try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra version.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra version: %s', e) raise return ret[0].get('release_version') def info(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra information for this cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The information for this Cassandra cluster. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.info salt 'minion1' cassandra_cql.info contact_points=minion1 ''' query = '''select cluster_name, data_center, partitioner, host_id, rack, release_version, cql_version, schema_version, thrift_version from system.local limit 1;''' ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list Cassandra info.') raise except BaseException as e: log.critical('Unexpected error while listing Cassandra info: %s', e) raise return ret def list_keyspaces(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List keyspaces in a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The keyspaces in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_keyspaces salt 'minion1' cassandra_cql.list_keyspaces contact_points=minion1 port=9000 ''' query = { '2': 'select keyspace_name from system.schema_keyspaces;', '3': 'select keyspace_name from system_schema.keyspaces;', } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list keyspaces.') raise except BaseException as e: log.critical('Unexpected error while listing keyspaces: %s', e) raise return ret def list_column_families(keyspace=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List column families in a Cassandra cluster for all keyspaces or just the provided one. :param keyspace: The keyspace to provide the column families for, optional. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The column families in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_column_families salt 'minion1' cassandra_cql.list_column_families contact_points=minion1 salt 'minion1' cassandra_cql.list_column_families keyspace=system ''' where_clause = "where keyspace_name = '{0}'".format(keyspace) if keyspace else "" query = { '2': '''select columnfamily_name from system.schema_columnfamilies {0};'''.format(where_clause), '3': '''select column_name from system_schema.columns {0};'''.format(where_clause), } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list column families.') raise except BaseException as e: log.critical('Unexpected error while listing column families: %s', e) raise return ret def keyspace_exists(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Check if a keyspace exists in a Cassandra cluster. :param keyspace The keyspace name to check for. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.keyspace_exists keyspace=system ''' query = { '2': '''select keyspace_name from system.schema_keyspaces where keyspace_name = '{0}';'''.format(keyspace), '3': '''select keyspace_name from system_schema.keyspaces where keyspace_name = '{0}';'''.format(keyspace), } try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not determine if keyspace exists.') raise except BaseException as e: log.critical('Unexpected error while determining if keyspace exists: %s', e) raise return True if ret else False def create_keyspace(keyspace, replication_strategy='SimpleStrategy', replication_factor=1, replication_datacenters=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new keyspace in Cassandra. :param keyspace: The keyspace name :type keyspace: str :param replication_strategy: either `SimpleStrategy` or `NetworkTopologyStrategy` :type replication_strategy: str :param replication_factor: number of replicas of data on multiple nodes. not used if using NetworkTopologyStrategy :type replication_factor: int :param replication_datacenters: string or dict of datacenter names to replication factors, required if using NetworkTopologyStrategy (will be a dict if coming from state file). :type replication_datacenters: str | dict[str, int] :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash # CLI Example: salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace replication_strategy=NetworkTopologyStrategy \ replication_datacenters='{"datacenter_1": 3, "datacenter_2": 2}' ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if not existing_keyspace: # Add the strategy, replication_factor, etc. replication_map = { 'class': replication_strategy } if replication_datacenters: if isinstance(replication_datacenters, six.string_types): try: replication_datacenter_map = salt.utils.json.loads(replication_datacenters) replication_map.update(**replication_datacenter_map) except BaseException: # pylint: disable=W0703 log.error("Could not load json replication_datacenters.") return False else: replication_map.update(**replication_datacenters) else: replication_map['replication_factor'] = replication_factor query = '''create keyspace {0} with replication = {1} and durable_writes = true;'''.format(keyspace, replication_map) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create keyspace.') raise except BaseException as e: log.critical('Unexpected error while creating keyspace: %s', e) raise def drop_keyspace(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Drop a keyspace if it exists in a Cassandra cluster. :param keyspace: The keyspace to drop. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.drop_keyspace keyspace=test salt 'minion1' cassandra_cql.drop_keyspace keyspace=test contact_points=minion1 ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if existing_keyspace: query = '''drop keyspace {0};'''.format(keyspace) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not drop keyspace.') raise except BaseException as e: log.critical('Unexpected error while dropping keyspace: %s', e) raise return True def list_users(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List existing users in this Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param port: The Cassandra cluster port, defaults to None. :type port: int :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :return: The list of existing users. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_users salt 'minion1' cassandra_cql.list_users contact_points=minion1 ''' query = "list users;" ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list users.') raise except BaseException as e: log.critical('Unexpected error while listing users: %s', e) raise return ret def create_user(username, password, superuser=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra user with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new user going to be a superuser? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_user username=joe password=secret salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True contact_points=minion1 ''' superuser_cql = 'superuser' if superuser else 'nosuperuser' query = '''create user if not exists {0} with password '{1}' {2};'''.format(username, password, superuser_cql) log.debug("Attempting to create a new user with username=%s superuser=%s", username, superuser_cql) # The create user query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create user.') raise except BaseException as e: log.critical('Unexpected error while creating user: %s', e) raise return True def create_role(username, password, superuser=False, login=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra role with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new role going to be a superuser? default: False :type superuser: bool :param login: Is the new role going to be allowed to log in? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_role username=joe password=secret salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True contact_points=minion1 ''' superuser_cql = 'superuser = true' if superuser else 'superuser = false' login_cql = 'login = true' if login else 'login = false' query = '''create role if not exists {0} with password '{1}' and {2} and {3} ;'''.format(username, password, superuser_cql, login_cql) log.debug("Attempting to create a new role with username=%s superuser=%s login=%s", username, superuser, login) # The create role query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create role.') raise except BaseException as e: log.critical('Unexpected error while creating role: %s', e) raise return True def grant_permission(username, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Grant permissions to a user. :param username: The name of the user to grant permissions to. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are granted. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are granted. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.grant_permission salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' permission_cql = "grant {0}".format(permission) if permission else "grant all permissions" resource_cql = "on {0} {1}".format(resource_type, resource) if resource else "on all keyspaces" query = "{0} {1} to {2}".format(permission_cql, resource_cql, username) log.debug("Attempting to grant permissions with query '%s'", query) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not grant permissions.') raise except BaseException as e: log.critical('Unexpected error while granting permissions: %s', e) raise return True
saltstack/salt
salt/modules/cassandra_cql.py
grant_permission
python
def grant_permission(username, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Grant permissions to a user. :param username: The name of the user to grant permissions to. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are granted. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are granted. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.grant_permission salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' permission_cql = "grant {0}".format(permission) if permission else "grant all permissions" resource_cql = "on {0} {1}".format(resource_type, resource) if resource else "on all keyspaces" query = "{0} {1} to {2}".format(permission_cql, resource_cql, username) log.debug("Attempting to grant permissions with query '%s'", query) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not grant permissions.') raise except BaseException as e: log.critical('Unexpected error while granting permissions: %s', e) raise return True
Grant permissions to a user. :param username: The name of the user to grant permissions to. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are granted. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are granted. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.grant_permission salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cassandra_cql.py#L997-L1046
[ "def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None):\n '''\n Run a query on a Cassandra cluster and return a dictionary.\n\n :param query: The query to execute.\n :type query: str\n :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs.\n :type contact_points: str | list[str]\n :param cql_user: The Cassandra user if authentication is turned on.\n :type cql_user: str\n :param cql_pass: The Cassandra user password if authentication is turned on.\n :type cql_pass: str\n :param port: The Cassandra cluster port, defaults to None.\n :type port: int\n :param params: The parameters for the query, optional.\n :type params: str\n :return: A dictionary from the return values of the query\n :rtype: list[dict]\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'cassandra-server' cassandra_cql.cql_query \"SELECT * FROM users_by_name WHERE first_name = 'jane'\"\n '''\n try:\n cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass)\n except CommandExecutionError:\n log.critical('Could not get Cassandra cluster session.')\n raise\n except BaseException as e:\n log.critical('Unexpected error while getting Cassandra cluster session: %s', e)\n raise\n\n session.row_factory = dict_factory\n ret = []\n\n # Cassandra changed their internal schema from v2 to v3\n # If the query contains a dictionary sorted by versions\n # Find the query for the current cluster version.\n # https://issues.apache.org/jira/browse/CASSANDRA-6717\n if isinstance(query, dict):\n cluster_version = version(contact_points=contact_points,\n port=port,\n cql_user=cql_user,\n cql_pass=cql_pass)\n match = re.match(r'^(\\d+)\\.(\\d+)(?:\\.(\\d+))?', cluster_version)\n major, minor, point = match.groups()\n # try to find the specific version in the query dictionary\n # then try the major version\n # otherwise default to the highest version number\n try:\n query = query[cluster_version]\n except KeyError:\n query = query.get(major, max(query))\n log.debug('New query is: %s', query)\n\n try:\n results = session.execute(query)\n except BaseException as e:\n log.error('Failed to execute query: %s\\n reason: %s', query, e)\n msg = \"ERROR: Cassandra query failed: {0} reason: {1}\".format(query, e)\n raise CommandExecutionError(msg)\n\n if results:\n for result in results:\n values = {}\n for key, value in six.iteritems(result):\n # Salt won't return dictionaries with odd types like uuid.UUID\n if not isinstance(value, six.text_type):\n # Must support Cassandra collection types.\n # Namely, Cassandras set, list, and map collections.\n if not isinstance(value, (set, list, dict)):\n value = six.text_type(value)\n values[key] = value\n ret.append(values)\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Cassandra Database Module .. versionadded:: 2015.5.0 This module works with Cassandra v2 and v3 and hence generates queries based on the internal schema of said version. :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :referenced by: Salt's cassandra_cql returner :configuration: The Cassandra cluster members and connection port can either be specified in the master or minion config, the minion's pillar or be passed to the module. Example configuration in the config for a single node: .. code-block:: yaml cassandra: cluster: 192.168.50.10 port: 9000 Example configuration in the config for a cluster: .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin .. versionchanged:: 2016.11.0 Added support for ``ssl_options`` and ``protocol_version``. Example configuration with `ssl options <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_: If ``ssl_options`` are present in cassandra config the cassandra_cql returner will use SSL. SSL isn't used if ``ssl_options`` isn't specified. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin ssl_options: ca_certs: /etc/ssl/certs/ca-bundle.trust.crt # SSL version should be one from the ssl module # This is an optional parameter ssl_version: PROTOCOL_TLSv1 Additionally you can also specify the ``protocol_version`` to `use <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin # defaults to 4, if not set protocol_version: 3 ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import logging import re import ssl # Import Salt Libs import salt.utils.json from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.versions SSL_VERSION = 'ssl_version' log = logging.getLogger(__name__) __virtualname__ = 'cassandra_cql' HAS_DRIVER = False try: # pylint: disable=import-error,no-name-in-module from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, \ ConnectionShutdown, OperationTimedOut from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=import-error,no-name-in-module HAS_DRIVER = True except ImportError: pass def __virtual__(): ''' Return virtual name of the module only if the python driver can be loaded. :return: The virtual name of the module. :rtype: str ''' if HAS_DRIVER: return __virtualname__ return (False, 'Cannot load cassandra_cql module: python driver not found') def _async_log_errors(errors): log.error('Cassandra_cql asynchronous call returned: %s', errors) def _load_properties(property_name, config_option, set_default=False, default=None): ''' Load properties for the cassandra module from config or pillar. :param property_name: The property to load. :type property_name: str or list of str :param config_option: The name of the config option. :type config_option: str :param set_default: Should a default be set if not found in config. :type set_default: bool :param default: The default value to be set. :type default: str or int :return: The property fetched from the configuration or default. :rtype: str or list of str ''' if not property_name: log.debug("No property specified in function, trying to load from salt configuration") try: options = __salt__['config.option']('cassandra') except BaseException as e: log.error("Failed to get cassandra config options. Reason: %s", e) raise loaded_property = options.get(config_option) if not loaded_property: if set_default: log.debug('Setting default Cassandra %s to %s', config_option, default) loaded_property = default else: log.error('No cassandra %s specified in the configuration or passed to the module.', config_option) raise CommandExecutionError("ERROR: Cassandra {0} cannot be empty.".format(config_option)) return loaded_property return property_name def _get_ssl_opts(): ''' Parse out ssl_options for Cassandra cluster connection. Make sure that the ssl_version (if any specified) is valid. ''' sslopts = __salt__['config.option']('cassandra').get('ssl_options', None) ssl_opts = {} if sslopts: ssl_opts['ca_certs'] = sslopts['ca_certs'] if SSL_VERSION in sslopts: if not sslopts[SSL_VERSION].startswith('PROTOCOL_'): valid_opts = ', '.join( [x for x in dir(ssl) if x.startswith('PROTOCOL_')] ) raise CommandExecutionError('Invalid protocol_version ' 'specified! ' 'Please make sure ' 'that the ssl protocol' 'version is one from the SSL' 'module. ' 'Valid options are ' '{0}'.format(valid_opts)) else: ssl_opts[SSL_VERSION] = \ getattr(ssl, sslopts[SSL_VERSION]) return ssl_opts else: return None def _connect(contact_points=None, port=None, cql_user=None, cql_pass=None, protocol_version=None): ''' Connect to a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str or list of str :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param protocol_version: Cassandra protocol version to use. :type port: int :return: The session and cluster objects. :rtype: cluster object, session object ''' # Lazy load the Cassandra cluster and session for this module by creating a # cluster and session when cql_query is called the first time. Get the # Cassandra cluster and session from this module's __context__ after it is # loaded the first time cql_query is called. # # TODO: Call cluster.shutdown() when the module is unloaded on # master/minion shutdown. Currently, Master.shutdown() and Minion.shutdown() # do nothing to allow loaded modules to gracefully handle resources stored # in __context__ (i.e. connection pools). This means that the connection # pool is orphaned and Salt relies on Cassandra to reclaim connections. # Perhaps if Master/Minion daemons could be enhanced to call an "__unload__" # function, or something similar for each loaded module, connection pools # and the like can be gracefully reclaimed/shutdown. if (__context__ and 'cassandra_cql_returner_cluster' in __context__ and 'cassandra_cql_returner_session' in __context__): return __context__['cassandra_cql_returner_cluster'], __context__['cassandra_cql_returner_session'] else: contact_points = _load_properties(property_name=contact_points, config_option='cluster') contact_points = contact_points if isinstance(contact_points, list) else contact_points.split(',') port = _load_properties(property_name=port, config_option='port', set_default=True, default=9042) cql_user = _load_properties(property_name=cql_user, config_option='username', set_default=True, default="cassandra") cql_pass = _load_properties(property_name=cql_pass, config_option='password', set_default=True, default="cassandra") protocol_version = _load_properties(property_name=protocol_version, config_option='protocol_version', set_default=True, default=4) try: auth_provider = PlainTextAuthProvider(username=cql_user, password=cql_pass) ssl_opts = _get_ssl_opts() if ssl_opts: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, ssl_options=ssl_opts, protocol_version=protocol_version, compression=True) else: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, protocol_version=protocol_version, compression=True) for recontimes in range(1, 4): try: session = cluster.connect() break except OperationTimedOut: log.warning('Cassandra cluster.connect timed out, try %s', recontimes) if recontimes >= 3: raise # TODO: Call cluster.shutdown() when the module is unloaded on shutdown. __context__['cassandra_cql_returner_cluster'] = cluster __context__['cassandra_cql_returner_session'] = session __context__['cassandra_cql_prepared'] = {} log.debug('Successfully connected to Cassandra cluster at %s', contact_points) return cluster, session except TypeError: pass except (ConnectionException, ConnectionShutdown, NoHostAvailable): log.error('Could not connect to Cassandra cluster at %s', contact_points) raise CommandExecutionError('ERROR: Could not connect to Cassandra cluster.') def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Run a query on a Cassandra cluster and return a dictionary. :param query: The query to execute. :type query: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash salt 'cassandra-server' cassandra_cql.cql_query "SELECT * FROM users_by_name WHERE first_name = 'jane'" ''' try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise session.row_factory = dict_factory ret = [] # Cassandra changed their internal schema from v2 to v3 # If the query contains a dictionary sorted by versions # Find the query for the current cluster version. # https://issues.apache.org/jira/browse/CASSANDRA-6717 if isinstance(query, dict): cluster_version = version(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) match = re.match(r'^(\d+)\.(\d+)(?:\.(\d+))?', cluster_version) major, minor, point = match.groups() # try to find the specific version in the query dictionary # then try the major version # otherwise default to the highest version number try: query = query[cluster_version] except KeyError: query = query.get(major, max(query)) log.debug('New query is: %s', query) try: results = session.execute(query) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) return ret def cql_query_with_prepare(query, statement_name, statement_arguments, callback_errors=None, contact_points=None, port=None, cql_user=None, cql_pass=None, **kwargs): ''' Run a query on a Cassandra cluster and return a dictionary. This function should not be used asynchronously for SELECTs -- it will not return anything and we don't currently have a mechanism for handling a future that will return results. :param query: The query to execute. :type query: str :param statement_name: Name to assign the prepared statement in the __context__ dictionary :type statement_name: str :param statement_arguments: Bind parameters for the SQL statement :type statement_arguments: list[str] :param async: Run this query in asynchronous mode :type async: bool :param callback_errors: Function to call after query runs if there is an error :type callback_errors: Function callable :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash # Insert data asynchronously salt this-node cassandra_cql.cql_query_with_prepare "name_insert" "INSERT INTO USERS (first_name, last_name) VALUES (?, ?)" \ statement_arguments=['John','Doe'], asynchronous=True # Select data, should not be asynchronous because there is not currently a facility to return data from a future salt this-node cassandra_cql.cql_query_with_prepare "name_select" "SELECT * FROM USERS WHERE first_name=?" \ statement_arguments=['John'] ''' # Backward-compatibility with Python 3.7: "async" is a reserved word asynchronous = kwargs.get('async', False) try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise if statement_name not in __context__['cassandra_cql_prepared']: try: bound_statement = session.prepare(query) __context__['cassandra_cql_prepared'][statement_name] = bound_statement except BaseException as e: log.critical('Unexpected error while preparing SQL statement: %s', e) raise else: bound_statement = __context__['cassandra_cql_prepared'][statement_name] session.row_factory = dict_factory ret = [] try: if asynchronous: future_results = session.execute_async(bound_statement.bind(statement_arguments)) # future_results.add_callbacks(_async_log_errors) else: results = session.execute(bound_statement.bind(statement_arguments)) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if not asynchronous and results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) # If this was a synchronous call, then we either have an empty list # because there was no return, or we have a return # If this was an asynchronous call we only return the empty list return ret def version(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra version. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The version for this Cassandra cluster. :rtype: str CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.version salt 'minion1' cassandra_cql.version contact_points=minion1 ''' query = '''select release_version from system.local limit 1;''' try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra version.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra version: %s', e) raise return ret[0].get('release_version') def info(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra information for this cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The information for this Cassandra cluster. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.info salt 'minion1' cassandra_cql.info contact_points=minion1 ''' query = '''select cluster_name, data_center, partitioner, host_id, rack, release_version, cql_version, schema_version, thrift_version from system.local limit 1;''' ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list Cassandra info.') raise except BaseException as e: log.critical('Unexpected error while listing Cassandra info: %s', e) raise return ret def list_keyspaces(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List keyspaces in a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The keyspaces in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_keyspaces salt 'minion1' cassandra_cql.list_keyspaces contact_points=minion1 port=9000 ''' query = { '2': 'select keyspace_name from system.schema_keyspaces;', '3': 'select keyspace_name from system_schema.keyspaces;', } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list keyspaces.') raise except BaseException as e: log.critical('Unexpected error while listing keyspaces: %s', e) raise return ret def list_column_families(keyspace=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List column families in a Cassandra cluster for all keyspaces or just the provided one. :param keyspace: The keyspace to provide the column families for, optional. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The column families in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_column_families salt 'minion1' cassandra_cql.list_column_families contact_points=minion1 salt 'minion1' cassandra_cql.list_column_families keyspace=system ''' where_clause = "where keyspace_name = '{0}'".format(keyspace) if keyspace else "" query = { '2': '''select columnfamily_name from system.schema_columnfamilies {0};'''.format(where_clause), '3': '''select column_name from system_schema.columns {0};'''.format(where_clause), } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list column families.') raise except BaseException as e: log.critical('Unexpected error while listing column families: %s', e) raise return ret def keyspace_exists(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Check if a keyspace exists in a Cassandra cluster. :param keyspace The keyspace name to check for. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.keyspace_exists keyspace=system ''' query = { '2': '''select keyspace_name from system.schema_keyspaces where keyspace_name = '{0}';'''.format(keyspace), '3': '''select keyspace_name from system_schema.keyspaces where keyspace_name = '{0}';'''.format(keyspace), } try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not determine if keyspace exists.') raise except BaseException as e: log.critical('Unexpected error while determining if keyspace exists: %s', e) raise return True if ret else False def create_keyspace(keyspace, replication_strategy='SimpleStrategy', replication_factor=1, replication_datacenters=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new keyspace in Cassandra. :param keyspace: The keyspace name :type keyspace: str :param replication_strategy: either `SimpleStrategy` or `NetworkTopologyStrategy` :type replication_strategy: str :param replication_factor: number of replicas of data on multiple nodes. not used if using NetworkTopologyStrategy :type replication_factor: int :param replication_datacenters: string or dict of datacenter names to replication factors, required if using NetworkTopologyStrategy (will be a dict if coming from state file). :type replication_datacenters: str | dict[str, int] :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash # CLI Example: salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace replication_strategy=NetworkTopologyStrategy \ replication_datacenters='{"datacenter_1": 3, "datacenter_2": 2}' ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if not existing_keyspace: # Add the strategy, replication_factor, etc. replication_map = { 'class': replication_strategy } if replication_datacenters: if isinstance(replication_datacenters, six.string_types): try: replication_datacenter_map = salt.utils.json.loads(replication_datacenters) replication_map.update(**replication_datacenter_map) except BaseException: # pylint: disable=W0703 log.error("Could not load json replication_datacenters.") return False else: replication_map.update(**replication_datacenters) else: replication_map['replication_factor'] = replication_factor query = '''create keyspace {0} with replication = {1} and durable_writes = true;'''.format(keyspace, replication_map) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create keyspace.') raise except BaseException as e: log.critical('Unexpected error while creating keyspace: %s', e) raise def drop_keyspace(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Drop a keyspace if it exists in a Cassandra cluster. :param keyspace: The keyspace to drop. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.drop_keyspace keyspace=test salt 'minion1' cassandra_cql.drop_keyspace keyspace=test contact_points=minion1 ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if existing_keyspace: query = '''drop keyspace {0};'''.format(keyspace) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not drop keyspace.') raise except BaseException as e: log.critical('Unexpected error while dropping keyspace: %s', e) raise return True def list_users(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List existing users in this Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param port: The Cassandra cluster port, defaults to None. :type port: int :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :return: The list of existing users. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_users salt 'minion1' cassandra_cql.list_users contact_points=minion1 ''' query = "list users;" ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list users.') raise except BaseException as e: log.critical('Unexpected error while listing users: %s', e) raise return ret def create_user(username, password, superuser=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra user with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new user going to be a superuser? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_user username=joe password=secret salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True contact_points=minion1 ''' superuser_cql = 'superuser' if superuser else 'nosuperuser' query = '''create user if not exists {0} with password '{1}' {2};'''.format(username, password, superuser_cql) log.debug("Attempting to create a new user with username=%s superuser=%s", username, superuser_cql) # The create user query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create user.') raise except BaseException as e: log.critical('Unexpected error while creating user: %s', e) raise return True def create_role(username, password, superuser=False, login=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra role with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new role going to be a superuser? default: False :type superuser: bool :param login: Is the new role going to be allowed to log in? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_role username=joe password=secret salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True contact_points=minion1 ''' superuser_cql = 'superuser = true' if superuser else 'superuser = false' login_cql = 'login = true' if login else 'login = false' query = '''create role if not exists {0} with password '{1}' and {2} and {3} ;'''.format(username, password, superuser_cql, login_cql) log.debug("Attempting to create a new role with username=%s superuser=%s login=%s", username, superuser, login) # The create role query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create role.') raise except BaseException as e: log.critical('Unexpected error while creating role: %s', e) raise return True def list_permissions(username=None, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List permissions. :param username: The name of the user to list permissions for. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are listed. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are listed. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: Dictionary of permissions. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_permissions salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' keyspace_cql = "{0} {1}".format(resource_type, resource) if resource else "all keyspaces" permission_cql = "{0} permission".format(permission) if permission else "all permissions" query = "list {0} on {1}".format(permission_cql, keyspace_cql) if username: query = "{0} of {1}".format(query, username) log.debug("Attempting to list permissions with query '%s'", query) ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list permissions.') raise except BaseException as e: log.critical('Unexpected error while listing permissions: %s', e) raise return ret
saltstack/salt
salt/beacons/journald.py
_get_journal
python
def _get_journal(): ''' Return the active running journal object ''' if 'systemd.journald' in __context__: return __context__['systemd.journald'] __context__['systemd.journald'] = systemd.journal.Reader() # get to the end of the journal __context__['systemd.journald'].seek_tail() __context__['systemd.journald'].get_previous() return __context__['systemd.journald']
Return the active running journal object
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/journald.py#L33-L43
null
# -*- coding: utf-8 -*- ''' A simple beacon to watch journald for specific entries ''' # Import Python libs from __future__ import absolute_import, unicode_literals # Import salt libs import salt.utils.data import salt.ext.six from salt.ext.six.moves import map # Import third party libs try: import systemd.journal HAS_SYSTEMD = True except ImportError: HAS_SYSTEMD = False import logging log = logging.getLogger(__name__) __virtualname__ = 'journald' def __virtual__(): if HAS_SYSTEMD: return __virtualname__ return False def validate(config): ''' Validate the beacon configuration ''' # Configuration for journald beacon should be a list of dicts if not isinstance(config, list): return (False, 'Configuration for journald beacon must be a list.') else: _config = {} list(map(_config.update, config)) for name in _config.get('services', {}): if not isinstance(_config['services'][name], dict): return False, ('Services configuration for journald beacon ' 'must be a list of dictionaries.') return True, 'Valid beacon configuration' def beacon(config): ''' The journald beacon allows for the systemd journal to be parsed and linked objects to be turned into events. This beacons config will return all sshd jornal entries .. code-block:: yaml beacons: journald: - services: sshd: SYSLOG_IDENTIFIER: sshd PRIORITY: 6 ''' ret = [] journal = _get_journal() _config = {} list(map(_config.update, config)) while True: cur = journal.get_next() if not cur: break for name in _config.get('services', {}): n_flag = 0 for key in _config['services'][name]: if isinstance(key, salt.ext.six.string_types): key = salt.utils.data.decode(key) if key in cur: if _config['services'][name][key] == cur[key]: n_flag += 1 if n_flag == len(_config['services'][name]): # Match! sub = salt.utils.data.simple_types_filter(cur) sub.update({'tag': name}) ret.append(sub) return ret
saltstack/salt
salt/beacons/journald.py
beacon
python
def beacon(config): ''' The journald beacon allows for the systemd journal to be parsed and linked objects to be turned into events. This beacons config will return all sshd jornal entries .. code-block:: yaml beacons: journald: - services: sshd: SYSLOG_IDENTIFIER: sshd PRIORITY: 6 ''' ret = [] journal = _get_journal() _config = {} list(map(_config.update, config)) while True: cur = journal.get_next() if not cur: break for name in _config.get('services', {}): n_flag = 0 for key in _config['services'][name]: if isinstance(key, salt.ext.six.string_types): key = salt.utils.data.decode(key) if key in cur: if _config['services'][name][key] == cur[key]: n_flag += 1 if n_flag == len(_config['services'][name]): # Match! sub = salt.utils.data.simple_types_filter(cur) sub.update({'tag': name}) ret.append(sub) return ret
The journald beacon allows for the systemd journal to be parsed and linked objects to be turned into events. This beacons config will return all sshd jornal entries .. code-block:: yaml beacons: journald: - services: sshd: SYSLOG_IDENTIFIER: sshd PRIORITY: 6
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/journald.py#L64-L104
[ "def simple_types_filter(data):\n '''\n Convert the data list, dictionary into simple types, i.e., int, float, string,\n bool, etc.\n '''\n if data is None:\n return data\n\n simpletypes_keys = (six.string_types, six.text_type, six.integer_types, float, bool)\n simpletypes_values = tuple(list(simpletypes_keys) + [list, tuple])\n\n if isinstance(data, (list, tuple)):\n simplearray = []\n for value in data:\n if value is not None:\n if isinstance(value, (dict, list)):\n value = simple_types_filter(value)\n elif not isinstance(value, simpletypes_values):\n value = repr(value)\n simplearray.append(value)\n return simplearray\n\n if isinstance(data, dict):\n simpledict = {}\n for key, value in six.iteritems(data):\n if key is not None and not isinstance(key, simpletypes_keys):\n key = repr(key)\n if value is not None and isinstance(value, (dict, list, tuple)):\n value = simple_types_filter(value)\n elif value is not None and not isinstance(value, simpletypes_values):\n value = repr(value)\n simpledict[key] = value\n return simpledict\n\n return data\n", "def _get_journal():\n '''\n Return the active running journal object\n '''\n if 'systemd.journald' in __context__:\n return __context__['systemd.journald']\n __context__['systemd.journald'] = systemd.journal.Reader()\n # get to the end of the journal\n __context__['systemd.journald'].seek_tail()\n __context__['systemd.journald'].get_previous()\n return __context__['systemd.journald']\n" ]
# -*- coding: utf-8 -*- ''' A simple beacon to watch journald for specific entries ''' # Import Python libs from __future__ import absolute_import, unicode_literals # Import salt libs import salt.utils.data import salt.ext.six from salt.ext.six.moves import map # Import third party libs try: import systemd.journal HAS_SYSTEMD = True except ImportError: HAS_SYSTEMD = False import logging log = logging.getLogger(__name__) __virtualname__ = 'journald' def __virtual__(): if HAS_SYSTEMD: return __virtualname__ return False def _get_journal(): ''' Return the active running journal object ''' if 'systemd.journald' in __context__: return __context__['systemd.journald'] __context__['systemd.journald'] = systemd.journal.Reader() # get to the end of the journal __context__['systemd.journald'].seek_tail() __context__['systemd.journald'].get_previous() return __context__['systemd.journald'] def validate(config): ''' Validate the beacon configuration ''' # Configuration for journald beacon should be a list of dicts if not isinstance(config, list): return (False, 'Configuration for journald beacon must be a list.') else: _config = {} list(map(_config.update, config)) for name in _config.get('services', {}): if not isinstance(_config['services'][name], dict): return False, ('Services configuration for journald beacon ' 'must be a list of dictionaries.') return True, 'Valid beacon configuration'
saltstack/salt
salt/returners/couchdb_return.py
_get_options
python
def _get_options(ret=None): ''' Get the couchdb options from salt. ''' attrs = {'url': 'url', 'db': 'db', 'user': 'user', 'passwd': 'passwd', 'redact_pws': 'redact_pws', 'minimum_return': 'minimum_return'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) if 'url' not in _options: log.debug("Using default url.") _options['url'] = "http://salt:5984/" if 'db' not in _options: log.debug("Using default database.") _options['db'] = "salt" if 'user' not in _options: log.debug("Not athenticating with a user.") _options['user'] = None if 'passwd' not in _options: log.debug("Not athenticating with a password.") _options['passwd'] = None if 'redact_pws' not in _options: log.debug("Not redacting passwords.") _options['redact_pws'] = None if 'minimum_return' not in _options: log.debug("Not minimizing the return object.") _options['minimum_return'] = None return _options
Get the couchdb options from salt.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L96-L136
[ "def get_returner_options(virtualname=None,\n ret=None,\n attrs=None,\n **kwargs):\n '''\n Get the returner options from salt.\n\n :param str virtualname: The returner virtualname (as returned\n by __virtual__()\n :param ret: result of the module that ran. dict-like object\n\n May contain a `ret_config` key pointing to a string\n If a `ret_config` is specified, config options are read from::\n\n value.virtualname.option\n\n If not, config options are read from::\n\n value.virtualname.option\n\n :param attrs: options the returner wants to read\n :param __opts__: Optional dict-like object that contains a fallback config\n in case the param `__salt__` is not supplied.\n\n Defaults to empty dict.\n :param __salt__: Optional dict-like object that exposes the salt API.\n\n Defaults to empty dict.\n\n a) if __salt__ contains a 'config.option' configuration options,\n we infer the returner is being called from a state or module run ->\n config is a copy of the `config.option` function\n\n b) if __salt__ was not available, we infer that the returner is being\n called from the Salt scheduler, so we look for the\n configuration options in the param `__opts__`\n -> cfg is a copy for the __opts__ dictionary\n :param str profile_attr: Optional.\n\n If supplied, an overriding config profile is read from\n the corresponding key of `__salt__`.\n\n :param dict profile_attrs: Optional\n\n .. fixme:: only keys are read\n\n For each key in profile_attr, a value is read in the are\n used to fetch a value pointed by 'virtualname.%key' in\n the dict found thanks to the param `profile_attr`\n '''\n\n ret_config = _fetch_ret_config(ret)\n\n attrs = attrs or {}\n profile_attr = kwargs.get('profile_attr', None)\n profile_attrs = kwargs.get('profile_attrs', None)\n defaults = kwargs.get('defaults', None)\n __salt__ = kwargs.get('__salt__', {})\n __opts__ = kwargs.get('__opts__', {})\n\n # select the config source\n cfg = __salt__.get('config.option', __opts__)\n\n # browse the config for relevant options, store them in a dict\n _options = dict(\n _options_browser(\n cfg,\n ret_config,\n defaults,\n virtualname,\n attrs,\n )\n )\n\n # override some values with relevant profile options\n _options.update(\n _fetch_profile_opts(\n cfg,\n virtualname,\n __salt__,\n _options,\n profile_attr,\n profile_attrs\n )\n )\n\n # override some values with relevant options from\n # keyword arguments passed via return_kwargs\n if ret and 'ret_kwargs' in ret:\n _options.update(ret['ret_kwargs'])\n\n return _options\n" ]
# -*- coding: utf-8 -*- ''' Simple returner for CouchDB. Optional configuration settings are listed below, along with sane defaults: .. code-block:: yaml couchdb.db: 'salt' couchdb.url: 'http://salt:5984/' couchdb.user: None couchdb.passwd: None couchdb.redact_pws: None couchdb.minimum_return: None Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location: .. code-block:: yaml alternative.couchdb.db: 'salt' alternative.couchdb.url: 'http://salt:5984/' To use the couchdb returner, append ``--return couchdb`` to the salt command. Example: .. code-block:: bash salt '*' test.ping --return couchdb To use the alternative configuration, append ``--return_config alternative`` to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_kwargs '{"db": "another-salt"}' On concurrent database access ============================== As this returner creates a couchdb document with the salt job id as document id and as only one document with a given id can exist in a given couchdb database, it is advised for most setups that every minion be configured to write to it own database (the value of ``couchdb.db`` may be suffixed with the minion id), otherwise multi-minion targeting can lead to losing output: * the first returning minion is able to create a document in the database * other minions fail with ``{'error': 'HTTP Error 409: Conflict'}`` ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.error import HTTPError from salt.ext.six.moves.urllib.request import ( Request as _Request, HTTPHandler as _HTTPHandler, build_opener as _build_opener, ) # pylint: enable=no-name-in-module,import-error # Import Salt libs import salt.utils.jid import salt.utils.json import salt.returners # boltons lib for redact_pws and minimum_return try: from boltons.iterutils import remap boltons_lib = True except ImportError: boltons_lib = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchdb' def __virtual__(): return __virtualname__ def _redact_passwords(path, key, value): if 'password' in str(key) and value: return key, 'XXX-REDACTED-XXX' return key, value def _minimize_return(path, key, value): if isinstance(key, str) and key.startswith('__pub'): return False return True def _generate_doc(ret): ''' Create a object that will be saved into the database based on options. ''' # Create a copy of the object that we will return. retc = ret.copy() # Set the ID of the document to be the JID. retc["_id"] = ret["jid"] # Add a timestamp field to the document retc["timestamp"] = time.time() return retc def _request(method, url, content_type=None, _data=None, user=None, passwd=None): ''' Makes a HTTP request. Returns the JSON parse, or an obj with an error. ''' opener = _build_opener(_HTTPHandler) request = _Request(url, data=_data) if content_type: request.add_header('Content-Type', content_type) if user and passwd: auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1] auth_basic = "Basic {0}".format(auth_encode) request.add_header('Authorization', auth_basic) request.add_header('Accept', 'application/json') request.get_method = lambda: method try: handler = opener.open(request) except HTTPError as exc: return {'error': '{0}'.format(exc)} return salt.utils.json.loads(handler.read()) def _generate_event_doc(event): ''' Create a object that will be saved into the database based in options. ''' # Create a copy of the object that we will return. eventc = event.copy() # Set the ID of the document to be the JID. eventc["_id"] = '{}-{}'.format( event.get('tag', '').split('/')[2], event.get('tag', '').split('/')[3] ) # Add a timestamp field to the document eventc["timestamp"] = time.time() # remove any return data as it's captured in the "returner" function if eventc.get('data').get('return'): del eventc['data']['return'] return eventc def returner(ret): ''' Take in the return and shove it into the couchdb database. ''' options = _get_options(ret) # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs", user=options['user'], passwd=options['passwd']) if options['db'] not in _response: # Make a PUT request to create the database. _response = _request("PUT", options['url'] + options['db'], user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', options['db']) log.debug('_response object is: %s', _response) return log.info('Created database "%s"', options['db']) if boltons_lib: # redact all passwords if options['redact_pws'] is True if options['redact_pws']: ret_remap_pws = remap(ret, visit=_redact_passwords) else: ret_remap_pws = ret # remove all return values starting with '__pub' if options['minimum_return'] is True if options['minimum_return']: ret_remapped = remap(ret_remap_pws, visit=_minimize_return) else: ret_remapped = ret_remap_pws else: log.info('boltons library not installed. pip install boltons. https://github.com/mahmoud/boltons.') ret_remapped = ret # Call _generate_doc to get a dict object of the document we're going to shove into the database. doc = _generate_doc(ret_remapped) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + options['db'] + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def event_return(events): ''' Return event to CouchDB server Requires that configuration be enabled via 'event_return' option in master config. Example: event_return: - couchdb ''' log.debug('events data is: %s', events) options = _get_options() # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs") event_db = '{}-events'.format(options['db']) if event_db not in _response: # Make a PUT request to create the database. log.info('Creating database "%s"', event_db) _response = _request("PUT", options['url'] + event_db, user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', event_db) return log.info('Created database "%s"', event_db) for event in events: # Call _generate_doc to get a dict object of the document we're going to shove into the database. log.debug('event data is: %s', event) doc = _generate_event_doc(event) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + event_db + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def get_jid(jid): ''' Get the document with a given JID. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response} def get_jids(): ''' List all the jobs that we have.. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + "/_all_docs?include_docs=true") # Make sure the 'total_rows' is returned.. if not error out. if 'total_rows' not in _response: log.error('Didn\'t get valid response from requesting all docs: %s', _response) return {} # Return the rows. ret = {} for row in _response['rows']: # Because this shows all the documents in the database, including the # design documents, verify the id is salt jid jid = row['id'] if not salt.utils.jid.is_jid(jid): continue ret[jid] = salt.utils.jid.format_jid_instance(jid, row['doc']) return ret def get_fun(fun): ''' Return a dict with key being minion and value being the job details of the last run of function 'fun'. ''' # Get the options.. options = _get_options(ret=None) # Define a simple return object. _ret = {} # get_minions takes care of calling ensure_views for us. For each minion we know about for minion in get_minions(): # Make a query of the by-minion-and-timestamp view and limit the count to 1. _response = _request("GET", options['url'] + options['db'] + ('/_design/salt/_view/by-minion-fun-times' 'tamp?descending=true&endkey=["{0}","{1}' '",0]&startkey=["{2}","{3}",9999999999]&' 'limit=1').format(minion, fun, minion, fun)) # Skip the minion if we got an error.. if 'error' in _response: log.warning('Got an error when querying for last command ' 'by a minion: %s', _response['error']) continue # Skip the minion if we didn't get any rows back. ( IE function that # they're looking for has a typo in it or some such ). if not _response['rows']: continue # Set the respnse .. _ret[minion] = _response['rows'][0]['value'] return _ret def get_minions(): ''' Return a list of minion identifiers from a request of the view. ''' options = _get_options(ret=None) # Make sure the views are valid, which includes the minions.. if not ensure_views(): return [] # Make the request for the view.. _response = _request("GET", options['url'] + options['db'] + "/_design/salt/_view/minions?group=true") # Verify that we got a response back. if 'rows' not in _response: log.error('Unable to get available minions: %s', _response) return [] # Iterate over the rows to build up a list return it. _ret = [] for row in _response['rows']: _ret.append(row['key']) return _ret def ensure_views(): ''' This function makes sure that all the views that should exist in the design document do exist. ''' # Get the options so we have the URL and DB.. options = _get_options(ret=None) # Make a request to check if the design document exists. _response = _request("GET", options['url'] + options['db'] + "/_design/salt") # If the document doesn't exist, or for some reason there are not views. if 'error' in _response: return set_salt_view() # Determine if any views are missing from the design doc stored on the # server.. If we come across one, simply set the salt view and return out. # set_salt_view will set all the views, so we don't need to continue t # check. for view in get_valid_salt_views(): if view not in _response['views']: return set_salt_view() # Valid views, return true. return True def get_valid_salt_views(): ''' Returns a dict object of views that should be part of the salt design document. ''' ret = {} ret['minions'] = {} ret['minions']['map'] = "function( doc ){ emit( doc.id, null ); }" ret['minions']['reduce'] = \ "function( keys,values,rereduce ){ return key[0]; }" ret['by-minion-fun-timestamp'] = {} ret['by-minion-fun-timestamp']['map'] = \ "function( doc ){ emit( [doc.id,doc.fun,doc.timestamp], doc ); }" return ret def set_salt_view(): ''' Helper function that sets the salt design document. Uses get_valid_salt_views and some hardcoded values. ''' options = _get_options(ret=None) # Create the new object that we will shove in as the design doc. new_doc = {} new_doc['views'] = get_valid_salt_views() new_doc['language'] = "javascript" # Make the request to update the design doc. _response = _request("PUT", options['url'] + options['db'] + "/_design/salt", "application/json", salt.utils.json.dumps(new_doc)) if 'error' in _response: log.warning('Unable to set the salt design document: %s', _response['error']) return False return True def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def save_load(jid, load): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def get_load(jid): ''' Included for API consistency ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response}
saltstack/salt
salt/returners/couchdb_return.py
_generate_doc
python
def _generate_doc(ret): ''' Create a object that will be saved into the database based on options. ''' # Create a copy of the object that we will return. retc = ret.copy() # Set the ID of the document to be the JID. retc["_id"] = ret["jid"] # Add a timestamp field to the document retc["timestamp"] = time.time() return retc
Create a object that will be saved into the database based on options.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L151-L166
null
# -*- coding: utf-8 -*- ''' Simple returner for CouchDB. Optional configuration settings are listed below, along with sane defaults: .. code-block:: yaml couchdb.db: 'salt' couchdb.url: 'http://salt:5984/' couchdb.user: None couchdb.passwd: None couchdb.redact_pws: None couchdb.minimum_return: None Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location: .. code-block:: yaml alternative.couchdb.db: 'salt' alternative.couchdb.url: 'http://salt:5984/' To use the couchdb returner, append ``--return couchdb`` to the salt command. Example: .. code-block:: bash salt '*' test.ping --return couchdb To use the alternative configuration, append ``--return_config alternative`` to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_kwargs '{"db": "another-salt"}' On concurrent database access ============================== As this returner creates a couchdb document with the salt job id as document id and as only one document with a given id can exist in a given couchdb database, it is advised for most setups that every minion be configured to write to it own database (the value of ``couchdb.db`` may be suffixed with the minion id), otherwise multi-minion targeting can lead to losing output: * the first returning minion is able to create a document in the database * other minions fail with ``{'error': 'HTTP Error 409: Conflict'}`` ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.error import HTTPError from salt.ext.six.moves.urllib.request import ( Request as _Request, HTTPHandler as _HTTPHandler, build_opener as _build_opener, ) # pylint: enable=no-name-in-module,import-error # Import Salt libs import salt.utils.jid import salt.utils.json import salt.returners # boltons lib for redact_pws and minimum_return try: from boltons.iterutils import remap boltons_lib = True except ImportError: boltons_lib = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchdb' def __virtual__(): return __virtualname__ def _get_options(ret=None): ''' Get the couchdb options from salt. ''' attrs = {'url': 'url', 'db': 'db', 'user': 'user', 'passwd': 'passwd', 'redact_pws': 'redact_pws', 'minimum_return': 'minimum_return'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) if 'url' not in _options: log.debug("Using default url.") _options['url'] = "http://salt:5984/" if 'db' not in _options: log.debug("Using default database.") _options['db'] = "salt" if 'user' not in _options: log.debug("Not athenticating with a user.") _options['user'] = None if 'passwd' not in _options: log.debug("Not athenticating with a password.") _options['passwd'] = None if 'redact_pws' not in _options: log.debug("Not redacting passwords.") _options['redact_pws'] = None if 'minimum_return' not in _options: log.debug("Not minimizing the return object.") _options['minimum_return'] = None return _options def _redact_passwords(path, key, value): if 'password' in str(key) and value: return key, 'XXX-REDACTED-XXX' return key, value def _minimize_return(path, key, value): if isinstance(key, str) and key.startswith('__pub'): return False return True def _request(method, url, content_type=None, _data=None, user=None, passwd=None): ''' Makes a HTTP request. Returns the JSON parse, or an obj with an error. ''' opener = _build_opener(_HTTPHandler) request = _Request(url, data=_data) if content_type: request.add_header('Content-Type', content_type) if user and passwd: auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1] auth_basic = "Basic {0}".format(auth_encode) request.add_header('Authorization', auth_basic) request.add_header('Accept', 'application/json') request.get_method = lambda: method try: handler = opener.open(request) except HTTPError as exc: return {'error': '{0}'.format(exc)} return salt.utils.json.loads(handler.read()) def _generate_event_doc(event): ''' Create a object that will be saved into the database based in options. ''' # Create a copy of the object that we will return. eventc = event.copy() # Set the ID of the document to be the JID. eventc["_id"] = '{}-{}'.format( event.get('tag', '').split('/')[2], event.get('tag', '').split('/')[3] ) # Add a timestamp field to the document eventc["timestamp"] = time.time() # remove any return data as it's captured in the "returner" function if eventc.get('data').get('return'): del eventc['data']['return'] return eventc def returner(ret): ''' Take in the return and shove it into the couchdb database. ''' options = _get_options(ret) # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs", user=options['user'], passwd=options['passwd']) if options['db'] not in _response: # Make a PUT request to create the database. _response = _request("PUT", options['url'] + options['db'], user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', options['db']) log.debug('_response object is: %s', _response) return log.info('Created database "%s"', options['db']) if boltons_lib: # redact all passwords if options['redact_pws'] is True if options['redact_pws']: ret_remap_pws = remap(ret, visit=_redact_passwords) else: ret_remap_pws = ret # remove all return values starting with '__pub' if options['minimum_return'] is True if options['minimum_return']: ret_remapped = remap(ret_remap_pws, visit=_minimize_return) else: ret_remapped = ret_remap_pws else: log.info('boltons library not installed. pip install boltons. https://github.com/mahmoud/boltons.') ret_remapped = ret # Call _generate_doc to get a dict object of the document we're going to shove into the database. doc = _generate_doc(ret_remapped) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + options['db'] + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def event_return(events): ''' Return event to CouchDB server Requires that configuration be enabled via 'event_return' option in master config. Example: event_return: - couchdb ''' log.debug('events data is: %s', events) options = _get_options() # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs") event_db = '{}-events'.format(options['db']) if event_db not in _response: # Make a PUT request to create the database. log.info('Creating database "%s"', event_db) _response = _request("PUT", options['url'] + event_db, user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', event_db) return log.info('Created database "%s"', event_db) for event in events: # Call _generate_doc to get a dict object of the document we're going to shove into the database. log.debug('event data is: %s', event) doc = _generate_event_doc(event) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + event_db + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def get_jid(jid): ''' Get the document with a given JID. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response} def get_jids(): ''' List all the jobs that we have.. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + "/_all_docs?include_docs=true") # Make sure the 'total_rows' is returned.. if not error out. if 'total_rows' not in _response: log.error('Didn\'t get valid response from requesting all docs: %s', _response) return {} # Return the rows. ret = {} for row in _response['rows']: # Because this shows all the documents in the database, including the # design documents, verify the id is salt jid jid = row['id'] if not salt.utils.jid.is_jid(jid): continue ret[jid] = salt.utils.jid.format_jid_instance(jid, row['doc']) return ret def get_fun(fun): ''' Return a dict with key being minion and value being the job details of the last run of function 'fun'. ''' # Get the options.. options = _get_options(ret=None) # Define a simple return object. _ret = {} # get_minions takes care of calling ensure_views for us. For each minion we know about for minion in get_minions(): # Make a query of the by-minion-and-timestamp view and limit the count to 1. _response = _request("GET", options['url'] + options['db'] + ('/_design/salt/_view/by-minion-fun-times' 'tamp?descending=true&endkey=["{0}","{1}' '",0]&startkey=["{2}","{3}",9999999999]&' 'limit=1').format(minion, fun, minion, fun)) # Skip the minion if we got an error.. if 'error' in _response: log.warning('Got an error when querying for last command ' 'by a minion: %s', _response['error']) continue # Skip the minion if we didn't get any rows back. ( IE function that # they're looking for has a typo in it or some such ). if not _response['rows']: continue # Set the respnse .. _ret[minion] = _response['rows'][0]['value'] return _ret def get_minions(): ''' Return a list of minion identifiers from a request of the view. ''' options = _get_options(ret=None) # Make sure the views are valid, which includes the minions.. if not ensure_views(): return [] # Make the request for the view.. _response = _request("GET", options['url'] + options['db'] + "/_design/salt/_view/minions?group=true") # Verify that we got a response back. if 'rows' not in _response: log.error('Unable to get available minions: %s', _response) return [] # Iterate over the rows to build up a list return it. _ret = [] for row in _response['rows']: _ret.append(row['key']) return _ret def ensure_views(): ''' This function makes sure that all the views that should exist in the design document do exist. ''' # Get the options so we have the URL and DB.. options = _get_options(ret=None) # Make a request to check if the design document exists. _response = _request("GET", options['url'] + options['db'] + "/_design/salt") # If the document doesn't exist, or for some reason there are not views. if 'error' in _response: return set_salt_view() # Determine if any views are missing from the design doc stored on the # server.. If we come across one, simply set the salt view and return out. # set_salt_view will set all the views, so we don't need to continue t # check. for view in get_valid_salt_views(): if view not in _response['views']: return set_salt_view() # Valid views, return true. return True def get_valid_salt_views(): ''' Returns a dict object of views that should be part of the salt design document. ''' ret = {} ret['minions'] = {} ret['minions']['map'] = "function( doc ){ emit( doc.id, null ); }" ret['minions']['reduce'] = \ "function( keys,values,rereduce ){ return key[0]; }" ret['by-minion-fun-timestamp'] = {} ret['by-minion-fun-timestamp']['map'] = \ "function( doc ){ emit( [doc.id,doc.fun,doc.timestamp], doc ); }" return ret def set_salt_view(): ''' Helper function that sets the salt design document. Uses get_valid_salt_views and some hardcoded values. ''' options = _get_options(ret=None) # Create the new object that we will shove in as the design doc. new_doc = {} new_doc['views'] = get_valid_salt_views() new_doc['language'] = "javascript" # Make the request to update the design doc. _response = _request("PUT", options['url'] + options['db'] + "/_design/salt", "application/json", salt.utils.json.dumps(new_doc)) if 'error' in _response: log.warning('Unable to set the salt design document: %s', _response['error']) return False return True def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def save_load(jid, load): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def get_load(jid): ''' Included for API consistency ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response}
saltstack/salt
salt/returners/couchdb_return.py
_request
python
def _request(method, url, content_type=None, _data=None, user=None, passwd=None): ''' Makes a HTTP request. Returns the JSON parse, or an obj with an error. ''' opener = _build_opener(_HTTPHandler) request = _Request(url, data=_data) if content_type: request.add_header('Content-Type', content_type) if user and passwd: auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1] auth_basic = "Basic {0}".format(auth_encode) request.add_header('Authorization', auth_basic) request.add_header('Accept', 'application/json') request.get_method = lambda: method try: handler = opener.open(request) except HTTPError as exc: return {'error': '{0}'.format(exc)} return salt.utils.json.loads(handler.read())
Makes a HTTP request. Returns the JSON parse, or an obj with an error.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L169-L187
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n" ]
# -*- coding: utf-8 -*- ''' Simple returner for CouchDB. Optional configuration settings are listed below, along with sane defaults: .. code-block:: yaml couchdb.db: 'salt' couchdb.url: 'http://salt:5984/' couchdb.user: None couchdb.passwd: None couchdb.redact_pws: None couchdb.minimum_return: None Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location: .. code-block:: yaml alternative.couchdb.db: 'salt' alternative.couchdb.url: 'http://salt:5984/' To use the couchdb returner, append ``--return couchdb`` to the salt command. Example: .. code-block:: bash salt '*' test.ping --return couchdb To use the alternative configuration, append ``--return_config alternative`` to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_kwargs '{"db": "another-salt"}' On concurrent database access ============================== As this returner creates a couchdb document with the salt job id as document id and as only one document with a given id can exist in a given couchdb database, it is advised for most setups that every minion be configured to write to it own database (the value of ``couchdb.db`` may be suffixed with the minion id), otherwise multi-minion targeting can lead to losing output: * the first returning minion is able to create a document in the database * other minions fail with ``{'error': 'HTTP Error 409: Conflict'}`` ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.error import HTTPError from salt.ext.six.moves.urllib.request import ( Request as _Request, HTTPHandler as _HTTPHandler, build_opener as _build_opener, ) # pylint: enable=no-name-in-module,import-error # Import Salt libs import salt.utils.jid import salt.utils.json import salt.returners # boltons lib for redact_pws and minimum_return try: from boltons.iterutils import remap boltons_lib = True except ImportError: boltons_lib = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchdb' def __virtual__(): return __virtualname__ def _get_options(ret=None): ''' Get the couchdb options from salt. ''' attrs = {'url': 'url', 'db': 'db', 'user': 'user', 'passwd': 'passwd', 'redact_pws': 'redact_pws', 'minimum_return': 'minimum_return'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) if 'url' not in _options: log.debug("Using default url.") _options['url'] = "http://salt:5984/" if 'db' not in _options: log.debug("Using default database.") _options['db'] = "salt" if 'user' not in _options: log.debug("Not athenticating with a user.") _options['user'] = None if 'passwd' not in _options: log.debug("Not athenticating with a password.") _options['passwd'] = None if 'redact_pws' not in _options: log.debug("Not redacting passwords.") _options['redact_pws'] = None if 'minimum_return' not in _options: log.debug("Not minimizing the return object.") _options['minimum_return'] = None return _options def _redact_passwords(path, key, value): if 'password' in str(key) and value: return key, 'XXX-REDACTED-XXX' return key, value def _minimize_return(path, key, value): if isinstance(key, str) and key.startswith('__pub'): return False return True def _generate_doc(ret): ''' Create a object that will be saved into the database based on options. ''' # Create a copy of the object that we will return. retc = ret.copy() # Set the ID of the document to be the JID. retc["_id"] = ret["jid"] # Add a timestamp field to the document retc["timestamp"] = time.time() return retc def _generate_event_doc(event): ''' Create a object that will be saved into the database based in options. ''' # Create a copy of the object that we will return. eventc = event.copy() # Set the ID of the document to be the JID. eventc["_id"] = '{}-{}'.format( event.get('tag', '').split('/')[2], event.get('tag', '').split('/')[3] ) # Add a timestamp field to the document eventc["timestamp"] = time.time() # remove any return data as it's captured in the "returner" function if eventc.get('data').get('return'): del eventc['data']['return'] return eventc def returner(ret): ''' Take in the return and shove it into the couchdb database. ''' options = _get_options(ret) # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs", user=options['user'], passwd=options['passwd']) if options['db'] not in _response: # Make a PUT request to create the database. _response = _request("PUT", options['url'] + options['db'], user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', options['db']) log.debug('_response object is: %s', _response) return log.info('Created database "%s"', options['db']) if boltons_lib: # redact all passwords if options['redact_pws'] is True if options['redact_pws']: ret_remap_pws = remap(ret, visit=_redact_passwords) else: ret_remap_pws = ret # remove all return values starting with '__pub' if options['minimum_return'] is True if options['minimum_return']: ret_remapped = remap(ret_remap_pws, visit=_minimize_return) else: ret_remapped = ret_remap_pws else: log.info('boltons library not installed. pip install boltons. https://github.com/mahmoud/boltons.') ret_remapped = ret # Call _generate_doc to get a dict object of the document we're going to shove into the database. doc = _generate_doc(ret_remapped) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + options['db'] + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def event_return(events): ''' Return event to CouchDB server Requires that configuration be enabled via 'event_return' option in master config. Example: event_return: - couchdb ''' log.debug('events data is: %s', events) options = _get_options() # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs") event_db = '{}-events'.format(options['db']) if event_db not in _response: # Make a PUT request to create the database. log.info('Creating database "%s"', event_db) _response = _request("PUT", options['url'] + event_db, user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', event_db) return log.info('Created database "%s"', event_db) for event in events: # Call _generate_doc to get a dict object of the document we're going to shove into the database. log.debug('event data is: %s', event) doc = _generate_event_doc(event) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + event_db + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def get_jid(jid): ''' Get the document with a given JID. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response} def get_jids(): ''' List all the jobs that we have.. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + "/_all_docs?include_docs=true") # Make sure the 'total_rows' is returned.. if not error out. if 'total_rows' not in _response: log.error('Didn\'t get valid response from requesting all docs: %s', _response) return {} # Return the rows. ret = {} for row in _response['rows']: # Because this shows all the documents in the database, including the # design documents, verify the id is salt jid jid = row['id'] if not salt.utils.jid.is_jid(jid): continue ret[jid] = salt.utils.jid.format_jid_instance(jid, row['doc']) return ret def get_fun(fun): ''' Return a dict with key being minion and value being the job details of the last run of function 'fun'. ''' # Get the options.. options = _get_options(ret=None) # Define a simple return object. _ret = {} # get_minions takes care of calling ensure_views for us. For each minion we know about for minion in get_minions(): # Make a query of the by-minion-and-timestamp view and limit the count to 1. _response = _request("GET", options['url'] + options['db'] + ('/_design/salt/_view/by-minion-fun-times' 'tamp?descending=true&endkey=["{0}","{1}' '",0]&startkey=["{2}","{3}",9999999999]&' 'limit=1').format(minion, fun, minion, fun)) # Skip the minion if we got an error.. if 'error' in _response: log.warning('Got an error when querying for last command ' 'by a minion: %s', _response['error']) continue # Skip the minion if we didn't get any rows back. ( IE function that # they're looking for has a typo in it or some such ). if not _response['rows']: continue # Set the respnse .. _ret[minion] = _response['rows'][0]['value'] return _ret def get_minions(): ''' Return a list of minion identifiers from a request of the view. ''' options = _get_options(ret=None) # Make sure the views are valid, which includes the minions.. if not ensure_views(): return [] # Make the request for the view.. _response = _request("GET", options['url'] + options['db'] + "/_design/salt/_view/minions?group=true") # Verify that we got a response back. if 'rows' not in _response: log.error('Unable to get available minions: %s', _response) return [] # Iterate over the rows to build up a list return it. _ret = [] for row in _response['rows']: _ret.append(row['key']) return _ret def ensure_views(): ''' This function makes sure that all the views that should exist in the design document do exist. ''' # Get the options so we have the URL and DB.. options = _get_options(ret=None) # Make a request to check if the design document exists. _response = _request("GET", options['url'] + options['db'] + "/_design/salt") # If the document doesn't exist, or for some reason there are not views. if 'error' in _response: return set_salt_view() # Determine if any views are missing from the design doc stored on the # server.. If we come across one, simply set the salt view and return out. # set_salt_view will set all the views, so we don't need to continue t # check. for view in get_valid_salt_views(): if view not in _response['views']: return set_salt_view() # Valid views, return true. return True def get_valid_salt_views(): ''' Returns a dict object of views that should be part of the salt design document. ''' ret = {} ret['minions'] = {} ret['minions']['map'] = "function( doc ){ emit( doc.id, null ); }" ret['minions']['reduce'] = \ "function( keys,values,rereduce ){ return key[0]; }" ret['by-minion-fun-timestamp'] = {} ret['by-minion-fun-timestamp']['map'] = \ "function( doc ){ emit( [doc.id,doc.fun,doc.timestamp], doc ); }" return ret def set_salt_view(): ''' Helper function that sets the salt design document. Uses get_valid_salt_views and some hardcoded values. ''' options = _get_options(ret=None) # Create the new object that we will shove in as the design doc. new_doc = {} new_doc['views'] = get_valid_salt_views() new_doc['language'] = "javascript" # Make the request to update the design doc. _response = _request("PUT", options['url'] + options['db'] + "/_design/salt", "application/json", salt.utils.json.dumps(new_doc)) if 'error' in _response: log.warning('Unable to set the salt design document: %s', _response['error']) return False return True def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def save_load(jid, load): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def get_load(jid): ''' Included for API consistency ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response}
saltstack/salt
salt/returners/couchdb_return.py
_generate_event_doc
python
def _generate_event_doc(event): ''' Create a object that will be saved into the database based in options. ''' # Create a copy of the object that we will return. eventc = event.copy() # Set the ID of the document to be the JID. eventc["_id"] = '{}-{}'.format( event.get('tag', '').split('/')[2], event.get('tag', '').split('/')[3] ) # Add a timestamp field to the document eventc["timestamp"] = time.time() # remove any return data as it's captured in the "returner" function if eventc.get('data').get('return'): del eventc['data']['return'] return eventc
Create a object that will be saved into the database based in options.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L190-L212
null
# -*- coding: utf-8 -*- ''' Simple returner for CouchDB. Optional configuration settings are listed below, along with sane defaults: .. code-block:: yaml couchdb.db: 'salt' couchdb.url: 'http://salt:5984/' couchdb.user: None couchdb.passwd: None couchdb.redact_pws: None couchdb.minimum_return: None Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location: .. code-block:: yaml alternative.couchdb.db: 'salt' alternative.couchdb.url: 'http://salt:5984/' To use the couchdb returner, append ``--return couchdb`` to the salt command. Example: .. code-block:: bash salt '*' test.ping --return couchdb To use the alternative configuration, append ``--return_config alternative`` to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_kwargs '{"db": "another-salt"}' On concurrent database access ============================== As this returner creates a couchdb document with the salt job id as document id and as only one document with a given id can exist in a given couchdb database, it is advised for most setups that every minion be configured to write to it own database (the value of ``couchdb.db`` may be suffixed with the minion id), otherwise multi-minion targeting can lead to losing output: * the first returning minion is able to create a document in the database * other minions fail with ``{'error': 'HTTP Error 409: Conflict'}`` ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.error import HTTPError from salt.ext.six.moves.urllib.request import ( Request as _Request, HTTPHandler as _HTTPHandler, build_opener as _build_opener, ) # pylint: enable=no-name-in-module,import-error # Import Salt libs import salt.utils.jid import salt.utils.json import salt.returners # boltons lib for redact_pws and minimum_return try: from boltons.iterutils import remap boltons_lib = True except ImportError: boltons_lib = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchdb' def __virtual__(): return __virtualname__ def _get_options(ret=None): ''' Get the couchdb options from salt. ''' attrs = {'url': 'url', 'db': 'db', 'user': 'user', 'passwd': 'passwd', 'redact_pws': 'redact_pws', 'minimum_return': 'minimum_return'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) if 'url' not in _options: log.debug("Using default url.") _options['url'] = "http://salt:5984/" if 'db' not in _options: log.debug("Using default database.") _options['db'] = "salt" if 'user' not in _options: log.debug("Not athenticating with a user.") _options['user'] = None if 'passwd' not in _options: log.debug("Not athenticating with a password.") _options['passwd'] = None if 'redact_pws' not in _options: log.debug("Not redacting passwords.") _options['redact_pws'] = None if 'minimum_return' not in _options: log.debug("Not minimizing the return object.") _options['minimum_return'] = None return _options def _redact_passwords(path, key, value): if 'password' in str(key) and value: return key, 'XXX-REDACTED-XXX' return key, value def _minimize_return(path, key, value): if isinstance(key, str) and key.startswith('__pub'): return False return True def _generate_doc(ret): ''' Create a object that will be saved into the database based on options. ''' # Create a copy of the object that we will return. retc = ret.copy() # Set the ID of the document to be the JID. retc["_id"] = ret["jid"] # Add a timestamp field to the document retc["timestamp"] = time.time() return retc def _request(method, url, content_type=None, _data=None, user=None, passwd=None): ''' Makes a HTTP request. Returns the JSON parse, or an obj with an error. ''' opener = _build_opener(_HTTPHandler) request = _Request(url, data=_data) if content_type: request.add_header('Content-Type', content_type) if user and passwd: auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1] auth_basic = "Basic {0}".format(auth_encode) request.add_header('Authorization', auth_basic) request.add_header('Accept', 'application/json') request.get_method = lambda: method try: handler = opener.open(request) except HTTPError as exc: return {'error': '{0}'.format(exc)} return salt.utils.json.loads(handler.read()) def returner(ret): ''' Take in the return and shove it into the couchdb database. ''' options = _get_options(ret) # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs", user=options['user'], passwd=options['passwd']) if options['db'] not in _response: # Make a PUT request to create the database. _response = _request("PUT", options['url'] + options['db'], user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', options['db']) log.debug('_response object is: %s', _response) return log.info('Created database "%s"', options['db']) if boltons_lib: # redact all passwords if options['redact_pws'] is True if options['redact_pws']: ret_remap_pws = remap(ret, visit=_redact_passwords) else: ret_remap_pws = ret # remove all return values starting with '__pub' if options['minimum_return'] is True if options['minimum_return']: ret_remapped = remap(ret_remap_pws, visit=_minimize_return) else: ret_remapped = ret_remap_pws else: log.info('boltons library not installed. pip install boltons. https://github.com/mahmoud/boltons.') ret_remapped = ret # Call _generate_doc to get a dict object of the document we're going to shove into the database. doc = _generate_doc(ret_remapped) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + options['db'] + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def event_return(events): ''' Return event to CouchDB server Requires that configuration be enabled via 'event_return' option in master config. Example: event_return: - couchdb ''' log.debug('events data is: %s', events) options = _get_options() # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs") event_db = '{}-events'.format(options['db']) if event_db not in _response: # Make a PUT request to create the database. log.info('Creating database "%s"', event_db) _response = _request("PUT", options['url'] + event_db, user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', event_db) return log.info('Created database "%s"', event_db) for event in events: # Call _generate_doc to get a dict object of the document we're going to shove into the database. log.debug('event data is: %s', event) doc = _generate_event_doc(event) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + event_db + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def get_jid(jid): ''' Get the document with a given JID. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response} def get_jids(): ''' List all the jobs that we have.. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + "/_all_docs?include_docs=true") # Make sure the 'total_rows' is returned.. if not error out. if 'total_rows' not in _response: log.error('Didn\'t get valid response from requesting all docs: %s', _response) return {} # Return the rows. ret = {} for row in _response['rows']: # Because this shows all the documents in the database, including the # design documents, verify the id is salt jid jid = row['id'] if not salt.utils.jid.is_jid(jid): continue ret[jid] = salt.utils.jid.format_jid_instance(jid, row['doc']) return ret def get_fun(fun): ''' Return a dict with key being minion and value being the job details of the last run of function 'fun'. ''' # Get the options.. options = _get_options(ret=None) # Define a simple return object. _ret = {} # get_minions takes care of calling ensure_views for us. For each minion we know about for minion in get_minions(): # Make a query of the by-minion-and-timestamp view and limit the count to 1. _response = _request("GET", options['url'] + options['db'] + ('/_design/salt/_view/by-minion-fun-times' 'tamp?descending=true&endkey=["{0}","{1}' '",0]&startkey=["{2}","{3}",9999999999]&' 'limit=1').format(minion, fun, minion, fun)) # Skip the minion if we got an error.. if 'error' in _response: log.warning('Got an error when querying for last command ' 'by a minion: %s', _response['error']) continue # Skip the minion if we didn't get any rows back. ( IE function that # they're looking for has a typo in it or some such ). if not _response['rows']: continue # Set the respnse .. _ret[minion] = _response['rows'][0]['value'] return _ret def get_minions(): ''' Return a list of minion identifiers from a request of the view. ''' options = _get_options(ret=None) # Make sure the views are valid, which includes the minions.. if not ensure_views(): return [] # Make the request for the view.. _response = _request("GET", options['url'] + options['db'] + "/_design/salt/_view/minions?group=true") # Verify that we got a response back. if 'rows' not in _response: log.error('Unable to get available minions: %s', _response) return [] # Iterate over the rows to build up a list return it. _ret = [] for row in _response['rows']: _ret.append(row['key']) return _ret def ensure_views(): ''' This function makes sure that all the views that should exist in the design document do exist. ''' # Get the options so we have the URL and DB.. options = _get_options(ret=None) # Make a request to check if the design document exists. _response = _request("GET", options['url'] + options['db'] + "/_design/salt") # If the document doesn't exist, or for some reason there are not views. if 'error' in _response: return set_salt_view() # Determine if any views are missing from the design doc stored on the # server.. If we come across one, simply set the salt view and return out. # set_salt_view will set all the views, so we don't need to continue t # check. for view in get_valid_salt_views(): if view not in _response['views']: return set_salt_view() # Valid views, return true. return True def get_valid_salt_views(): ''' Returns a dict object of views that should be part of the salt design document. ''' ret = {} ret['minions'] = {} ret['minions']['map'] = "function( doc ){ emit( doc.id, null ); }" ret['minions']['reduce'] = \ "function( keys,values,rereduce ){ return key[0]; }" ret['by-minion-fun-timestamp'] = {} ret['by-minion-fun-timestamp']['map'] = \ "function( doc ){ emit( [doc.id,doc.fun,doc.timestamp], doc ); }" return ret def set_salt_view(): ''' Helper function that sets the salt design document. Uses get_valid_salt_views and some hardcoded values. ''' options = _get_options(ret=None) # Create the new object that we will shove in as the design doc. new_doc = {} new_doc['views'] = get_valid_salt_views() new_doc['language'] = "javascript" # Make the request to update the design doc. _response = _request("PUT", options['url'] + options['db'] + "/_design/salt", "application/json", salt.utils.json.dumps(new_doc)) if 'error' in _response: log.warning('Unable to set the salt design document: %s', _response['error']) return False return True def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def save_load(jid, load): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def get_load(jid): ''' Included for API consistency ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response}
saltstack/salt
salt/returners/couchdb_return.py
returner
python
def returner(ret): ''' Take in the return and shove it into the couchdb database. ''' options = _get_options(ret) # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs", user=options['user'], passwd=options['passwd']) if options['db'] not in _response: # Make a PUT request to create the database. _response = _request("PUT", options['url'] + options['db'], user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', options['db']) log.debug('_response object is: %s', _response) return log.info('Created database "%s"', options['db']) if boltons_lib: # redact all passwords if options['redact_pws'] is True if options['redact_pws']: ret_remap_pws = remap(ret, visit=_redact_passwords) else: ret_remap_pws = ret # remove all return values starting with '__pub' if options['minimum_return'] is True if options['minimum_return']: ret_remapped = remap(ret_remap_pws, visit=_minimize_return) else: ret_remapped = ret_remap_pws else: log.info('boltons library not installed. pip install boltons. https://github.com/mahmoud/boltons.') ret_remapped = ret # Call _generate_doc to get a dict object of the document we're going to shove into the database. doc = _generate_doc(ret_remapped) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + options['db'] + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response)
Take in the return and shove it into the couchdb database.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L215-L269
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def _get_options(ret=None):\n '''\n Get the couchdb options from salt.\n '''\n attrs = {'url': 'url',\n 'db': 'db',\n 'user': 'user',\n 'passwd': 'passwd',\n 'redact_pws': 'redact_pws',\n 'minimum_return': 'minimum_return'}\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n if 'url' not in _options:\n log.debug(\"Using default url.\")\n _options['url'] = \"http://salt:5984/\"\n\n if 'db' not in _options:\n log.debug(\"Using default database.\")\n _options['db'] = \"salt\"\n\n if 'user' not in _options:\n log.debug(\"Not athenticating with a user.\")\n _options['user'] = None\n\n if 'passwd' not in _options:\n log.debug(\"Not athenticating with a password.\")\n _options['passwd'] = None\n\n if 'redact_pws' not in _options:\n log.debug(\"Not redacting passwords.\")\n _options['redact_pws'] = None\n\n if 'minimum_return' not in _options:\n log.debug(\"Not minimizing the return object.\")\n _options['minimum_return'] = None\n\n return _options\n", "def _generate_doc(ret):\n '''\n Create a object that will be saved into the database based on\n options.\n '''\n\n # Create a copy of the object that we will return.\n retc = ret.copy()\n\n # Set the ID of the document to be the JID.\n retc[\"_id\"] = ret[\"jid\"]\n\n # Add a timestamp field to the document\n retc[\"timestamp\"] = time.time()\n\n return retc\n", "def _request(method, url, content_type=None, _data=None, user=None, passwd=None):\n '''\n Makes a HTTP request. Returns the JSON parse, or an obj with an error.\n '''\n opener = _build_opener(_HTTPHandler)\n request = _Request(url, data=_data)\n if content_type:\n request.add_header('Content-Type', content_type)\n if user and passwd:\n auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1]\n auth_basic = \"Basic {0}\".format(auth_encode)\n request.add_header('Authorization', auth_basic)\n request.add_header('Accept', 'application/json')\n request.get_method = lambda: method\n try:\n handler = opener.open(request)\n except HTTPError as exc:\n return {'error': '{0}'.format(exc)}\n return salt.utils.json.loads(handler.read())\n" ]
# -*- coding: utf-8 -*- ''' Simple returner for CouchDB. Optional configuration settings are listed below, along with sane defaults: .. code-block:: yaml couchdb.db: 'salt' couchdb.url: 'http://salt:5984/' couchdb.user: None couchdb.passwd: None couchdb.redact_pws: None couchdb.minimum_return: None Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location: .. code-block:: yaml alternative.couchdb.db: 'salt' alternative.couchdb.url: 'http://salt:5984/' To use the couchdb returner, append ``--return couchdb`` to the salt command. Example: .. code-block:: bash salt '*' test.ping --return couchdb To use the alternative configuration, append ``--return_config alternative`` to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_kwargs '{"db": "another-salt"}' On concurrent database access ============================== As this returner creates a couchdb document with the salt job id as document id and as only one document with a given id can exist in a given couchdb database, it is advised for most setups that every minion be configured to write to it own database (the value of ``couchdb.db`` may be suffixed with the minion id), otherwise multi-minion targeting can lead to losing output: * the first returning minion is able to create a document in the database * other minions fail with ``{'error': 'HTTP Error 409: Conflict'}`` ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.error import HTTPError from salt.ext.six.moves.urllib.request import ( Request as _Request, HTTPHandler as _HTTPHandler, build_opener as _build_opener, ) # pylint: enable=no-name-in-module,import-error # Import Salt libs import salt.utils.jid import salt.utils.json import salt.returners # boltons lib for redact_pws and minimum_return try: from boltons.iterutils import remap boltons_lib = True except ImportError: boltons_lib = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchdb' def __virtual__(): return __virtualname__ def _get_options(ret=None): ''' Get the couchdb options from salt. ''' attrs = {'url': 'url', 'db': 'db', 'user': 'user', 'passwd': 'passwd', 'redact_pws': 'redact_pws', 'minimum_return': 'minimum_return'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) if 'url' not in _options: log.debug("Using default url.") _options['url'] = "http://salt:5984/" if 'db' not in _options: log.debug("Using default database.") _options['db'] = "salt" if 'user' not in _options: log.debug("Not athenticating with a user.") _options['user'] = None if 'passwd' not in _options: log.debug("Not athenticating with a password.") _options['passwd'] = None if 'redact_pws' not in _options: log.debug("Not redacting passwords.") _options['redact_pws'] = None if 'minimum_return' not in _options: log.debug("Not minimizing the return object.") _options['minimum_return'] = None return _options def _redact_passwords(path, key, value): if 'password' in str(key) and value: return key, 'XXX-REDACTED-XXX' return key, value def _minimize_return(path, key, value): if isinstance(key, str) and key.startswith('__pub'): return False return True def _generate_doc(ret): ''' Create a object that will be saved into the database based on options. ''' # Create a copy of the object that we will return. retc = ret.copy() # Set the ID of the document to be the JID. retc["_id"] = ret["jid"] # Add a timestamp field to the document retc["timestamp"] = time.time() return retc def _request(method, url, content_type=None, _data=None, user=None, passwd=None): ''' Makes a HTTP request. Returns the JSON parse, or an obj with an error. ''' opener = _build_opener(_HTTPHandler) request = _Request(url, data=_data) if content_type: request.add_header('Content-Type', content_type) if user and passwd: auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1] auth_basic = "Basic {0}".format(auth_encode) request.add_header('Authorization', auth_basic) request.add_header('Accept', 'application/json') request.get_method = lambda: method try: handler = opener.open(request) except HTTPError as exc: return {'error': '{0}'.format(exc)} return salt.utils.json.loads(handler.read()) def _generate_event_doc(event): ''' Create a object that will be saved into the database based in options. ''' # Create a copy of the object that we will return. eventc = event.copy() # Set the ID of the document to be the JID. eventc["_id"] = '{}-{}'.format( event.get('tag', '').split('/')[2], event.get('tag', '').split('/')[3] ) # Add a timestamp field to the document eventc["timestamp"] = time.time() # remove any return data as it's captured in the "returner" function if eventc.get('data').get('return'): del eventc['data']['return'] return eventc def event_return(events): ''' Return event to CouchDB server Requires that configuration be enabled via 'event_return' option in master config. Example: event_return: - couchdb ''' log.debug('events data is: %s', events) options = _get_options() # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs") event_db = '{}-events'.format(options['db']) if event_db not in _response: # Make a PUT request to create the database. log.info('Creating database "%s"', event_db) _response = _request("PUT", options['url'] + event_db, user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', event_db) return log.info('Created database "%s"', event_db) for event in events: # Call _generate_doc to get a dict object of the document we're going to shove into the database. log.debug('event data is: %s', event) doc = _generate_event_doc(event) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + event_db + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def get_jid(jid): ''' Get the document with a given JID. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response} def get_jids(): ''' List all the jobs that we have.. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + "/_all_docs?include_docs=true") # Make sure the 'total_rows' is returned.. if not error out. if 'total_rows' not in _response: log.error('Didn\'t get valid response from requesting all docs: %s', _response) return {} # Return the rows. ret = {} for row in _response['rows']: # Because this shows all the documents in the database, including the # design documents, verify the id is salt jid jid = row['id'] if not salt.utils.jid.is_jid(jid): continue ret[jid] = salt.utils.jid.format_jid_instance(jid, row['doc']) return ret def get_fun(fun): ''' Return a dict with key being minion and value being the job details of the last run of function 'fun'. ''' # Get the options.. options = _get_options(ret=None) # Define a simple return object. _ret = {} # get_minions takes care of calling ensure_views for us. For each minion we know about for minion in get_minions(): # Make a query of the by-minion-and-timestamp view and limit the count to 1. _response = _request("GET", options['url'] + options['db'] + ('/_design/salt/_view/by-minion-fun-times' 'tamp?descending=true&endkey=["{0}","{1}' '",0]&startkey=["{2}","{3}",9999999999]&' 'limit=1').format(minion, fun, minion, fun)) # Skip the minion if we got an error.. if 'error' in _response: log.warning('Got an error when querying for last command ' 'by a minion: %s', _response['error']) continue # Skip the minion if we didn't get any rows back. ( IE function that # they're looking for has a typo in it or some such ). if not _response['rows']: continue # Set the respnse .. _ret[minion] = _response['rows'][0]['value'] return _ret def get_minions(): ''' Return a list of minion identifiers from a request of the view. ''' options = _get_options(ret=None) # Make sure the views are valid, which includes the minions.. if not ensure_views(): return [] # Make the request for the view.. _response = _request("GET", options['url'] + options['db'] + "/_design/salt/_view/minions?group=true") # Verify that we got a response back. if 'rows' not in _response: log.error('Unable to get available minions: %s', _response) return [] # Iterate over the rows to build up a list return it. _ret = [] for row in _response['rows']: _ret.append(row['key']) return _ret def ensure_views(): ''' This function makes sure that all the views that should exist in the design document do exist. ''' # Get the options so we have the URL and DB.. options = _get_options(ret=None) # Make a request to check if the design document exists. _response = _request("GET", options['url'] + options['db'] + "/_design/salt") # If the document doesn't exist, or for some reason there are not views. if 'error' in _response: return set_salt_view() # Determine if any views are missing from the design doc stored on the # server.. If we come across one, simply set the salt view and return out. # set_salt_view will set all the views, so we don't need to continue t # check. for view in get_valid_salt_views(): if view not in _response['views']: return set_salt_view() # Valid views, return true. return True def get_valid_salt_views(): ''' Returns a dict object of views that should be part of the salt design document. ''' ret = {} ret['minions'] = {} ret['minions']['map'] = "function( doc ){ emit( doc.id, null ); }" ret['minions']['reduce'] = \ "function( keys,values,rereduce ){ return key[0]; }" ret['by-minion-fun-timestamp'] = {} ret['by-minion-fun-timestamp']['map'] = \ "function( doc ){ emit( [doc.id,doc.fun,doc.timestamp], doc ); }" return ret def set_salt_view(): ''' Helper function that sets the salt design document. Uses get_valid_salt_views and some hardcoded values. ''' options = _get_options(ret=None) # Create the new object that we will shove in as the design doc. new_doc = {} new_doc['views'] = get_valid_salt_views() new_doc['language'] = "javascript" # Make the request to update the design doc. _response = _request("PUT", options['url'] + options['db'] + "/_design/salt", "application/json", salt.utils.json.dumps(new_doc)) if 'error' in _response: log.warning('Unable to set the salt design document: %s', _response['error']) return False return True def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def save_load(jid, load): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def get_load(jid): ''' Included for API consistency ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response}
saltstack/salt
salt/returners/couchdb_return.py
event_return
python
def event_return(events): ''' Return event to CouchDB server Requires that configuration be enabled via 'event_return' option in master config. Example: event_return: - couchdb ''' log.debug('events data is: %s', events) options = _get_options() # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs") event_db = '{}-events'.format(options['db']) if event_db not in _response: # Make a PUT request to create the database. log.info('Creating database "%s"', event_db) _response = _request("PUT", options['url'] + event_db, user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', event_db) return log.info('Created database "%s"', event_db) for event in events: # Call _generate_doc to get a dict object of the document we're going to shove into the database. log.debug('event data is: %s', event) doc = _generate_event_doc(event) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + event_db + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response)
Return event to CouchDB server Requires that configuration be enabled via 'event_return' option in master config. Example: event_return: - couchdb
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L272-L318
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def _get_options(ret=None):\n '''\n Get the couchdb options from salt.\n '''\n attrs = {'url': 'url',\n 'db': 'db',\n 'user': 'user',\n 'passwd': 'passwd',\n 'redact_pws': 'redact_pws',\n 'minimum_return': 'minimum_return'}\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n if 'url' not in _options:\n log.debug(\"Using default url.\")\n _options['url'] = \"http://salt:5984/\"\n\n if 'db' not in _options:\n log.debug(\"Using default database.\")\n _options['db'] = \"salt\"\n\n if 'user' not in _options:\n log.debug(\"Not athenticating with a user.\")\n _options['user'] = None\n\n if 'passwd' not in _options:\n log.debug(\"Not athenticating with a password.\")\n _options['passwd'] = None\n\n if 'redact_pws' not in _options:\n log.debug(\"Not redacting passwords.\")\n _options['redact_pws'] = None\n\n if 'minimum_return' not in _options:\n log.debug(\"Not minimizing the return object.\")\n _options['minimum_return'] = None\n\n return _options\n", "def _request(method, url, content_type=None, _data=None, user=None, passwd=None):\n '''\n Makes a HTTP request. Returns the JSON parse, or an obj with an error.\n '''\n opener = _build_opener(_HTTPHandler)\n request = _Request(url, data=_data)\n if content_type:\n request.add_header('Content-Type', content_type)\n if user and passwd:\n auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1]\n auth_basic = \"Basic {0}\".format(auth_encode)\n request.add_header('Authorization', auth_basic)\n request.add_header('Accept', 'application/json')\n request.get_method = lambda: method\n try:\n handler = opener.open(request)\n except HTTPError as exc:\n return {'error': '{0}'.format(exc)}\n return salt.utils.json.loads(handler.read())\n", "def _generate_event_doc(event):\n '''\n Create a object that will be saved into the database based in\n options.\n '''\n\n # Create a copy of the object that we will return.\n eventc = event.copy()\n\n # Set the ID of the document to be the JID.\n eventc[\"_id\"] = '{}-{}'.format(\n event.get('tag', '').split('/')[2],\n event.get('tag', '').split('/')[3]\n )\n\n # Add a timestamp field to the document\n eventc[\"timestamp\"] = time.time()\n\n # remove any return data as it's captured in the \"returner\" function\n if eventc.get('data').get('return'):\n del eventc['data']['return']\n\n return eventc\n" ]
# -*- coding: utf-8 -*- ''' Simple returner for CouchDB. Optional configuration settings are listed below, along with sane defaults: .. code-block:: yaml couchdb.db: 'salt' couchdb.url: 'http://salt:5984/' couchdb.user: None couchdb.passwd: None couchdb.redact_pws: None couchdb.minimum_return: None Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location: .. code-block:: yaml alternative.couchdb.db: 'salt' alternative.couchdb.url: 'http://salt:5984/' To use the couchdb returner, append ``--return couchdb`` to the salt command. Example: .. code-block:: bash salt '*' test.ping --return couchdb To use the alternative configuration, append ``--return_config alternative`` to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_kwargs '{"db": "another-salt"}' On concurrent database access ============================== As this returner creates a couchdb document with the salt job id as document id and as only one document with a given id can exist in a given couchdb database, it is advised for most setups that every minion be configured to write to it own database (the value of ``couchdb.db`` may be suffixed with the minion id), otherwise multi-minion targeting can lead to losing output: * the first returning minion is able to create a document in the database * other minions fail with ``{'error': 'HTTP Error 409: Conflict'}`` ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.error import HTTPError from salt.ext.six.moves.urllib.request import ( Request as _Request, HTTPHandler as _HTTPHandler, build_opener as _build_opener, ) # pylint: enable=no-name-in-module,import-error # Import Salt libs import salt.utils.jid import salt.utils.json import salt.returners # boltons lib for redact_pws and minimum_return try: from boltons.iterutils import remap boltons_lib = True except ImportError: boltons_lib = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchdb' def __virtual__(): return __virtualname__ def _get_options(ret=None): ''' Get the couchdb options from salt. ''' attrs = {'url': 'url', 'db': 'db', 'user': 'user', 'passwd': 'passwd', 'redact_pws': 'redact_pws', 'minimum_return': 'minimum_return'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) if 'url' not in _options: log.debug("Using default url.") _options['url'] = "http://salt:5984/" if 'db' not in _options: log.debug("Using default database.") _options['db'] = "salt" if 'user' not in _options: log.debug("Not athenticating with a user.") _options['user'] = None if 'passwd' not in _options: log.debug("Not athenticating with a password.") _options['passwd'] = None if 'redact_pws' not in _options: log.debug("Not redacting passwords.") _options['redact_pws'] = None if 'minimum_return' not in _options: log.debug("Not minimizing the return object.") _options['minimum_return'] = None return _options def _redact_passwords(path, key, value): if 'password' in str(key) and value: return key, 'XXX-REDACTED-XXX' return key, value def _minimize_return(path, key, value): if isinstance(key, str) and key.startswith('__pub'): return False return True def _generate_doc(ret): ''' Create a object that will be saved into the database based on options. ''' # Create a copy of the object that we will return. retc = ret.copy() # Set the ID of the document to be the JID. retc["_id"] = ret["jid"] # Add a timestamp field to the document retc["timestamp"] = time.time() return retc def _request(method, url, content_type=None, _data=None, user=None, passwd=None): ''' Makes a HTTP request. Returns the JSON parse, or an obj with an error. ''' opener = _build_opener(_HTTPHandler) request = _Request(url, data=_data) if content_type: request.add_header('Content-Type', content_type) if user and passwd: auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1] auth_basic = "Basic {0}".format(auth_encode) request.add_header('Authorization', auth_basic) request.add_header('Accept', 'application/json') request.get_method = lambda: method try: handler = opener.open(request) except HTTPError as exc: return {'error': '{0}'.format(exc)} return salt.utils.json.loads(handler.read()) def _generate_event_doc(event): ''' Create a object that will be saved into the database based in options. ''' # Create a copy of the object that we will return. eventc = event.copy() # Set the ID of the document to be the JID. eventc["_id"] = '{}-{}'.format( event.get('tag', '').split('/')[2], event.get('tag', '').split('/')[3] ) # Add a timestamp field to the document eventc["timestamp"] = time.time() # remove any return data as it's captured in the "returner" function if eventc.get('data').get('return'): del eventc['data']['return'] return eventc def returner(ret): ''' Take in the return and shove it into the couchdb database. ''' options = _get_options(ret) # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs", user=options['user'], passwd=options['passwd']) if options['db'] not in _response: # Make a PUT request to create the database. _response = _request("PUT", options['url'] + options['db'], user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', options['db']) log.debug('_response object is: %s', _response) return log.info('Created database "%s"', options['db']) if boltons_lib: # redact all passwords if options['redact_pws'] is True if options['redact_pws']: ret_remap_pws = remap(ret, visit=_redact_passwords) else: ret_remap_pws = ret # remove all return values starting with '__pub' if options['minimum_return'] is True if options['minimum_return']: ret_remapped = remap(ret_remap_pws, visit=_minimize_return) else: ret_remapped = ret_remap_pws else: log.info('boltons library not installed. pip install boltons. https://github.com/mahmoud/boltons.') ret_remapped = ret # Call _generate_doc to get a dict object of the document we're going to shove into the database. doc = _generate_doc(ret_remapped) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + options['db'] + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def get_jid(jid): ''' Get the document with a given JID. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response} def get_jids(): ''' List all the jobs that we have.. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + "/_all_docs?include_docs=true") # Make sure the 'total_rows' is returned.. if not error out. if 'total_rows' not in _response: log.error('Didn\'t get valid response from requesting all docs: %s', _response) return {} # Return the rows. ret = {} for row in _response['rows']: # Because this shows all the documents in the database, including the # design documents, verify the id is salt jid jid = row['id'] if not salt.utils.jid.is_jid(jid): continue ret[jid] = salt.utils.jid.format_jid_instance(jid, row['doc']) return ret def get_fun(fun): ''' Return a dict with key being minion and value being the job details of the last run of function 'fun'. ''' # Get the options.. options = _get_options(ret=None) # Define a simple return object. _ret = {} # get_minions takes care of calling ensure_views for us. For each minion we know about for minion in get_minions(): # Make a query of the by-minion-and-timestamp view and limit the count to 1. _response = _request("GET", options['url'] + options['db'] + ('/_design/salt/_view/by-minion-fun-times' 'tamp?descending=true&endkey=["{0}","{1}' '",0]&startkey=["{2}","{3}",9999999999]&' 'limit=1').format(minion, fun, minion, fun)) # Skip the minion if we got an error.. if 'error' in _response: log.warning('Got an error when querying for last command ' 'by a minion: %s', _response['error']) continue # Skip the minion if we didn't get any rows back. ( IE function that # they're looking for has a typo in it or some such ). if not _response['rows']: continue # Set the respnse .. _ret[minion] = _response['rows'][0]['value'] return _ret def get_minions(): ''' Return a list of minion identifiers from a request of the view. ''' options = _get_options(ret=None) # Make sure the views are valid, which includes the minions.. if not ensure_views(): return [] # Make the request for the view.. _response = _request("GET", options['url'] + options['db'] + "/_design/salt/_view/minions?group=true") # Verify that we got a response back. if 'rows' not in _response: log.error('Unable to get available minions: %s', _response) return [] # Iterate over the rows to build up a list return it. _ret = [] for row in _response['rows']: _ret.append(row['key']) return _ret def ensure_views(): ''' This function makes sure that all the views that should exist in the design document do exist. ''' # Get the options so we have the URL and DB.. options = _get_options(ret=None) # Make a request to check if the design document exists. _response = _request("GET", options['url'] + options['db'] + "/_design/salt") # If the document doesn't exist, or for some reason there are not views. if 'error' in _response: return set_salt_view() # Determine if any views are missing from the design doc stored on the # server.. If we come across one, simply set the salt view and return out. # set_salt_view will set all the views, so we don't need to continue t # check. for view in get_valid_salt_views(): if view not in _response['views']: return set_salt_view() # Valid views, return true. return True def get_valid_salt_views(): ''' Returns a dict object of views that should be part of the salt design document. ''' ret = {} ret['minions'] = {} ret['minions']['map'] = "function( doc ){ emit( doc.id, null ); }" ret['minions']['reduce'] = \ "function( keys,values,rereduce ){ return key[0]; }" ret['by-minion-fun-timestamp'] = {} ret['by-minion-fun-timestamp']['map'] = \ "function( doc ){ emit( [doc.id,doc.fun,doc.timestamp], doc ); }" return ret def set_salt_view(): ''' Helper function that sets the salt design document. Uses get_valid_salt_views and some hardcoded values. ''' options = _get_options(ret=None) # Create the new object that we will shove in as the design doc. new_doc = {} new_doc['views'] = get_valid_salt_views() new_doc['language'] = "javascript" # Make the request to update the design doc. _response = _request("PUT", options['url'] + options['db'] + "/_design/salt", "application/json", salt.utils.json.dumps(new_doc)) if 'error' in _response: log.warning('Unable to set the salt design document: %s', _response['error']) return False return True def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def save_load(jid, load): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def get_load(jid): ''' Included for API consistency ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response}
saltstack/salt
salt/returners/couchdb_return.py
get_jids
python
def get_jids(): ''' List all the jobs that we have.. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + "/_all_docs?include_docs=true") # Make sure the 'total_rows' is returned.. if not error out. if 'total_rows' not in _response: log.error('Didn\'t get valid response from requesting all docs: %s', _response) return {} # Return the rows. ret = {} for row in _response['rows']: # Because this shows all the documents in the database, including the # design documents, verify the id is salt jid jid = row['id'] if not salt.utils.jid.is_jid(jid): continue ret[jid] = salt.utils.jid.format_jid_instance(jid, row['doc']) return ret
List all the jobs that we have..
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L333-L356
[ "def _get_options(ret=None):\n '''\n Get the couchdb options from salt.\n '''\n attrs = {'url': 'url',\n 'db': 'db',\n 'user': 'user',\n 'passwd': 'passwd',\n 'redact_pws': 'redact_pws',\n 'minimum_return': 'minimum_return'}\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n if 'url' not in _options:\n log.debug(\"Using default url.\")\n _options['url'] = \"http://salt:5984/\"\n\n if 'db' not in _options:\n log.debug(\"Using default database.\")\n _options['db'] = \"salt\"\n\n if 'user' not in _options:\n log.debug(\"Not athenticating with a user.\")\n _options['user'] = None\n\n if 'passwd' not in _options:\n log.debug(\"Not athenticating with a password.\")\n _options['passwd'] = None\n\n if 'redact_pws' not in _options:\n log.debug(\"Not redacting passwords.\")\n _options['redact_pws'] = None\n\n if 'minimum_return' not in _options:\n log.debug(\"Not minimizing the return object.\")\n _options['minimum_return'] = None\n\n return _options\n", "def is_jid(jid):\n '''\n Returns True if the passed in value is a job id\n '''\n if not isinstance(jid, six.string_types):\n return False\n if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'):\n return False\n try:\n int(jid[:20])\n return True\n except ValueError:\n return False\n", "def _request(method, url, content_type=None, _data=None, user=None, passwd=None):\n '''\n Makes a HTTP request. Returns the JSON parse, or an obj with an error.\n '''\n opener = _build_opener(_HTTPHandler)\n request = _Request(url, data=_data)\n if content_type:\n request.add_header('Content-Type', content_type)\n if user and passwd:\n auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1]\n auth_basic = \"Basic {0}\".format(auth_encode)\n request.add_header('Authorization', auth_basic)\n request.add_header('Accept', 'application/json')\n request.get_method = lambda: method\n try:\n handler = opener.open(request)\n except HTTPError as exc:\n return {'error': '{0}'.format(exc)}\n return salt.utils.json.loads(handler.read())\n" ]
# -*- coding: utf-8 -*- ''' Simple returner for CouchDB. Optional configuration settings are listed below, along with sane defaults: .. code-block:: yaml couchdb.db: 'salt' couchdb.url: 'http://salt:5984/' couchdb.user: None couchdb.passwd: None couchdb.redact_pws: None couchdb.minimum_return: None Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location: .. code-block:: yaml alternative.couchdb.db: 'salt' alternative.couchdb.url: 'http://salt:5984/' To use the couchdb returner, append ``--return couchdb`` to the salt command. Example: .. code-block:: bash salt '*' test.ping --return couchdb To use the alternative configuration, append ``--return_config alternative`` to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_kwargs '{"db": "another-salt"}' On concurrent database access ============================== As this returner creates a couchdb document with the salt job id as document id and as only one document with a given id can exist in a given couchdb database, it is advised for most setups that every minion be configured to write to it own database (the value of ``couchdb.db`` may be suffixed with the minion id), otherwise multi-minion targeting can lead to losing output: * the first returning minion is able to create a document in the database * other minions fail with ``{'error': 'HTTP Error 409: Conflict'}`` ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.error import HTTPError from salt.ext.six.moves.urllib.request import ( Request as _Request, HTTPHandler as _HTTPHandler, build_opener as _build_opener, ) # pylint: enable=no-name-in-module,import-error # Import Salt libs import salt.utils.jid import salt.utils.json import salt.returners # boltons lib for redact_pws and minimum_return try: from boltons.iterutils import remap boltons_lib = True except ImportError: boltons_lib = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchdb' def __virtual__(): return __virtualname__ def _get_options(ret=None): ''' Get the couchdb options from salt. ''' attrs = {'url': 'url', 'db': 'db', 'user': 'user', 'passwd': 'passwd', 'redact_pws': 'redact_pws', 'minimum_return': 'minimum_return'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) if 'url' not in _options: log.debug("Using default url.") _options['url'] = "http://salt:5984/" if 'db' not in _options: log.debug("Using default database.") _options['db'] = "salt" if 'user' not in _options: log.debug("Not athenticating with a user.") _options['user'] = None if 'passwd' not in _options: log.debug("Not athenticating with a password.") _options['passwd'] = None if 'redact_pws' not in _options: log.debug("Not redacting passwords.") _options['redact_pws'] = None if 'minimum_return' not in _options: log.debug("Not minimizing the return object.") _options['minimum_return'] = None return _options def _redact_passwords(path, key, value): if 'password' in str(key) and value: return key, 'XXX-REDACTED-XXX' return key, value def _minimize_return(path, key, value): if isinstance(key, str) and key.startswith('__pub'): return False return True def _generate_doc(ret): ''' Create a object that will be saved into the database based on options. ''' # Create a copy of the object that we will return. retc = ret.copy() # Set the ID of the document to be the JID. retc["_id"] = ret["jid"] # Add a timestamp field to the document retc["timestamp"] = time.time() return retc def _request(method, url, content_type=None, _data=None, user=None, passwd=None): ''' Makes a HTTP request. Returns the JSON parse, or an obj with an error. ''' opener = _build_opener(_HTTPHandler) request = _Request(url, data=_data) if content_type: request.add_header('Content-Type', content_type) if user and passwd: auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1] auth_basic = "Basic {0}".format(auth_encode) request.add_header('Authorization', auth_basic) request.add_header('Accept', 'application/json') request.get_method = lambda: method try: handler = opener.open(request) except HTTPError as exc: return {'error': '{0}'.format(exc)} return salt.utils.json.loads(handler.read()) def _generate_event_doc(event): ''' Create a object that will be saved into the database based in options. ''' # Create a copy of the object that we will return. eventc = event.copy() # Set the ID of the document to be the JID. eventc["_id"] = '{}-{}'.format( event.get('tag', '').split('/')[2], event.get('tag', '').split('/')[3] ) # Add a timestamp field to the document eventc["timestamp"] = time.time() # remove any return data as it's captured in the "returner" function if eventc.get('data').get('return'): del eventc['data']['return'] return eventc def returner(ret): ''' Take in the return and shove it into the couchdb database. ''' options = _get_options(ret) # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs", user=options['user'], passwd=options['passwd']) if options['db'] not in _response: # Make a PUT request to create the database. _response = _request("PUT", options['url'] + options['db'], user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', options['db']) log.debug('_response object is: %s', _response) return log.info('Created database "%s"', options['db']) if boltons_lib: # redact all passwords if options['redact_pws'] is True if options['redact_pws']: ret_remap_pws = remap(ret, visit=_redact_passwords) else: ret_remap_pws = ret # remove all return values starting with '__pub' if options['minimum_return'] is True if options['minimum_return']: ret_remapped = remap(ret_remap_pws, visit=_minimize_return) else: ret_remapped = ret_remap_pws else: log.info('boltons library not installed. pip install boltons. https://github.com/mahmoud/boltons.') ret_remapped = ret # Call _generate_doc to get a dict object of the document we're going to shove into the database. doc = _generate_doc(ret_remapped) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + options['db'] + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def event_return(events): ''' Return event to CouchDB server Requires that configuration be enabled via 'event_return' option in master config. Example: event_return: - couchdb ''' log.debug('events data is: %s', events) options = _get_options() # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs") event_db = '{}-events'.format(options['db']) if event_db not in _response: # Make a PUT request to create the database. log.info('Creating database "%s"', event_db) _response = _request("PUT", options['url'] + event_db, user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', event_db) return log.info('Created database "%s"', event_db) for event in events: # Call _generate_doc to get a dict object of the document we're going to shove into the database. log.debug('event data is: %s', event) doc = _generate_event_doc(event) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + event_db + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def get_jid(jid): ''' Get the document with a given JID. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response} def get_fun(fun): ''' Return a dict with key being minion and value being the job details of the last run of function 'fun'. ''' # Get the options.. options = _get_options(ret=None) # Define a simple return object. _ret = {} # get_minions takes care of calling ensure_views for us. For each minion we know about for minion in get_minions(): # Make a query of the by-minion-and-timestamp view and limit the count to 1. _response = _request("GET", options['url'] + options['db'] + ('/_design/salt/_view/by-minion-fun-times' 'tamp?descending=true&endkey=["{0}","{1}' '",0]&startkey=["{2}","{3}",9999999999]&' 'limit=1').format(minion, fun, minion, fun)) # Skip the minion if we got an error.. if 'error' in _response: log.warning('Got an error when querying for last command ' 'by a minion: %s', _response['error']) continue # Skip the minion if we didn't get any rows back. ( IE function that # they're looking for has a typo in it or some such ). if not _response['rows']: continue # Set the respnse .. _ret[minion] = _response['rows'][0]['value'] return _ret def get_minions(): ''' Return a list of minion identifiers from a request of the view. ''' options = _get_options(ret=None) # Make sure the views are valid, which includes the minions.. if not ensure_views(): return [] # Make the request for the view.. _response = _request("GET", options['url'] + options['db'] + "/_design/salt/_view/minions?group=true") # Verify that we got a response back. if 'rows' not in _response: log.error('Unable to get available minions: %s', _response) return [] # Iterate over the rows to build up a list return it. _ret = [] for row in _response['rows']: _ret.append(row['key']) return _ret def ensure_views(): ''' This function makes sure that all the views that should exist in the design document do exist. ''' # Get the options so we have the URL and DB.. options = _get_options(ret=None) # Make a request to check if the design document exists. _response = _request("GET", options['url'] + options['db'] + "/_design/salt") # If the document doesn't exist, or for some reason there are not views. if 'error' in _response: return set_salt_view() # Determine if any views are missing from the design doc stored on the # server.. If we come across one, simply set the salt view and return out. # set_salt_view will set all the views, so we don't need to continue t # check. for view in get_valid_salt_views(): if view not in _response['views']: return set_salt_view() # Valid views, return true. return True def get_valid_salt_views(): ''' Returns a dict object of views that should be part of the salt design document. ''' ret = {} ret['minions'] = {} ret['minions']['map'] = "function( doc ){ emit( doc.id, null ); }" ret['minions']['reduce'] = \ "function( keys,values,rereduce ){ return key[0]; }" ret['by-minion-fun-timestamp'] = {} ret['by-minion-fun-timestamp']['map'] = \ "function( doc ){ emit( [doc.id,doc.fun,doc.timestamp], doc ); }" return ret def set_salt_view(): ''' Helper function that sets the salt design document. Uses get_valid_salt_views and some hardcoded values. ''' options = _get_options(ret=None) # Create the new object that we will shove in as the design doc. new_doc = {} new_doc['views'] = get_valid_salt_views() new_doc['language'] = "javascript" # Make the request to update the design doc. _response = _request("PUT", options['url'] + options['db'] + "/_design/salt", "application/json", salt.utils.json.dumps(new_doc)) if 'error' in _response: log.warning('Unable to set the salt design document: %s', _response['error']) return False return True def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def save_load(jid, load): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def get_load(jid): ''' Included for API consistency ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response}
saltstack/salt
salt/returners/couchdb_return.py
get_fun
python
def get_fun(fun): ''' Return a dict with key being minion and value being the job details of the last run of function 'fun'. ''' # Get the options.. options = _get_options(ret=None) # Define a simple return object. _ret = {} # get_minions takes care of calling ensure_views for us. For each minion we know about for minion in get_minions(): # Make a query of the by-minion-and-timestamp view and limit the count to 1. _response = _request("GET", options['url'] + options['db'] + ('/_design/salt/_view/by-minion-fun-times' 'tamp?descending=true&endkey=["{0}","{1}' '",0]&startkey=["{2}","{3}",9999999999]&' 'limit=1').format(minion, fun, minion, fun)) # Skip the minion if we got an error.. if 'error' in _response: log.warning('Got an error when querying for last command ' 'by a minion: %s', _response['error']) continue # Skip the minion if we didn't get any rows back. ( IE function that # they're looking for has a typo in it or some such ). if not _response['rows']: continue # Set the respnse .. _ret[minion] = _response['rows'][0]['value'] return _ret
Return a dict with key being minion and value being the job details of the last run of function 'fun'.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L359-L399
[ "def _get_options(ret=None):\n '''\n Get the couchdb options from salt.\n '''\n attrs = {'url': 'url',\n 'db': 'db',\n 'user': 'user',\n 'passwd': 'passwd',\n 'redact_pws': 'redact_pws',\n 'minimum_return': 'minimum_return'}\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n if 'url' not in _options:\n log.debug(\"Using default url.\")\n _options['url'] = \"http://salt:5984/\"\n\n if 'db' not in _options:\n log.debug(\"Using default database.\")\n _options['db'] = \"salt\"\n\n if 'user' not in _options:\n log.debug(\"Not athenticating with a user.\")\n _options['user'] = None\n\n if 'passwd' not in _options:\n log.debug(\"Not athenticating with a password.\")\n _options['passwd'] = None\n\n if 'redact_pws' not in _options:\n log.debug(\"Not redacting passwords.\")\n _options['redact_pws'] = None\n\n if 'minimum_return' not in _options:\n log.debug(\"Not minimizing the return object.\")\n _options['minimum_return'] = None\n\n return _options\n", "def get_minions():\n '''\n Return a list of minion identifiers from a request of the view.\n '''\n options = _get_options(ret=None)\n\n # Make sure the views are valid, which includes the minions..\n if not ensure_views():\n return []\n\n # Make the request for the view..\n _response = _request(\"GET\",\n options['url'] +\n options['db'] +\n \"/_design/salt/_view/minions?group=true\")\n\n # Verify that we got a response back.\n if 'rows' not in _response:\n log.error('Unable to get available minions: %s', _response)\n return []\n\n # Iterate over the rows to build up a list return it.\n _ret = []\n for row in _response['rows']:\n _ret.append(row['key'])\n return _ret\n", "def _request(method, url, content_type=None, _data=None, user=None, passwd=None):\n '''\n Makes a HTTP request. Returns the JSON parse, or an obj with an error.\n '''\n opener = _build_opener(_HTTPHandler)\n request = _Request(url, data=_data)\n if content_type:\n request.add_header('Content-Type', content_type)\n if user and passwd:\n auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1]\n auth_basic = \"Basic {0}\".format(auth_encode)\n request.add_header('Authorization', auth_basic)\n request.add_header('Accept', 'application/json')\n request.get_method = lambda: method\n try:\n handler = opener.open(request)\n except HTTPError as exc:\n return {'error': '{0}'.format(exc)}\n return salt.utils.json.loads(handler.read())\n" ]
# -*- coding: utf-8 -*- ''' Simple returner for CouchDB. Optional configuration settings are listed below, along with sane defaults: .. code-block:: yaml couchdb.db: 'salt' couchdb.url: 'http://salt:5984/' couchdb.user: None couchdb.passwd: None couchdb.redact_pws: None couchdb.minimum_return: None Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location: .. code-block:: yaml alternative.couchdb.db: 'salt' alternative.couchdb.url: 'http://salt:5984/' To use the couchdb returner, append ``--return couchdb`` to the salt command. Example: .. code-block:: bash salt '*' test.ping --return couchdb To use the alternative configuration, append ``--return_config alternative`` to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_kwargs '{"db": "another-salt"}' On concurrent database access ============================== As this returner creates a couchdb document with the salt job id as document id and as only one document with a given id can exist in a given couchdb database, it is advised for most setups that every minion be configured to write to it own database (the value of ``couchdb.db`` may be suffixed with the minion id), otherwise multi-minion targeting can lead to losing output: * the first returning minion is able to create a document in the database * other minions fail with ``{'error': 'HTTP Error 409: Conflict'}`` ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.error import HTTPError from salt.ext.six.moves.urllib.request import ( Request as _Request, HTTPHandler as _HTTPHandler, build_opener as _build_opener, ) # pylint: enable=no-name-in-module,import-error # Import Salt libs import salt.utils.jid import salt.utils.json import salt.returners # boltons lib for redact_pws and minimum_return try: from boltons.iterutils import remap boltons_lib = True except ImportError: boltons_lib = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchdb' def __virtual__(): return __virtualname__ def _get_options(ret=None): ''' Get the couchdb options from salt. ''' attrs = {'url': 'url', 'db': 'db', 'user': 'user', 'passwd': 'passwd', 'redact_pws': 'redact_pws', 'minimum_return': 'minimum_return'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) if 'url' not in _options: log.debug("Using default url.") _options['url'] = "http://salt:5984/" if 'db' not in _options: log.debug("Using default database.") _options['db'] = "salt" if 'user' not in _options: log.debug("Not athenticating with a user.") _options['user'] = None if 'passwd' not in _options: log.debug("Not athenticating with a password.") _options['passwd'] = None if 'redact_pws' not in _options: log.debug("Not redacting passwords.") _options['redact_pws'] = None if 'minimum_return' not in _options: log.debug("Not minimizing the return object.") _options['minimum_return'] = None return _options def _redact_passwords(path, key, value): if 'password' in str(key) and value: return key, 'XXX-REDACTED-XXX' return key, value def _minimize_return(path, key, value): if isinstance(key, str) and key.startswith('__pub'): return False return True def _generate_doc(ret): ''' Create a object that will be saved into the database based on options. ''' # Create a copy of the object that we will return. retc = ret.copy() # Set the ID of the document to be the JID. retc["_id"] = ret["jid"] # Add a timestamp field to the document retc["timestamp"] = time.time() return retc def _request(method, url, content_type=None, _data=None, user=None, passwd=None): ''' Makes a HTTP request. Returns the JSON parse, or an obj with an error. ''' opener = _build_opener(_HTTPHandler) request = _Request(url, data=_data) if content_type: request.add_header('Content-Type', content_type) if user and passwd: auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1] auth_basic = "Basic {0}".format(auth_encode) request.add_header('Authorization', auth_basic) request.add_header('Accept', 'application/json') request.get_method = lambda: method try: handler = opener.open(request) except HTTPError as exc: return {'error': '{0}'.format(exc)} return salt.utils.json.loads(handler.read()) def _generate_event_doc(event): ''' Create a object that will be saved into the database based in options. ''' # Create a copy of the object that we will return. eventc = event.copy() # Set the ID of the document to be the JID. eventc["_id"] = '{}-{}'.format( event.get('tag', '').split('/')[2], event.get('tag', '').split('/')[3] ) # Add a timestamp field to the document eventc["timestamp"] = time.time() # remove any return data as it's captured in the "returner" function if eventc.get('data').get('return'): del eventc['data']['return'] return eventc def returner(ret): ''' Take in the return and shove it into the couchdb database. ''' options = _get_options(ret) # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs", user=options['user'], passwd=options['passwd']) if options['db'] not in _response: # Make a PUT request to create the database. _response = _request("PUT", options['url'] + options['db'], user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', options['db']) log.debug('_response object is: %s', _response) return log.info('Created database "%s"', options['db']) if boltons_lib: # redact all passwords if options['redact_pws'] is True if options['redact_pws']: ret_remap_pws = remap(ret, visit=_redact_passwords) else: ret_remap_pws = ret # remove all return values starting with '__pub' if options['minimum_return'] is True if options['minimum_return']: ret_remapped = remap(ret_remap_pws, visit=_minimize_return) else: ret_remapped = ret_remap_pws else: log.info('boltons library not installed. pip install boltons. https://github.com/mahmoud/boltons.') ret_remapped = ret # Call _generate_doc to get a dict object of the document we're going to shove into the database. doc = _generate_doc(ret_remapped) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + options['db'] + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def event_return(events): ''' Return event to CouchDB server Requires that configuration be enabled via 'event_return' option in master config. Example: event_return: - couchdb ''' log.debug('events data is: %s', events) options = _get_options() # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs") event_db = '{}-events'.format(options['db']) if event_db not in _response: # Make a PUT request to create the database. log.info('Creating database "%s"', event_db) _response = _request("PUT", options['url'] + event_db, user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', event_db) return log.info('Created database "%s"', event_db) for event in events: # Call _generate_doc to get a dict object of the document we're going to shove into the database. log.debug('event data is: %s', event) doc = _generate_event_doc(event) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + event_db + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def get_jid(jid): ''' Get the document with a given JID. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response} def get_jids(): ''' List all the jobs that we have.. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + "/_all_docs?include_docs=true") # Make sure the 'total_rows' is returned.. if not error out. if 'total_rows' not in _response: log.error('Didn\'t get valid response from requesting all docs: %s', _response) return {} # Return the rows. ret = {} for row in _response['rows']: # Because this shows all the documents in the database, including the # design documents, verify the id is salt jid jid = row['id'] if not salt.utils.jid.is_jid(jid): continue ret[jid] = salt.utils.jid.format_jid_instance(jid, row['doc']) return ret def get_minions(): ''' Return a list of minion identifiers from a request of the view. ''' options = _get_options(ret=None) # Make sure the views are valid, which includes the minions.. if not ensure_views(): return [] # Make the request for the view.. _response = _request("GET", options['url'] + options['db'] + "/_design/salt/_view/minions?group=true") # Verify that we got a response back. if 'rows' not in _response: log.error('Unable to get available minions: %s', _response) return [] # Iterate over the rows to build up a list return it. _ret = [] for row in _response['rows']: _ret.append(row['key']) return _ret def ensure_views(): ''' This function makes sure that all the views that should exist in the design document do exist. ''' # Get the options so we have the URL and DB.. options = _get_options(ret=None) # Make a request to check if the design document exists. _response = _request("GET", options['url'] + options['db'] + "/_design/salt") # If the document doesn't exist, or for some reason there are not views. if 'error' in _response: return set_salt_view() # Determine if any views are missing from the design doc stored on the # server.. If we come across one, simply set the salt view and return out. # set_salt_view will set all the views, so we don't need to continue t # check. for view in get_valid_salt_views(): if view not in _response['views']: return set_salt_view() # Valid views, return true. return True def get_valid_salt_views(): ''' Returns a dict object of views that should be part of the salt design document. ''' ret = {} ret['minions'] = {} ret['minions']['map'] = "function( doc ){ emit( doc.id, null ); }" ret['minions']['reduce'] = \ "function( keys,values,rereduce ){ return key[0]; }" ret['by-minion-fun-timestamp'] = {} ret['by-minion-fun-timestamp']['map'] = \ "function( doc ){ emit( [doc.id,doc.fun,doc.timestamp], doc ); }" return ret def set_salt_view(): ''' Helper function that sets the salt design document. Uses get_valid_salt_views and some hardcoded values. ''' options = _get_options(ret=None) # Create the new object that we will shove in as the design doc. new_doc = {} new_doc['views'] = get_valid_salt_views() new_doc['language'] = "javascript" # Make the request to update the design doc. _response = _request("PUT", options['url'] + options['db'] + "/_design/salt", "application/json", salt.utils.json.dumps(new_doc)) if 'error' in _response: log.warning('Unable to set the salt design document: %s', _response['error']) return False return True def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def save_load(jid, load): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def get_load(jid): ''' Included for API consistency ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response}
saltstack/salt
salt/returners/couchdb_return.py
get_minions
python
def get_minions(): ''' Return a list of minion identifiers from a request of the view. ''' options = _get_options(ret=None) # Make sure the views are valid, which includes the minions.. if not ensure_views(): return [] # Make the request for the view.. _response = _request("GET", options['url'] + options['db'] + "/_design/salt/_view/minions?group=true") # Verify that we got a response back. if 'rows' not in _response: log.error('Unable to get available minions: %s', _response) return [] # Iterate over the rows to build up a list return it. _ret = [] for row in _response['rows']: _ret.append(row['key']) return _ret
Return a list of minion identifiers from a request of the view.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L402-L427
[ "def _get_options(ret=None):\n '''\n Get the couchdb options from salt.\n '''\n attrs = {'url': 'url',\n 'db': 'db',\n 'user': 'user',\n 'passwd': 'passwd',\n 'redact_pws': 'redact_pws',\n 'minimum_return': 'minimum_return'}\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n if 'url' not in _options:\n log.debug(\"Using default url.\")\n _options['url'] = \"http://salt:5984/\"\n\n if 'db' not in _options:\n log.debug(\"Using default database.\")\n _options['db'] = \"salt\"\n\n if 'user' not in _options:\n log.debug(\"Not athenticating with a user.\")\n _options['user'] = None\n\n if 'passwd' not in _options:\n log.debug(\"Not athenticating with a password.\")\n _options['passwd'] = None\n\n if 'redact_pws' not in _options:\n log.debug(\"Not redacting passwords.\")\n _options['redact_pws'] = None\n\n if 'minimum_return' not in _options:\n log.debug(\"Not minimizing the return object.\")\n _options['minimum_return'] = None\n\n return _options\n", "def _request(method, url, content_type=None, _data=None, user=None, passwd=None):\n '''\n Makes a HTTP request. Returns the JSON parse, or an obj with an error.\n '''\n opener = _build_opener(_HTTPHandler)\n request = _Request(url, data=_data)\n if content_type:\n request.add_header('Content-Type', content_type)\n if user and passwd:\n auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1]\n auth_basic = \"Basic {0}\".format(auth_encode)\n request.add_header('Authorization', auth_basic)\n request.add_header('Accept', 'application/json')\n request.get_method = lambda: method\n try:\n handler = opener.open(request)\n except HTTPError as exc:\n return {'error': '{0}'.format(exc)}\n return salt.utils.json.loads(handler.read())\n", "def ensure_views():\n '''\n This function makes sure that all the views that should\n exist in the design document do exist.\n '''\n\n # Get the options so we have the URL and DB..\n options = _get_options(ret=None)\n\n # Make a request to check if the design document exists.\n _response = _request(\"GET\",\n options['url'] + options['db'] + \"/_design/salt\")\n\n # If the document doesn't exist, or for some reason there are not views.\n if 'error' in _response:\n return set_salt_view()\n\n # Determine if any views are missing from the design doc stored on the\n # server.. If we come across one, simply set the salt view and return out.\n # set_salt_view will set all the views, so we don't need to continue t\n # check.\n for view in get_valid_salt_views():\n if view not in _response['views']:\n return set_salt_view()\n\n # Valid views, return true.\n return True\n" ]
# -*- coding: utf-8 -*- ''' Simple returner for CouchDB. Optional configuration settings are listed below, along with sane defaults: .. code-block:: yaml couchdb.db: 'salt' couchdb.url: 'http://salt:5984/' couchdb.user: None couchdb.passwd: None couchdb.redact_pws: None couchdb.minimum_return: None Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location: .. code-block:: yaml alternative.couchdb.db: 'salt' alternative.couchdb.url: 'http://salt:5984/' To use the couchdb returner, append ``--return couchdb`` to the salt command. Example: .. code-block:: bash salt '*' test.ping --return couchdb To use the alternative configuration, append ``--return_config alternative`` to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_kwargs '{"db": "another-salt"}' On concurrent database access ============================== As this returner creates a couchdb document with the salt job id as document id and as only one document with a given id can exist in a given couchdb database, it is advised for most setups that every minion be configured to write to it own database (the value of ``couchdb.db`` may be suffixed with the minion id), otherwise multi-minion targeting can lead to losing output: * the first returning minion is able to create a document in the database * other minions fail with ``{'error': 'HTTP Error 409: Conflict'}`` ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.error import HTTPError from salt.ext.six.moves.urllib.request import ( Request as _Request, HTTPHandler as _HTTPHandler, build_opener as _build_opener, ) # pylint: enable=no-name-in-module,import-error # Import Salt libs import salt.utils.jid import salt.utils.json import salt.returners # boltons lib for redact_pws and minimum_return try: from boltons.iterutils import remap boltons_lib = True except ImportError: boltons_lib = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchdb' def __virtual__(): return __virtualname__ def _get_options(ret=None): ''' Get the couchdb options from salt. ''' attrs = {'url': 'url', 'db': 'db', 'user': 'user', 'passwd': 'passwd', 'redact_pws': 'redact_pws', 'minimum_return': 'minimum_return'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) if 'url' not in _options: log.debug("Using default url.") _options['url'] = "http://salt:5984/" if 'db' not in _options: log.debug("Using default database.") _options['db'] = "salt" if 'user' not in _options: log.debug("Not athenticating with a user.") _options['user'] = None if 'passwd' not in _options: log.debug("Not athenticating with a password.") _options['passwd'] = None if 'redact_pws' not in _options: log.debug("Not redacting passwords.") _options['redact_pws'] = None if 'minimum_return' not in _options: log.debug("Not minimizing the return object.") _options['minimum_return'] = None return _options def _redact_passwords(path, key, value): if 'password' in str(key) and value: return key, 'XXX-REDACTED-XXX' return key, value def _minimize_return(path, key, value): if isinstance(key, str) and key.startswith('__pub'): return False return True def _generate_doc(ret): ''' Create a object that will be saved into the database based on options. ''' # Create a copy of the object that we will return. retc = ret.copy() # Set the ID of the document to be the JID. retc["_id"] = ret["jid"] # Add a timestamp field to the document retc["timestamp"] = time.time() return retc def _request(method, url, content_type=None, _data=None, user=None, passwd=None): ''' Makes a HTTP request. Returns the JSON parse, or an obj with an error. ''' opener = _build_opener(_HTTPHandler) request = _Request(url, data=_data) if content_type: request.add_header('Content-Type', content_type) if user and passwd: auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1] auth_basic = "Basic {0}".format(auth_encode) request.add_header('Authorization', auth_basic) request.add_header('Accept', 'application/json') request.get_method = lambda: method try: handler = opener.open(request) except HTTPError as exc: return {'error': '{0}'.format(exc)} return salt.utils.json.loads(handler.read()) def _generate_event_doc(event): ''' Create a object that will be saved into the database based in options. ''' # Create a copy of the object that we will return. eventc = event.copy() # Set the ID of the document to be the JID. eventc["_id"] = '{}-{}'.format( event.get('tag', '').split('/')[2], event.get('tag', '').split('/')[3] ) # Add a timestamp field to the document eventc["timestamp"] = time.time() # remove any return data as it's captured in the "returner" function if eventc.get('data').get('return'): del eventc['data']['return'] return eventc def returner(ret): ''' Take in the return and shove it into the couchdb database. ''' options = _get_options(ret) # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs", user=options['user'], passwd=options['passwd']) if options['db'] not in _response: # Make a PUT request to create the database. _response = _request("PUT", options['url'] + options['db'], user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', options['db']) log.debug('_response object is: %s', _response) return log.info('Created database "%s"', options['db']) if boltons_lib: # redact all passwords if options['redact_pws'] is True if options['redact_pws']: ret_remap_pws = remap(ret, visit=_redact_passwords) else: ret_remap_pws = ret # remove all return values starting with '__pub' if options['minimum_return'] is True if options['minimum_return']: ret_remapped = remap(ret_remap_pws, visit=_minimize_return) else: ret_remapped = ret_remap_pws else: log.info('boltons library not installed. pip install boltons. https://github.com/mahmoud/boltons.') ret_remapped = ret # Call _generate_doc to get a dict object of the document we're going to shove into the database. doc = _generate_doc(ret_remapped) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + options['db'] + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def event_return(events): ''' Return event to CouchDB server Requires that configuration be enabled via 'event_return' option in master config. Example: event_return: - couchdb ''' log.debug('events data is: %s', events) options = _get_options() # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs") event_db = '{}-events'.format(options['db']) if event_db not in _response: # Make a PUT request to create the database. log.info('Creating database "%s"', event_db) _response = _request("PUT", options['url'] + event_db, user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', event_db) return log.info('Created database "%s"', event_db) for event in events: # Call _generate_doc to get a dict object of the document we're going to shove into the database. log.debug('event data is: %s', event) doc = _generate_event_doc(event) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + event_db + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def get_jid(jid): ''' Get the document with a given JID. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response} def get_jids(): ''' List all the jobs that we have.. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + "/_all_docs?include_docs=true") # Make sure the 'total_rows' is returned.. if not error out. if 'total_rows' not in _response: log.error('Didn\'t get valid response from requesting all docs: %s', _response) return {} # Return the rows. ret = {} for row in _response['rows']: # Because this shows all the documents in the database, including the # design documents, verify the id is salt jid jid = row['id'] if not salt.utils.jid.is_jid(jid): continue ret[jid] = salt.utils.jid.format_jid_instance(jid, row['doc']) return ret def get_fun(fun): ''' Return a dict with key being minion and value being the job details of the last run of function 'fun'. ''' # Get the options.. options = _get_options(ret=None) # Define a simple return object. _ret = {} # get_minions takes care of calling ensure_views for us. For each minion we know about for minion in get_minions(): # Make a query of the by-minion-and-timestamp view and limit the count to 1. _response = _request("GET", options['url'] + options['db'] + ('/_design/salt/_view/by-minion-fun-times' 'tamp?descending=true&endkey=["{0}","{1}' '",0]&startkey=["{2}","{3}",9999999999]&' 'limit=1').format(minion, fun, minion, fun)) # Skip the minion if we got an error.. if 'error' in _response: log.warning('Got an error when querying for last command ' 'by a minion: %s', _response['error']) continue # Skip the minion if we didn't get any rows back. ( IE function that # they're looking for has a typo in it or some such ). if not _response['rows']: continue # Set the respnse .. _ret[minion] = _response['rows'][0]['value'] return _ret def ensure_views(): ''' This function makes sure that all the views that should exist in the design document do exist. ''' # Get the options so we have the URL and DB.. options = _get_options(ret=None) # Make a request to check if the design document exists. _response = _request("GET", options['url'] + options['db'] + "/_design/salt") # If the document doesn't exist, or for some reason there are not views. if 'error' in _response: return set_salt_view() # Determine if any views are missing from the design doc stored on the # server.. If we come across one, simply set the salt view and return out. # set_salt_view will set all the views, so we don't need to continue t # check. for view in get_valid_salt_views(): if view not in _response['views']: return set_salt_view() # Valid views, return true. return True def get_valid_salt_views(): ''' Returns a dict object of views that should be part of the salt design document. ''' ret = {} ret['minions'] = {} ret['minions']['map'] = "function( doc ){ emit( doc.id, null ); }" ret['minions']['reduce'] = \ "function( keys,values,rereduce ){ return key[0]; }" ret['by-minion-fun-timestamp'] = {} ret['by-minion-fun-timestamp']['map'] = \ "function( doc ){ emit( [doc.id,doc.fun,doc.timestamp], doc ); }" return ret def set_salt_view(): ''' Helper function that sets the salt design document. Uses get_valid_salt_views and some hardcoded values. ''' options = _get_options(ret=None) # Create the new object that we will shove in as the design doc. new_doc = {} new_doc['views'] = get_valid_salt_views() new_doc['language'] = "javascript" # Make the request to update the design doc. _response = _request("PUT", options['url'] + options['db'] + "/_design/salt", "application/json", salt.utils.json.dumps(new_doc)) if 'error' in _response: log.warning('Unable to set the salt design document: %s', _response['error']) return False return True def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def save_load(jid, load): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def get_load(jid): ''' Included for API consistency ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response}
saltstack/salt
salt/returners/couchdb_return.py
ensure_views
python
def ensure_views(): ''' This function makes sure that all the views that should exist in the design document do exist. ''' # Get the options so we have the URL and DB.. options = _get_options(ret=None) # Make a request to check if the design document exists. _response = _request("GET", options['url'] + options['db'] + "/_design/salt") # If the document doesn't exist, or for some reason there are not views. if 'error' in _response: return set_salt_view() # Determine if any views are missing from the design doc stored on the # server.. If we come across one, simply set the salt view and return out. # set_salt_view will set all the views, so we don't need to continue t # check. for view in get_valid_salt_views(): if view not in _response['views']: return set_salt_view() # Valid views, return true. return True
This function makes sure that all the views that should exist in the design document do exist.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L430-L456
[ "def _get_options(ret=None):\n '''\n Get the couchdb options from salt.\n '''\n attrs = {'url': 'url',\n 'db': 'db',\n 'user': 'user',\n 'passwd': 'passwd',\n 'redact_pws': 'redact_pws',\n 'minimum_return': 'minimum_return'}\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n if 'url' not in _options:\n log.debug(\"Using default url.\")\n _options['url'] = \"http://salt:5984/\"\n\n if 'db' not in _options:\n log.debug(\"Using default database.\")\n _options['db'] = \"salt\"\n\n if 'user' not in _options:\n log.debug(\"Not athenticating with a user.\")\n _options['user'] = None\n\n if 'passwd' not in _options:\n log.debug(\"Not athenticating with a password.\")\n _options['passwd'] = None\n\n if 'redact_pws' not in _options:\n log.debug(\"Not redacting passwords.\")\n _options['redact_pws'] = None\n\n if 'minimum_return' not in _options:\n log.debug(\"Not minimizing the return object.\")\n _options['minimum_return'] = None\n\n return _options\n", "def _request(method, url, content_type=None, _data=None, user=None, passwd=None):\n '''\n Makes a HTTP request. Returns the JSON parse, or an obj with an error.\n '''\n opener = _build_opener(_HTTPHandler)\n request = _Request(url, data=_data)\n if content_type:\n request.add_header('Content-Type', content_type)\n if user and passwd:\n auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1]\n auth_basic = \"Basic {0}\".format(auth_encode)\n request.add_header('Authorization', auth_basic)\n request.add_header('Accept', 'application/json')\n request.get_method = lambda: method\n try:\n handler = opener.open(request)\n except HTTPError as exc:\n return {'error': '{0}'.format(exc)}\n return salt.utils.json.loads(handler.read())\n", "def set_salt_view():\n '''\n Helper function that sets the salt design\n document. Uses get_valid_salt_views and some hardcoded values.\n '''\n\n options = _get_options(ret=None)\n\n # Create the new object that we will shove in as the design doc.\n new_doc = {}\n new_doc['views'] = get_valid_salt_views()\n new_doc['language'] = \"javascript\"\n\n # Make the request to update the design doc.\n _response = _request(\"PUT\",\n options['url'] + options['db'] + \"/_design/salt\",\n \"application/json\", salt.utils.json.dumps(new_doc))\n if 'error' in _response:\n log.warning('Unable to set the salt design document: %s', _response['error'])\n return False\n return True\n", "def get_valid_salt_views():\n '''\n Returns a dict object of views that should be\n part of the salt design document.\n '''\n ret = {}\n\n ret['minions'] = {}\n ret['minions']['map'] = \"function( doc ){ emit( doc.id, null ); }\"\n ret['minions']['reduce'] = \\\n \"function( keys,values,rereduce ){ return key[0]; }\"\n\n ret['by-minion-fun-timestamp'] = {}\n ret['by-minion-fun-timestamp']['map'] = \\\n \"function( doc ){ emit( [doc.id,doc.fun,doc.timestamp], doc ); }\"\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Simple returner for CouchDB. Optional configuration settings are listed below, along with sane defaults: .. code-block:: yaml couchdb.db: 'salt' couchdb.url: 'http://salt:5984/' couchdb.user: None couchdb.passwd: None couchdb.redact_pws: None couchdb.minimum_return: None Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location: .. code-block:: yaml alternative.couchdb.db: 'salt' alternative.couchdb.url: 'http://salt:5984/' To use the couchdb returner, append ``--return couchdb`` to the salt command. Example: .. code-block:: bash salt '*' test.ping --return couchdb To use the alternative configuration, append ``--return_config alternative`` to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_kwargs '{"db": "another-salt"}' On concurrent database access ============================== As this returner creates a couchdb document with the salt job id as document id and as only one document with a given id can exist in a given couchdb database, it is advised for most setups that every minion be configured to write to it own database (the value of ``couchdb.db`` may be suffixed with the minion id), otherwise multi-minion targeting can lead to losing output: * the first returning minion is able to create a document in the database * other minions fail with ``{'error': 'HTTP Error 409: Conflict'}`` ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.error import HTTPError from salt.ext.six.moves.urllib.request import ( Request as _Request, HTTPHandler as _HTTPHandler, build_opener as _build_opener, ) # pylint: enable=no-name-in-module,import-error # Import Salt libs import salt.utils.jid import salt.utils.json import salt.returners # boltons lib for redact_pws and minimum_return try: from boltons.iterutils import remap boltons_lib = True except ImportError: boltons_lib = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchdb' def __virtual__(): return __virtualname__ def _get_options(ret=None): ''' Get the couchdb options from salt. ''' attrs = {'url': 'url', 'db': 'db', 'user': 'user', 'passwd': 'passwd', 'redact_pws': 'redact_pws', 'minimum_return': 'minimum_return'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) if 'url' not in _options: log.debug("Using default url.") _options['url'] = "http://salt:5984/" if 'db' not in _options: log.debug("Using default database.") _options['db'] = "salt" if 'user' not in _options: log.debug("Not athenticating with a user.") _options['user'] = None if 'passwd' not in _options: log.debug("Not athenticating with a password.") _options['passwd'] = None if 'redact_pws' not in _options: log.debug("Not redacting passwords.") _options['redact_pws'] = None if 'minimum_return' not in _options: log.debug("Not minimizing the return object.") _options['minimum_return'] = None return _options def _redact_passwords(path, key, value): if 'password' in str(key) and value: return key, 'XXX-REDACTED-XXX' return key, value def _minimize_return(path, key, value): if isinstance(key, str) and key.startswith('__pub'): return False return True def _generate_doc(ret): ''' Create a object that will be saved into the database based on options. ''' # Create a copy of the object that we will return. retc = ret.copy() # Set the ID of the document to be the JID. retc["_id"] = ret["jid"] # Add a timestamp field to the document retc["timestamp"] = time.time() return retc def _request(method, url, content_type=None, _data=None, user=None, passwd=None): ''' Makes a HTTP request. Returns the JSON parse, or an obj with an error. ''' opener = _build_opener(_HTTPHandler) request = _Request(url, data=_data) if content_type: request.add_header('Content-Type', content_type) if user and passwd: auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1] auth_basic = "Basic {0}".format(auth_encode) request.add_header('Authorization', auth_basic) request.add_header('Accept', 'application/json') request.get_method = lambda: method try: handler = opener.open(request) except HTTPError as exc: return {'error': '{0}'.format(exc)} return salt.utils.json.loads(handler.read()) def _generate_event_doc(event): ''' Create a object that will be saved into the database based in options. ''' # Create a copy of the object that we will return. eventc = event.copy() # Set the ID of the document to be the JID. eventc["_id"] = '{}-{}'.format( event.get('tag', '').split('/')[2], event.get('tag', '').split('/')[3] ) # Add a timestamp field to the document eventc["timestamp"] = time.time() # remove any return data as it's captured in the "returner" function if eventc.get('data').get('return'): del eventc['data']['return'] return eventc def returner(ret): ''' Take in the return and shove it into the couchdb database. ''' options = _get_options(ret) # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs", user=options['user'], passwd=options['passwd']) if options['db'] not in _response: # Make a PUT request to create the database. _response = _request("PUT", options['url'] + options['db'], user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', options['db']) log.debug('_response object is: %s', _response) return log.info('Created database "%s"', options['db']) if boltons_lib: # redact all passwords if options['redact_pws'] is True if options['redact_pws']: ret_remap_pws = remap(ret, visit=_redact_passwords) else: ret_remap_pws = ret # remove all return values starting with '__pub' if options['minimum_return'] is True if options['minimum_return']: ret_remapped = remap(ret_remap_pws, visit=_minimize_return) else: ret_remapped = ret_remap_pws else: log.info('boltons library not installed. pip install boltons. https://github.com/mahmoud/boltons.') ret_remapped = ret # Call _generate_doc to get a dict object of the document we're going to shove into the database. doc = _generate_doc(ret_remapped) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + options['db'] + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def event_return(events): ''' Return event to CouchDB server Requires that configuration be enabled via 'event_return' option in master config. Example: event_return: - couchdb ''' log.debug('events data is: %s', events) options = _get_options() # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs") event_db = '{}-events'.format(options['db']) if event_db not in _response: # Make a PUT request to create the database. log.info('Creating database "%s"', event_db) _response = _request("PUT", options['url'] + event_db, user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', event_db) return log.info('Created database "%s"', event_db) for event in events: # Call _generate_doc to get a dict object of the document we're going to shove into the database. log.debug('event data is: %s', event) doc = _generate_event_doc(event) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + event_db + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def get_jid(jid): ''' Get the document with a given JID. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response} def get_jids(): ''' List all the jobs that we have.. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + "/_all_docs?include_docs=true") # Make sure the 'total_rows' is returned.. if not error out. if 'total_rows' not in _response: log.error('Didn\'t get valid response from requesting all docs: %s', _response) return {} # Return the rows. ret = {} for row in _response['rows']: # Because this shows all the documents in the database, including the # design documents, verify the id is salt jid jid = row['id'] if not salt.utils.jid.is_jid(jid): continue ret[jid] = salt.utils.jid.format_jid_instance(jid, row['doc']) return ret def get_fun(fun): ''' Return a dict with key being minion and value being the job details of the last run of function 'fun'. ''' # Get the options.. options = _get_options(ret=None) # Define a simple return object. _ret = {} # get_minions takes care of calling ensure_views for us. For each minion we know about for minion in get_minions(): # Make a query of the by-minion-and-timestamp view and limit the count to 1. _response = _request("GET", options['url'] + options['db'] + ('/_design/salt/_view/by-minion-fun-times' 'tamp?descending=true&endkey=["{0}","{1}' '",0]&startkey=["{2}","{3}",9999999999]&' 'limit=1').format(minion, fun, minion, fun)) # Skip the minion if we got an error.. if 'error' in _response: log.warning('Got an error when querying for last command ' 'by a minion: %s', _response['error']) continue # Skip the minion if we didn't get any rows back. ( IE function that # they're looking for has a typo in it or some such ). if not _response['rows']: continue # Set the respnse .. _ret[minion] = _response['rows'][0]['value'] return _ret def get_minions(): ''' Return a list of minion identifiers from a request of the view. ''' options = _get_options(ret=None) # Make sure the views are valid, which includes the minions.. if not ensure_views(): return [] # Make the request for the view.. _response = _request("GET", options['url'] + options['db'] + "/_design/salt/_view/minions?group=true") # Verify that we got a response back. if 'rows' not in _response: log.error('Unable to get available minions: %s', _response) return [] # Iterate over the rows to build up a list return it. _ret = [] for row in _response['rows']: _ret.append(row['key']) return _ret def get_valid_salt_views(): ''' Returns a dict object of views that should be part of the salt design document. ''' ret = {} ret['minions'] = {} ret['minions']['map'] = "function( doc ){ emit( doc.id, null ); }" ret['minions']['reduce'] = \ "function( keys,values,rereduce ){ return key[0]; }" ret['by-minion-fun-timestamp'] = {} ret['by-minion-fun-timestamp']['map'] = \ "function( doc ){ emit( [doc.id,doc.fun,doc.timestamp], doc ); }" return ret def set_salt_view(): ''' Helper function that sets the salt design document. Uses get_valid_salt_views and some hardcoded values. ''' options = _get_options(ret=None) # Create the new object that we will shove in as the design doc. new_doc = {} new_doc['views'] = get_valid_salt_views() new_doc['language'] = "javascript" # Make the request to update the design doc. _response = _request("PUT", options['url'] + options['db'] + "/_design/salt", "application/json", salt.utils.json.dumps(new_doc)) if 'error' in _response: log.warning('Unable to set the salt design document: %s', _response['error']) return False return True def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def save_load(jid, load): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def get_load(jid): ''' Included for API consistency ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response}
saltstack/salt
salt/returners/couchdb_return.py
set_salt_view
python
def set_salt_view(): ''' Helper function that sets the salt design document. Uses get_valid_salt_views and some hardcoded values. ''' options = _get_options(ret=None) # Create the new object that we will shove in as the design doc. new_doc = {} new_doc['views'] = get_valid_salt_views() new_doc['language'] = "javascript" # Make the request to update the design doc. _response = _request("PUT", options['url'] + options['db'] + "/_design/salt", "application/json", salt.utils.json.dumps(new_doc)) if 'error' in _response: log.warning('Unable to set the salt design document: %s', _response['error']) return False return True
Helper function that sets the salt design document. Uses get_valid_salt_views and some hardcoded values.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L477-L497
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def _get_options(ret=None):\n '''\n Get the couchdb options from salt.\n '''\n attrs = {'url': 'url',\n 'db': 'db',\n 'user': 'user',\n 'passwd': 'passwd',\n 'redact_pws': 'redact_pws',\n 'minimum_return': 'minimum_return'}\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n if 'url' not in _options:\n log.debug(\"Using default url.\")\n _options['url'] = \"http://salt:5984/\"\n\n if 'db' not in _options:\n log.debug(\"Using default database.\")\n _options['db'] = \"salt\"\n\n if 'user' not in _options:\n log.debug(\"Not athenticating with a user.\")\n _options['user'] = None\n\n if 'passwd' not in _options:\n log.debug(\"Not athenticating with a password.\")\n _options['passwd'] = None\n\n if 'redact_pws' not in _options:\n log.debug(\"Not redacting passwords.\")\n _options['redact_pws'] = None\n\n if 'minimum_return' not in _options:\n log.debug(\"Not minimizing the return object.\")\n _options['minimum_return'] = None\n\n return _options\n", "def _request(method, url, content_type=None, _data=None, user=None, passwd=None):\n '''\n Makes a HTTP request. Returns the JSON parse, or an obj with an error.\n '''\n opener = _build_opener(_HTTPHandler)\n request = _Request(url, data=_data)\n if content_type:\n request.add_header('Content-Type', content_type)\n if user and passwd:\n auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1]\n auth_basic = \"Basic {0}\".format(auth_encode)\n request.add_header('Authorization', auth_basic)\n request.add_header('Accept', 'application/json')\n request.get_method = lambda: method\n try:\n handler = opener.open(request)\n except HTTPError as exc:\n return {'error': '{0}'.format(exc)}\n return salt.utils.json.loads(handler.read())\n", "def get_valid_salt_views():\n '''\n Returns a dict object of views that should be\n part of the salt design document.\n '''\n ret = {}\n\n ret['minions'] = {}\n ret['minions']['map'] = \"function( doc ){ emit( doc.id, null ); }\"\n ret['minions']['reduce'] = \\\n \"function( keys,values,rereduce ){ return key[0]; }\"\n\n ret['by-minion-fun-timestamp'] = {}\n ret['by-minion-fun-timestamp']['map'] = \\\n \"function( doc ){ emit( [doc.id,doc.fun,doc.timestamp], doc ); }\"\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Simple returner for CouchDB. Optional configuration settings are listed below, along with sane defaults: .. code-block:: yaml couchdb.db: 'salt' couchdb.url: 'http://salt:5984/' couchdb.user: None couchdb.passwd: None couchdb.redact_pws: None couchdb.minimum_return: None Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location: .. code-block:: yaml alternative.couchdb.db: 'salt' alternative.couchdb.url: 'http://salt:5984/' To use the couchdb returner, append ``--return couchdb`` to the salt command. Example: .. code-block:: bash salt '*' test.ping --return couchdb To use the alternative configuration, append ``--return_config alternative`` to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_kwargs '{"db": "another-salt"}' On concurrent database access ============================== As this returner creates a couchdb document with the salt job id as document id and as only one document with a given id can exist in a given couchdb database, it is advised for most setups that every minion be configured to write to it own database (the value of ``couchdb.db`` may be suffixed with the minion id), otherwise multi-minion targeting can lead to losing output: * the first returning minion is able to create a document in the database * other minions fail with ``{'error': 'HTTP Error 409: Conflict'}`` ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.error import HTTPError from salt.ext.six.moves.urllib.request import ( Request as _Request, HTTPHandler as _HTTPHandler, build_opener as _build_opener, ) # pylint: enable=no-name-in-module,import-error # Import Salt libs import salt.utils.jid import salt.utils.json import salt.returners # boltons lib for redact_pws and minimum_return try: from boltons.iterutils import remap boltons_lib = True except ImportError: boltons_lib = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchdb' def __virtual__(): return __virtualname__ def _get_options(ret=None): ''' Get the couchdb options from salt. ''' attrs = {'url': 'url', 'db': 'db', 'user': 'user', 'passwd': 'passwd', 'redact_pws': 'redact_pws', 'minimum_return': 'minimum_return'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) if 'url' not in _options: log.debug("Using default url.") _options['url'] = "http://salt:5984/" if 'db' not in _options: log.debug("Using default database.") _options['db'] = "salt" if 'user' not in _options: log.debug("Not athenticating with a user.") _options['user'] = None if 'passwd' not in _options: log.debug("Not athenticating with a password.") _options['passwd'] = None if 'redact_pws' not in _options: log.debug("Not redacting passwords.") _options['redact_pws'] = None if 'minimum_return' not in _options: log.debug("Not minimizing the return object.") _options['minimum_return'] = None return _options def _redact_passwords(path, key, value): if 'password' in str(key) and value: return key, 'XXX-REDACTED-XXX' return key, value def _minimize_return(path, key, value): if isinstance(key, str) and key.startswith('__pub'): return False return True def _generate_doc(ret): ''' Create a object that will be saved into the database based on options. ''' # Create a copy of the object that we will return. retc = ret.copy() # Set the ID of the document to be the JID. retc["_id"] = ret["jid"] # Add a timestamp field to the document retc["timestamp"] = time.time() return retc def _request(method, url, content_type=None, _data=None, user=None, passwd=None): ''' Makes a HTTP request. Returns the JSON parse, or an obj with an error. ''' opener = _build_opener(_HTTPHandler) request = _Request(url, data=_data) if content_type: request.add_header('Content-Type', content_type) if user and passwd: auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1] auth_basic = "Basic {0}".format(auth_encode) request.add_header('Authorization', auth_basic) request.add_header('Accept', 'application/json') request.get_method = lambda: method try: handler = opener.open(request) except HTTPError as exc: return {'error': '{0}'.format(exc)} return salt.utils.json.loads(handler.read()) def _generate_event_doc(event): ''' Create a object that will be saved into the database based in options. ''' # Create a copy of the object that we will return. eventc = event.copy() # Set the ID of the document to be the JID. eventc["_id"] = '{}-{}'.format( event.get('tag', '').split('/')[2], event.get('tag', '').split('/')[3] ) # Add a timestamp field to the document eventc["timestamp"] = time.time() # remove any return data as it's captured in the "returner" function if eventc.get('data').get('return'): del eventc['data']['return'] return eventc def returner(ret): ''' Take in the return and shove it into the couchdb database. ''' options = _get_options(ret) # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs", user=options['user'], passwd=options['passwd']) if options['db'] not in _response: # Make a PUT request to create the database. _response = _request("PUT", options['url'] + options['db'], user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', options['db']) log.debug('_response object is: %s', _response) return log.info('Created database "%s"', options['db']) if boltons_lib: # redact all passwords if options['redact_pws'] is True if options['redact_pws']: ret_remap_pws = remap(ret, visit=_redact_passwords) else: ret_remap_pws = ret # remove all return values starting with '__pub' if options['minimum_return'] is True if options['minimum_return']: ret_remapped = remap(ret_remap_pws, visit=_minimize_return) else: ret_remapped = ret_remap_pws else: log.info('boltons library not installed. pip install boltons. https://github.com/mahmoud/boltons.') ret_remapped = ret # Call _generate_doc to get a dict object of the document we're going to shove into the database. doc = _generate_doc(ret_remapped) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + options['db'] + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def event_return(events): ''' Return event to CouchDB server Requires that configuration be enabled via 'event_return' option in master config. Example: event_return: - couchdb ''' log.debug('events data is: %s', events) options = _get_options() # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs") event_db = '{}-events'.format(options['db']) if event_db not in _response: # Make a PUT request to create the database. log.info('Creating database "%s"', event_db) _response = _request("PUT", options['url'] + event_db, user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', event_db) return log.info('Created database "%s"', event_db) for event in events: # Call _generate_doc to get a dict object of the document we're going to shove into the database. log.debug('event data is: %s', event) doc = _generate_event_doc(event) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + event_db + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def get_jid(jid): ''' Get the document with a given JID. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response} def get_jids(): ''' List all the jobs that we have.. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + "/_all_docs?include_docs=true") # Make sure the 'total_rows' is returned.. if not error out. if 'total_rows' not in _response: log.error('Didn\'t get valid response from requesting all docs: %s', _response) return {} # Return the rows. ret = {} for row in _response['rows']: # Because this shows all the documents in the database, including the # design documents, verify the id is salt jid jid = row['id'] if not salt.utils.jid.is_jid(jid): continue ret[jid] = salt.utils.jid.format_jid_instance(jid, row['doc']) return ret def get_fun(fun): ''' Return a dict with key being minion and value being the job details of the last run of function 'fun'. ''' # Get the options.. options = _get_options(ret=None) # Define a simple return object. _ret = {} # get_minions takes care of calling ensure_views for us. For each minion we know about for minion in get_minions(): # Make a query of the by-minion-and-timestamp view and limit the count to 1. _response = _request("GET", options['url'] + options['db'] + ('/_design/salt/_view/by-minion-fun-times' 'tamp?descending=true&endkey=["{0}","{1}' '",0]&startkey=["{2}","{3}",9999999999]&' 'limit=1').format(minion, fun, minion, fun)) # Skip the minion if we got an error.. if 'error' in _response: log.warning('Got an error when querying for last command ' 'by a minion: %s', _response['error']) continue # Skip the minion if we didn't get any rows back. ( IE function that # they're looking for has a typo in it or some such ). if not _response['rows']: continue # Set the respnse .. _ret[minion] = _response['rows'][0]['value'] return _ret def get_minions(): ''' Return a list of minion identifiers from a request of the view. ''' options = _get_options(ret=None) # Make sure the views are valid, which includes the minions.. if not ensure_views(): return [] # Make the request for the view.. _response = _request("GET", options['url'] + options['db'] + "/_design/salt/_view/minions?group=true") # Verify that we got a response back. if 'rows' not in _response: log.error('Unable to get available minions: %s', _response) return [] # Iterate over the rows to build up a list return it. _ret = [] for row in _response['rows']: _ret.append(row['key']) return _ret def ensure_views(): ''' This function makes sure that all the views that should exist in the design document do exist. ''' # Get the options so we have the URL and DB.. options = _get_options(ret=None) # Make a request to check if the design document exists. _response = _request("GET", options['url'] + options['db'] + "/_design/salt") # If the document doesn't exist, or for some reason there are not views. if 'error' in _response: return set_salt_view() # Determine if any views are missing from the design doc stored on the # server.. If we come across one, simply set the salt view and return out. # set_salt_view will set all the views, so we don't need to continue t # check. for view in get_valid_salt_views(): if view not in _response['views']: return set_salt_view() # Valid views, return true. return True def get_valid_salt_views(): ''' Returns a dict object of views that should be part of the salt design document. ''' ret = {} ret['minions'] = {} ret['minions']['map'] = "function( doc ){ emit( doc.id, null ); }" ret['minions']['reduce'] = \ "function( keys,values,rereduce ){ return key[0]; }" ret['by-minion-fun-timestamp'] = {} ret['by-minion-fun-timestamp']['map'] = \ "function( doc ){ emit( [doc.id,doc.fun,doc.timestamp], doc ); }" return ret def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def save_load(jid, load): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def get_load(jid): ''' Included for API consistency ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response}
saltstack/salt
salt/returners/couchdb_return.py
get_load
python
def get_load(jid): ''' Included for API consistency ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response}
Included for API consistency
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L521-L530
[ "def _get_options(ret=None):\n '''\n Get the couchdb options from salt.\n '''\n attrs = {'url': 'url',\n 'db': 'db',\n 'user': 'user',\n 'passwd': 'passwd',\n 'redact_pws': 'redact_pws',\n 'minimum_return': 'minimum_return'}\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n if 'url' not in _options:\n log.debug(\"Using default url.\")\n _options['url'] = \"http://salt:5984/\"\n\n if 'db' not in _options:\n log.debug(\"Using default database.\")\n _options['db'] = \"salt\"\n\n if 'user' not in _options:\n log.debug(\"Not athenticating with a user.\")\n _options['user'] = None\n\n if 'passwd' not in _options:\n log.debug(\"Not athenticating with a password.\")\n _options['passwd'] = None\n\n if 'redact_pws' not in _options:\n log.debug(\"Not redacting passwords.\")\n _options['redact_pws'] = None\n\n if 'minimum_return' not in _options:\n log.debug(\"Not minimizing the return object.\")\n _options['minimum_return'] = None\n\n return _options\n", "def _request(method, url, content_type=None, _data=None, user=None, passwd=None):\n '''\n Makes a HTTP request. Returns the JSON parse, or an obj with an error.\n '''\n opener = _build_opener(_HTTPHandler)\n request = _Request(url, data=_data)\n if content_type:\n request.add_header('Content-Type', content_type)\n if user and passwd:\n auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1]\n auth_basic = \"Basic {0}\".format(auth_encode)\n request.add_header('Authorization', auth_basic)\n request.add_header('Accept', 'application/json')\n request.get_method = lambda: method\n try:\n handler = opener.open(request)\n except HTTPError as exc:\n return {'error': '{0}'.format(exc)}\n return salt.utils.json.loads(handler.read())\n" ]
# -*- coding: utf-8 -*- ''' Simple returner for CouchDB. Optional configuration settings are listed below, along with sane defaults: .. code-block:: yaml couchdb.db: 'salt' couchdb.url: 'http://salt:5984/' couchdb.user: None couchdb.passwd: None couchdb.redact_pws: None couchdb.minimum_return: None Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location: .. code-block:: yaml alternative.couchdb.db: 'salt' alternative.couchdb.url: 'http://salt:5984/' To use the couchdb returner, append ``--return couchdb`` to the salt command. Example: .. code-block:: bash salt '*' test.ping --return couchdb To use the alternative configuration, append ``--return_config alternative`` to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return couchdb --return_kwargs '{"db": "another-salt"}' On concurrent database access ============================== As this returner creates a couchdb document with the salt job id as document id and as only one document with a given id can exist in a given couchdb database, it is advised for most setups that every minion be configured to write to it own database (the value of ``couchdb.db`` may be suffixed with the minion id), otherwise multi-minion targeting can lead to losing output: * the first returning minion is able to create a document in the database * other minions fail with ``{'error': 'HTTP Error 409: Conflict'}`` ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import 3rd-party libs # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.error import HTTPError from salt.ext.six.moves.urllib.request import ( Request as _Request, HTTPHandler as _HTTPHandler, build_opener as _build_opener, ) # pylint: enable=no-name-in-module,import-error # Import Salt libs import salt.utils.jid import salt.utils.json import salt.returners # boltons lib for redact_pws and minimum_return try: from boltons.iterutils import remap boltons_lib = True except ImportError: boltons_lib = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'couchdb' def __virtual__(): return __virtualname__ def _get_options(ret=None): ''' Get the couchdb options from salt. ''' attrs = {'url': 'url', 'db': 'db', 'user': 'user', 'passwd': 'passwd', 'redact_pws': 'redact_pws', 'minimum_return': 'minimum_return'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) if 'url' not in _options: log.debug("Using default url.") _options['url'] = "http://salt:5984/" if 'db' not in _options: log.debug("Using default database.") _options['db'] = "salt" if 'user' not in _options: log.debug("Not athenticating with a user.") _options['user'] = None if 'passwd' not in _options: log.debug("Not athenticating with a password.") _options['passwd'] = None if 'redact_pws' not in _options: log.debug("Not redacting passwords.") _options['redact_pws'] = None if 'minimum_return' not in _options: log.debug("Not minimizing the return object.") _options['minimum_return'] = None return _options def _redact_passwords(path, key, value): if 'password' in str(key) and value: return key, 'XXX-REDACTED-XXX' return key, value def _minimize_return(path, key, value): if isinstance(key, str) and key.startswith('__pub'): return False return True def _generate_doc(ret): ''' Create a object that will be saved into the database based on options. ''' # Create a copy of the object that we will return. retc = ret.copy() # Set the ID of the document to be the JID. retc["_id"] = ret["jid"] # Add a timestamp field to the document retc["timestamp"] = time.time() return retc def _request(method, url, content_type=None, _data=None, user=None, passwd=None): ''' Makes a HTTP request. Returns the JSON parse, or an obj with an error. ''' opener = _build_opener(_HTTPHandler) request = _Request(url, data=_data) if content_type: request.add_header('Content-Type', content_type) if user and passwd: auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1] auth_basic = "Basic {0}".format(auth_encode) request.add_header('Authorization', auth_basic) request.add_header('Accept', 'application/json') request.get_method = lambda: method try: handler = opener.open(request) except HTTPError as exc: return {'error': '{0}'.format(exc)} return salt.utils.json.loads(handler.read()) def _generate_event_doc(event): ''' Create a object that will be saved into the database based in options. ''' # Create a copy of the object that we will return. eventc = event.copy() # Set the ID of the document to be the JID. eventc["_id"] = '{}-{}'.format( event.get('tag', '').split('/')[2], event.get('tag', '').split('/')[3] ) # Add a timestamp field to the document eventc["timestamp"] = time.time() # remove any return data as it's captured in the "returner" function if eventc.get('data').get('return'): del eventc['data']['return'] return eventc def returner(ret): ''' Take in the return and shove it into the couchdb database. ''' options = _get_options(ret) # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs", user=options['user'], passwd=options['passwd']) if options['db'] not in _response: # Make a PUT request to create the database. _response = _request("PUT", options['url'] + options['db'], user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', options['db']) log.debug('_response object is: %s', _response) return log.info('Created database "%s"', options['db']) if boltons_lib: # redact all passwords if options['redact_pws'] is True if options['redact_pws']: ret_remap_pws = remap(ret, visit=_redact_passwords) else: ret_remap_pws = ret # remove all return values starting with '__pub' if options['minimum_return'] is True if options['minimum_return']: ret_remapped = remap(ret_remap_pws, visit=_minimize_return) else: ret_remapped = ret_remap_pws else: log.info('boltons library not installed. pip install boltons. https://github.com/mahmoud/boltons.') ret_remapped = ret # Call _generate_doc to get a dict object of the document we're going to shove into the database. doc = _generate_doc(ret_remapped) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + options['db'] + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def event_return(events): ''' Return event to CouchDB server Requires that configuration be enabled via 'event_return' option in master config. Example: event_return: - couchdb ''' log.debug('events data is: %s', events) options = _get_options() # Check to see if the database exists. _response = _request("GET", options['url'] + "_all_dbs") event_db = '{}-events'.format(options['db']) if event_db not in _response: # Make a PUT request to create the database. log.info('Creating database "%s"', event_db) _response = _request("PUT", options['url'] + event_db, user=options['user'], passwd=options['passwd']) # Confirm that the response back was simple 'ok': true. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create database "%s"', event_db) return log.info('Created database "%s"', event_db) for event in events: # Call _generate_doc to get a dict object of the document we're going to shove into the database. log.debug('event data is: %s', event) doc = _generate_event_doc(event) # Make the actual HTTP PUT request to create the doc. _response = _request("PUT", options['url'] + event_db + "/" + doc['_id'], 'application/json', salt.utils.json.dumps(doc)) # Sanity check regarding the response.. if 'ok' not in _response or _response['ok'] is not True: log.error('Nothing logged! Lost data. Unable to create document: "%s"', _response) def get_jid(jid): ''' Get the document with a given JID. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + '/' + jid) if 'error' in _response: log.error('Unable to get JID "%s" : "%s"', jid, _response) return {} return {_response['id']: _response} def get_jids(): ''' List all the jobs that we have.. ''' options = _get_options(ret=None) _response = _request("GET", options['url'] + options['db'] + "/_all_docs?include_docs=true") # Make sure the 'total_rows' is returned.. if not error out. if 'total_rows' not in _response: log.error('Didn\'t get valid response from requesting all docs: %s', _response) return {} # Return the rows. ret = {} for row in _response['rows']: # Because this shows all the documents in the database, including the # design documents, verify the id is salt jid jid = row['id'] if not salt.utils.jid.is_jid(jid): continue ret[jid] = salt.utils.jid.format_jid_instance(jid, row['doc']) return ret def get_fun(fun): ''' Return a dict with key being minion and value being the job details of the last run of function 'fun'. ''' # Get the options.. options = _get_options(ret=None) # Define a simple return object. _ret = {} # get_minions takes care of calling ensure_views for us. For each minion we know about for minion in get_minions(): # Make a query of the by-minion-and-timestamp view and limit the count to 1. _response = _request("GET", options['url'] + options['db'] + ('/_design/salt/_view/by-minion-fun-times' 'tamp?descending=true&endkey=["{0}","{1}' '",0]&startkey=["{2}","{3}",9999999999]&' 'limit=1').format(minion, fun, minion, fun)) # Skip the minion if we got an error.. if 'error' in _response: log.warning('Got an error when querying for last command ' 'by a minion: %s', _response['error']) continue # Skip the minion if we didn't get any rows back. ( IE function that # they're looking for has a typo in it or some such ). if not _response['rows']: continue # Set the respnse .. _ret[minion] = _response['rows'][0]['value'] return _ret def get_minions(): ''' Return a list of minion identifiers from a request of the view. ''' options = _get_options(ret=None) # Make sure the views are valid, which includes the minions.. if not ensure_views(): return [] # Make the request for the view.. _response = _request("GET", options['url'] + options['db'] + "/_design/salt/_view/minions?group=true") # Verify that we got a response back. if 'rows' not in _response: log.error('Unable to get available minions: %s', _response) return [] # Iterate over the rows to build up a list return it. _ret = [] for row in _response['rows']: _ret.append(row['key']) return _ret def ensure_views(): ''' This function makes sure that all the views that should exist in the design document do exist. ''' # Get the options so we have the URL and DB.. options = _get_options(ret=None) # Make a request to check if the design document exists. _response = _request("GET", options['url'] + options['db'] + "/_design/salt") # If the document doesn't exist, or for some reason there are not views. if 'error' in _response: return set_salt_view() # Determine if any views are missing from the design doc stored on the # server.. If we come across one, simply set the salt view and return out. # set_salt_view will set all the views, so we don't need to continue t # check. for view in get_valid_salt_views(): if view not in _response['views']: return set_salt_view() # Valid views, return true. return True def get_valid_salt_views(): ''' Returns a dict object of views that should be part of the salt design document. ''' ret = {} ret['minions'] = {} ret['minions']['map'] = "function( doc ){ emit( doc.id, null ); }" ret['minions']['reduce'] = \ "function( keys,values,rereduce ){ return key[0]; }" ret['by-minion-fun-timestamp'] = {} ret['by-minion-fun-timestamp']['map'] = \ "function( doc ){ emit( [doc.id,doc.fun,doc.timestamp], doc ); }" return ret def set_salt_view(): ''' Helper function that sets the salt design document. Uses get_valid_salt_views and some hardcoded values. ''' options = _get_options(ret=None) # Create the new object that we will shove in as the design doc. new_doc = {} new_doc['views'] = get_valid_salt_views() new_doc['language'] = "javascript" # Make the request to update the design doc. _response = _request("PUT", options['url'] + options['db'] + "/_design/salt", "application/json", salt.utils.json.dumps(new_doc)) if 'error' in _response: log.warning('Unable to set the salt design document: %s', _response['error']) return False return True def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass def save_load(jid, load): # pylint: disable=unused-argument ''' Included for API consistency ''' pass
saltstack/salt
salt/modules/heat.py
_auth
python
def _auth(profile=None, api_version=1, **connection_args): ''' Set up heat credentials, returns `heatclient.client.Client`. Optional parameter "api_version" defaults to 1. Only intended to be used within heat-enabled modules ''' if profile: prefix = profile + ':keystone.' else: prefix = 'keystone.' def get(key, default=None): ''' Checks connection_args, then salt-minion config, falls back to specified default value. ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', None) tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0') insecure = get('insecure', False) admin_token = get('token') region_name = get('region_name', None) if admin_token and api_version != 1 and not password: # If we had a password we could just # ignore the admin-token and move on... raise SaltInvocationError('Only can use keystone admin token ' + 'with Heat API v1') elif password: # Can't use the admin-token anyway kwargs = {'username': user, 'password': password, 'tenant_id': tenant_id, 'auth_url': auth_url, 'region_name': region_name, 'tenant_name': tenant} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True elif api_version == 1 and admin_token: kwargs = {'token': admin_token, 'auth_url': auth_url} else: raise SaltInvocationError('No credentials to authenticate with.') token = __salt__['keystone.token_get'](profile) kwargs['token'] = token['id'] # This doesn't realy prevent the password to show up # in the minion log as keystoneclient.session is # logging it anyway when in debug-mode kwargs.pop('password') try: heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['url'] except KeyError: heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['publicurl'] heat_endpoint = heat_endpoint % token log.debug('Calling heatclient.client.Client(%s, %s, **%s)', api_version, heat_endpoint, kwargs) # may raise exc.HTTPUnauthorized, exc.HTTPNotFound # but we deal with those elsewhere return heatclient.client.Client(api_version, endpoint=heat_endpoint, **kwargs)
Set up heat credentials, returns `heatclient.client.Client`. Optional parameter "api_version" defaults to 1. Only intended to be used within heat-enabled modules
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/heat.py#L102-L171
[ "def get(key, default=None):\n '''\n Checks connection_args, then salt-minion config,\n falls back to specified default value.\n '''\n return connection_args.get('connection_' + key,\n __salt__['config.get'](prefix + key, default))\n" ]
# -*- coding: utf-8 -*- ''' Module for handling OpenStack Heat calls .. versionadded:: 2017.7.0 :depends: - heatclient Python module :configuration: This module is not usable until the user, password, tenant, and auth URL are specified either in a pillar or in the minion's config file. For example:: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.insecure: False #(optional) keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' # Optional keystone.region_name: 'RegionOne' If configuration for multiple OpenStack accounts is required, they can be set up as different configuration profiles: For example:: openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the heat functions can make use of a configuration profile by declaring it explicitly. For example:: salt '*' heat.flavor_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time import logging # Import Salt libs from salt.exceptions import SaltInvocationError from salt.ext import six import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml # pylint: disable=import-error HAS_HEAT = False try: import heatclient HAS_HEAT = True except ImportError: pass HAS_OSLO = False try: from oslo_serialization import jsonutils HAS_OSLO = True except ImportError: pass SECTIONS = ( PARAMETER_DEFAULTS, PARAMETERS, RESOURCE_REGISTRY, EVENT_SINKS) = ( 'parameter_defaults', 'parameters', 'resource_registry', 'event_sinks') logging.basicConfig(level=logging.DEBUG) log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if heat is installed on this minion. ''' if HAS_HEAT and HAS_OSLO: return 'heat' return (False, 'The heat execution module cannot be loaded: ' 'the heatclient and oslo_serialization' # 'the heatclient and keystoneclient and oslo_serialization' ' python library is not available.') __opts__ = {} def _parse_template(tmpl_str): ''' Parsing template ''' tmpl_str = tmpl_str.strip() if tmpl_str.startswith('{'): tpl = salt.utils.json.loads(tmpl_str) else: try: tpl = salt.utils.yaml.safe_load(tmpl_str) except salt.utils.yaml.YAMLError as exc: raise ValueError(six.text_type(exc)) else: if tpl is None: tpl = {} if not ('HeatTemplateFormatVersion' in tpl or 'heat_template_version' in tpl or 'AWSTemplateFormatVersion' in tpl): raise ValueError(('Template format version not found.')) return tpl def _parse_environment(env_str): ''' Parsing template ''' try: env = salt.utils.yaml.safe_load(env_str) except salt.utils.yaml.YAMLError as exc: raise ValueError(six.text_type(exc)) else: if env is None: env = {} elif not isinstance(env, dict): raise ValueError( 'The environment is not a valid YAML mapping data type.' ) for param in env: if param not in SECTIONS: raise ValueError('environment has wrong section "{0}"'.format(param)) return env def _get_stack_events(h_client, stack_id, event_args): ''' Get event for stack ''' event_args['stack_id'] = stack_id event_args['resource_name'] = None try: events = h_client.events.list(**event_args) except heatclient.exc.HTTPNotFound as exc: raise heatclient.exc.CommandError(six.text_type(exc)) else: for event in events: event.stack_name = stack_id.split('/')[0] return events def _poll_for_events(h_client, stack_name, action=None, poll_period=5, timeout=60, marker=None): ''' Polling stack events ''' if action: stop_status = ('{0}_FAILED'.format(action), '{0}_COMPLETE'.format(action)) stop_check = lambda a: a in stop_status else: stop_check = lambda a: a.endswith('_COMPLETE') or a.endswith('_FAILED') timeout_sec = timeout * 60 no_event_polls = 0 msg_template = ('\n Stack %(name)s %(status)s \n') while True: events = _get_stack_events(h_client, stack_id=stack_name, event_args={'sort_dir': 'asc', 'marker': marker}) if not events: no_event_polls += 1 else: no_event_polls = 0 # set marker to last event that was received. marker = getattr(events[-1], 'id', None) for event in events: # check if stack event was also received if getattr(event, 'resource_name', '') == stack_name: stack_status = getattr(event, 'resource_status', '') msg = msg_template % dict( name=stack_name, status=stack_status) if stop_check(stack_status): return stack_status, msg if no_event_polls >= 2: # after 2 polls with no events, fall back to a stack get stack = h_client.stacks.get(stack_name) stack_status = stack.stack_status msg = msg_template % dict( name=stack_name, status=stack_status) if stop_check(stack_status): return stack_status, msg # go back to event polling again no_event_polls = 0 time.sleep(poll_period) timeout_sec -= poll_period if timeout_sec <= 0: stack_status = '{0}_FAILED'.format(action) msg = 'Timeout expired' return stack_status, msg def list_stack(profile=None): ''' Return a list of available stack (heat stack-list) profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.list_stack profile=openstack1 ''' ret = {} h_client = _auth(profile) for stack in h_client.stacks.list(): links = {} for link in stack.links: links[link['rel']] = link['href'] ret[stack.stack_name] = { 'status': stack.stack_status, 'id': stack.id, 'name': stack.stack_name, 'creation': stack.creation_time, 'owner': stack.stack_owner, 'reason': stack.stack_status_reason, 'links': links, } return ret def show_stack(name=None, profile=None): ''' Return details about a specific stack (heat stack-show) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.show_stack name=mystack profile=openstack1 ''' h_client = _auth(profile) if not name: return { 'result': False, 'comment': 'Parameter name missing or None' } try: ret = {} stack = h_client.stacks.get(name) links = {} for link in stack.links: links[link['rel']] = link['href'] ret[stack.stack_name] = { 'status': stack.stack_status, 'id': stack.id, 'name': stack.stack_name, 'creation': stack.creation_time, 'owner': stack.stack_owner, 'reason': stack.stack_status_reason, 'parameters': stack.parameters, 'links': links, } ret['result'] = True except heatclient.exc.HTTPNotFound: return { 'result': False, 'comment': 'No stack {0}'.format(name) } return ret def delete_stack(name=None, poll=0, timeout=60, profile=None): ''' Delete a stack (heat stack-delete) name Name of the stack poll Poll and report events until stack complete timeout Stack creation timeout in minute profile Profile to use CLI Examples: .. code-block:: bash salt '*' heat.delete_stack name=mystack poll=5 \\ profile=openstack1 ''' h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not name: ret['result'] = False ret['comment'] = 'Parameter name missing or None' return ret try: h_client.stacks.delete(name) except heatclient.exc.HTTPNotFound: ret['result'] = False ret['comment'] = 'No stack {0}'.format(name) except heatclient.exc.HTTPForbidden as forbidden: log.exception(forbidden) ret['result'] = False ret['comment'] = six.text_type(forbidden) if ret['result'] is False: return ret if poll > 0: try: stack_status, msg = _poll_for_events(h_client, name, action='DELETE', poll_period=poll, timeout=timeout) except heatclient.exc.CommandError: ret['comment'] = 'Deleted stack {0}.'.format(name) return ret except Exception as ex: # pylint: disable=W0703 log.exception('Delete failed %s', ex) ret['result'] = False ret['comment'] = '{0}'.format(ex) return ret if stack_status == 'DELETE_FAILED': ret['result'] = False ret['comment'] = 'Deleted stack FAILED\'{0}\'{1}.'.format(name, msg) else: ret['comment'] = 'Deleted stack {0}.'.format(name) return ret def create_stack(name=None, template_file=None, environment=None, parameters=None, poll=0, rollback=False, timeout=60, profile=None, enviroment=None): ''' Create a stack (heat stack-create) name Name of the new stack template_file File of template environment File of environment parameters Parameter dict used to create the stack poll Poll and report events until stack complete rollback Enable rollback on create failure timeout Stack creation timeout in minutes profile Profile to build on CLI Example: .. code-block:: bash salt '*' heat.create_stack name=mystack \\ template_file=salt://template.yaml \\ environment=salt://environment.yaml \\ parameters="{"image": "Debian 8", "flavor": "m1.small"}" \\ poll=5 rollback=False timeout=60 profile=openstack1 .. versionadded:: 2017.7.5,2018.3.1 The spelling mistake in parameter `enviroment` was corrected to `environment`. The misspelled version is still supported for backward compatibility, but will be removed in Salt Neon. ''' if environment is None and enviroment is not None: salt.utils.versions.warn_until('Neon', ( "Please use the 'environment' parameter instead of the misspelled 'enviroment' " "parameter which will be removed in Salt Neon." )) environment = enviroment h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not parameters: parameters = {} if template_file: template_tmp_file = salt.utils.files.mkstemp() tsfn, source_sum, comment_ = __salt__['file.get_managed']( name=template_tmp_file, template=None, source=template_file, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) template_manage_result = __salt__['file.manage_file']( name=template_tmp_file, sfn=tsfn, ret=None, source=template_file, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if template_manage_result['result']: with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_: tpl = salt.utils.stringutils.to_unicode(tfp_.read()) salt.utils.files.safe_rm(template_tmp_file) try: template = _parse_template(tpl) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open template: {0} {1}'.format(template_file, comment_) else: ret['result'] = False ret['comment'] = 'Can not open template' if ret['result'] is False: return ret kwargs = {} kwargs['template'] = template try: h_client.stacks.validate(**kwargs) except Exception as ex: log.exception('Template not valid') ret['result'] = False ret['comment'] = 'Template not valid: {0}'.format(ex) return ret env = {} if environment: environment_tmp_file = salt.utils.files.mkstemp() esfn, source_sum, comment_ = __salt__['file.get_managed']( name=environment_tmp_file, template=None, source=environment, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) environment_manage_result = __salt__['file.manage_file']( name=environment_tmp_file, sfn=esfn, ret=None, source=environment, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if environment_manage_result['result']: with salt.utils.files.fopen(environment_tmp_file, 'r') as efp_: env_str = salt.utils.stringutils.to_unicode(efp_.read()) salt.utils.files.safe_rm(environment_tmp_file) try: env = _parse_environment(env_str) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open environment: {0}, {1}'.format(environment, comment_) if ret['result'] is False: return ret fields = { 'stack_name': name, 'disable_rollback': not rollback, 'parameters': parameters, 'template': template, 'environment': env, 'timeout_mins': timeout } # If one or more environments is found, pass the listing to the server try: h_client.stacks.create(**fields) except Exception as ex: # pylint: disable=W0703 log.exception('Create failed') ret['result'] = False ret['comment'] = six.text_type(ex) return ret if poll > 0: stack_status, msg = _poll_for_events(h_client, name, action='CREATE', poll_period=poll, timeout=timeout) if stack_status == 'CREATE_FAILED': ret['result'] = False ret['comment'] = 'Created stack FAILED\'{0}\'{1}.'.format(name, msg) if ret['result'] is True: ret['comment'] = 'Created stack \'{0}\'.'.format(name) return ret def update_stack(name=None, template_file=None, environment=None, parameters=None, poll=0, rollback=False, timeout=60, profile=None, enviroment=None): ''' Update a stack (heat stack-template) name Name of the stack template_file File of template environment File of environment parameters Parameter dict used to update the stack poll Poll and report events until stack complete rollback Enable rollback on update failure timeout Stack creation timeout in minutes profile Profile to build on CLI Example: .. code-block:: bash salt '*' heat.update_stack name=mystack \\ template_file=salt://template.yaml \\ environment=salt://environment.yaml \\ parameters="{"image": "Debian 8", "flavor": "m1.small"}" \\ poll=5 rollback=False timeout=60 profile=openstack1 .. versionadded:: 2017.7.5,2018.3.1 The spelling mistake in parameter `enviroment` was corrected to `environment`. The misspelled version is still supported for backward compatibility, but will be removed in Salt Neon. ''' if environment is None and enviroment is not None: salt.utils.versions.warn_until('Neon', ( "Please use the 'environment' parameter instead of the misspelled 'enviroment' " "parameter which will be removed in Salt Neon." )) environment = enviroment h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not name: ret['result'] = False ret['comment'] = 'Parameter name missing or None' return ret if not parameters: parameters = {} if template_file: template_tmp_file = salt.utils.files.mkstemp() tsfn, source_sum, comment_ = __salt__['file.get_managed']( name=template_tmp_file, template=None, source=template_file, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) template_manage_result = __salt__['file.manage_file']( name=template_tmp_file, sfn=tsfn, ret=None, source=template_file, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if template_manage_result['result']: with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_: tpl = salt.utils.stringutils.to_unicode(tfp_.read()) salt.utils.files.safe_rm(template_tmp_file) try: template = _parse_template(tpl) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open template: {0} {1}'.format(template_file, comment_) else: ret['result'] = False ret['comment'] = 'Can not open template' if ret['result'] is False: return ret kwargs = {} kwargs['template'] = template try: h_client.stacks.validate(**kwargs) except Exception as ex: # pylint: disable=W0703 log.exception('Template not valid') ret['result'] = False ret['comment'] = 'Template not valid {0}'.format(ex) return ret env = {} if environment: environment_tmp_file = salt.utils.files.mkstemp() esfn, source_sum, comment_ = __salt__['file.get_managed']( name=environment_tmp_file, template=None, source=environment, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) environment_manage_result = __salt__['file.manage_file']( name=environment_tmp_file, sfn=esfn, ret=None, source=environment, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if environment_manage_result['result']: with salt.utils.files.fopen(environment_tmp_file, 'r') as efp_: env_str = salt.utils.stringutils.to_unicode(efp_.read()) salt.utils.files.safe_rm(environment_tmp_file) try: env = _parse_environment(env_str) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open environment: {0}, {1}'.format(environment, comment_) if ret['result'] is False: return ret fields = { 'disable_rollback': not rollback, 'parameters': parameters, 'template': template, 'environment': env, 'timeout_mins': timeout } try: h_client.stacks.update(name, **fields) except Exception as ex: # pylint: disable=W0703 log.exception('Update failed') ret['result'] = False ret['comment'] = 'Update failed {0}'.format(ex) return ret if poll > 0: stack_status, msg = _poll_for_events(h_client, name, action='UPDATE', poll_period=poll, timeout=timeout) if stack_status == 'UPDATE_FAILED': ret['result'] = False ret['comment'] = 'Updated stack FAILED\'{0}\'{1}.'.format(name, msg) if ret['result'] is True: ret['comment'] = 'Updated stack \'{0}\'.'.format(name), return ret def template_stack(name=None, profile=None): ''' Return template a specific stack (heat stack-template) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.template_stack name=mystack profile=openstack1 ''' h_client = _auth(profile) if not name: return { 'result': False, 'comment': 'Parameter name missing or None' } try: get_template = h_client.stacks.template(name) except heatclient.exc.HTTPNotFound: return { 'result': False, 'comment': 'No stack with {0}'.format(name) } except heatclient.exc.BadRequest: return { 'result': False, 'comment': 'Bad request fot stack {0}'.format(name) } if 'heat_template_version' in get_template: template = salt.utils.yaml.safe_dump(get_template) else: template = jsonutils.dumps(get_template, indent=2, ensure_ascii=False) checksum = __salt__['hashutil.digest'](template) ret = { 'template': template, 'result': True, 'checksum': checksum } return ret
saltstack/salt
salt/modules/heat.py
_parse_environment
python
def _parse_environment(env_str): ''' Parsing template ''' try: env = salt.utils.yaml.safe_load(env_str) except salt.utils.yaml.YAMLError as exc: raise ValueError(six.text_type(exc)) else: if env is None: env = {} elif not isinstance(env, dict): raise ValueError( 'The environment is not a valid YAML mapping data type.' ) for param in env: if param not in SECTIONS: raise ValueError('environment has wrong section "{0}"'.format(param)) return env
Parsing template
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/heat.py#L196-L216
[ "def safe_load(stream, Loader=SaltYamlSafeLoader):\n '''\n .. versionadded:: 2018.3.0\n\n Helper function which automagically uses our custom loader.\n '''\n return yaml.load(stream, Loader=Loader)\n" ]
# -*- coding: utf-8 -*- ''' Module for handling OpenStack Heat calls .. versionadded:: 2017.7.0 :depends: - heatclient Python module :configuration: This module is not usable until the user, password, tenant, and auth URL are specified either in a pillar or in the minion's config file. For example:: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.insecure: False #(optional) keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' # Optional keystone.region_name: 'RegionOne' If configuration for multiple OpenStack accounts is required, they can be set up as different configuration profiles: For example:: openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the heat functions can make use of a configuration profile by declaring it explicitly. For example:: salt '*' heat.flavor_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time import logging # Import Salt libs from salt.exceptions import SaltInvocationError from salt.ext import six import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml # pylint: disable=import-error HAS_HEAT = False try: import heatclient HAS_HEAT = True except ImportError: pass HAS_OSLO = False try: from oslo_serialization import jsonutils HAS_OSLO = True except ImportError: pass SECTIONS = ( PARAMETER_DEFAULTS, PARAMETERS, RESOURCE_REGISTRY, EVENT_SINKS) = ( 'parameter_defaults', 'parameters', 'resource_registry', 'event_sinks') logging.basicConfig(level=logging.DEBUG) log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if heat is installed on this minion. ''' if HAS_HEAT and HAS_OSLO: return 'heat' return (False, 'The heat execution module cannot be loaded: ' 'the heatclient and oslo_serialization' # 'the heatclient and keystoneclient and oslo_serialization' ' python library is not available.') __opts__ = {} def _auth(profile=None, api_version=1, **connection_args): ''' Set up heat credentials, returns `heatclient.client.Client`. Optional parameter "api_version" defaults to 1. Only intended to be used within heat-enabled modules ''' if profile: prefix = profile + ':keystone.' else: prefix = 'keystone.' def get(key, default=None): ''' Checks connection_args, then salt-minion config, falls back to specified default value. ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', None) tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0') insecure = get('insecure', False) admin_token = get('token') region_name = get('region_name', None) if admin_token and api_version != 1 and not password: # If we had a password we could just # ignore the admin-token and move on... raise SaltInvocationError('Only can use keystone admin token ' + 'with Heat API v1') elif password: # Can't use the admin-token anyway kwargs = {'username': user, 'password': password, 'tenant_id': tenant_id, 'auth_url': auth_url, 'region_name': region_name, 'tenant_name': tenant} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True elif api_version == 1 and admin_token: kwargs = {'token': admin_token, 'auth_url': auth_url} else: raise SaltInvocationError('No credentials to authenticate with.') token = __salt__['keystone.token_get'](profile) kwargs['token'] = token['id'] # This doesn't realy prevent the password to show up # in the minion log as keystoneclient.session is # logging it anyway when in debug-mode kwargs.pop('password') try: heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['url'] except KeyError: heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['publicurl'] heat_endpoint = heat_endpoint % token log.debug('Calling heatclient.client.Client(%s, %s, **%s)', api_version, heat_endpoint, kwargs) # may raise exc.HTTPUnauthorized, exc.HTTPNotFound # but we deal with those elsewhere return heatclient.client.Client(api_version, endpoint=heat_endpoint, **kwargs) def _parse_template(tmpl_str): ''' Parsing template ''' tmpl_str = tmpl_str.strip() if tmpl_str.startswith('{'): tpl = salt.utils.json.loads(tmpl_str) else: try: tpl = salt.utils.yaml.safe_load(tmpl_str) except salt.utils.yaml.YAMLError as exc: raise ValueError(six.text_type(exc)) else: if tpl is None: tpl = {} if not ('HeatTemplateFormatVersion' in tpl or 'heat_template_version' in tpl or 'AWSTemplateFormatVersion' in tpl): raise ValueError(('Template format version not found.')) return tpl def _get_stack_events(h_client, stack_id, event_args): ''' Get event for stack ''' event_args['stack_id'] = stack_id event_args['resource_name'] = None try: events = h_client.events.list(**event_args) except heatclient.exc.HTTPNotFound as exc: raise heatclient.exc.CommandError(six.text_type(exc)) else: for event in events: event.stack_name = stack_id.split('/')[0] return events def _poll_for_events(h_client, stack_name, action=None, poll_period=5, timeout=60, marker=None): ''' Polling stack events ''' if action: stop_status = ('{0}_FAILED'.format(action), '{0}_COMPLETE'.format(action)) stop_check = lambda a: a in stop_status else: stop_check = lambda a: a.endswith('_COMPLETE') or a.endswith('_FAILED') timeout_sec = timeout * 60 no_event_polls = 0 msg_template = ('\n Stack %(name)s %(status)s \n') while True: events = _get_stack_events(h_client, stack_id=stack_name, event_args={'sort_dir': 'asc', 'marker': marker}) if not events: no_event_polls += 1 else: no_event_polls = 0 # set marker to last event that was received. marker = getattr(events[-1], 'id', None) for event in events: # check if stack event was also received if getattr(event, 'resource_name', '') == stack_name: stack_status = getattr(event, 'resource_status', '') msg = msg_template % dict( name=stack_name, status=stack_status) if stop_check(stack_status): return stack_status, msg if no_event_polls >= 2: # after 2 polls with no events, fall back to a stack get stack = h_client.stacks.get(stack_name) stack_status = stack.stack_status msg = msg_template % dict( name=stack_name, status=stack_status) if stop_check(stack_status): return stack_status, msg # go back to event polling again no_event_polls = 0 time.sleep(poll_period) timeout_sec -= poll_period if timeout_sec <= 0: stack_status = '{0}_FAILED'.format(action) msg = 'Timeout expired' return stack_status, msg def list_stack(profile=None): ''' Return a list of available stack (heat stack-list) profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.list_stack profile=openstack1 ''' ret = {} h_client = _auth(profile) for stack in h_client.stacks.list(): links = {} for link in stack.links: links[link['rel']] = link['href'] ret[stack.stack_name] = { 'status': stack.stack_status, 'id': stack.id, 'name': stack.stack_name, 'creation': stack.creation_time, 'owner': stack.stack_owner, 'reason': stack.stack_status_reason, 'links': links, } return ret def show_stack(name=None, profile=None): ''' Return details about a specific stack (heat stack-show) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.show_stack name=mystack profile=openstack1 ''' h_client = _auth(profile) if not name: return { 'result': False, 'comment': 'Parameter name missing or None' } try: ret = {} stack = h_client.stacks.get(name) links = {} for link in stack.links: links[link['rel']] = link['href'] ret[stack.stack_name] = { 'status': stack.stack_status, 'id': stack.id, 'name': stack.stack_name, 'creation': stack.creation_time, 'owner': stack.stack_owner, 'reason': stack.stack_status_reason, 'parameters': stack.parameters, 'links': links, } ret['result'] = True except heatclient.exc.HTTPNotFound: return { 'result': False, 'comment': 'No stack {0}'.format(name) } return ret def delete_stack(name=None, poll=0, timeout=60, profile=None): ''' Delete a stack (heat stack-delete) name Name of the stack poll Poll and report events until stack complete timeout Stack creation timeout in minute profile Profile to use CLI Examples: .. code-block:: bash salt '*' heat.delete_stack name=mystack poll=5 \\ profile=openstack1 ''' h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not name: ret['result'] = False ret['comment'] = 'Parameter name missing or None' return ret try: h_client.stacks.delete(name) except heatclient.exc.HTTPNotFound: ret['result'] = False ret['comment'] = 'No stack {0}'.format(name) except heatclient.exc.HTTPForbidden as forbidden: log.exception(forbidden) ret['result'] = False ret['comment'] = six.text_type(forbidden) if ret['result'] is False: return ret if poll > 0: try: stack_status, msg = _poll_for_events(h_client, name, action='DELETE', poll_period=poll, timeout=timeout) except heatclient.exc.CommandError: ret['comment'] = 'Deleted stack {0}.'.format(name) return ret except Exception as ex: # pylint: disable=W0703 log.exception('Delete failed %s', ex) ret['result'] = False ret['comment'] = '{0}'.format(ex) return ret if stack_status == 'DELETE_FAILED': ret['result'] = False ret['comment'] = 'Deleted stack FAILED\'{0}\'{1}.'.format(name, msg) else: ret['comment'] = 'Deleted stack {0}.'.format(name) return ret def create_stack(name=None, template_file=None, environment=None, parameters=None, poll=0, rollback=False, timeout=60, profile=None, enviroment=None): ''' Create a stack (heat stack-create) name Name of the new stack template_file File of template environment File of environment parameters Parameter dict used to create the stack poll Poll and report events until stack complete rollback Enable rollback on create failure timeout Stack creation timeout in minutes profile Profile to build on CLI Example: .. code-block:: bash salt '*' heat.create_stack name=mystack \\ template_file=salt://template.yaml \\ environment=salt://environment.yaml \\ parameters="{"image": "Debian 8", "flavor": "m1.small"}" \\ poll=5 rollback=False timeout=60 profile=openstack1 .. versionadded:: 2017.7.5,2018.3.1 The spelling mistake in parameter `enviroment` was corrected to `environment`. The misspelled version is still supported for backward compatibility, but will be removed in Salt Neon. ''' if environment is None and enviroment is not None: salt.utils.versions.warn_until('Neon', ( "Please use the 'environment' parameter instead of the misspelled 'enviroment' " "parameter which will be removed in Salt Neon." )) environment = enviroment h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not parameters: parameters = {} if template_file: template_tmp_file = salt.utils.files.mkstemp() tsfn, source_sum, comment_ = __salt__['file.get_managed']( name=template_tmp_file, template=None, source=template_file, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) template_manage_result = __salt__['file.manage_file']( name=template_tmp_file, sfn=tsfn, ret=None, source=template_file, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if template_manage_result['result']: with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_: tpl = salt.utils.stringutils.to_unicode(tfp_.read()) salt.utils.files.safe_rm(template_tmp_file) try: template = _parse_template(tpl) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open template: {0} {1}'.format(template_file, comment_) else: ret['result'] = False ret['comment'] = 'Can not open template' if ret['result'] is False: return ret kwargs = {} kwargs['template'] = template try: h_client.stacks.validate(**kwargs) except Exception as ex: log.exception('Template not valid') ret['result'] = False ret['comment'] = 'Template not valid: {0}'.format(ex) return ret env = {} if environment: environment_tmp_file = salt.utils.files.mkstemp() esfn, source_sum, comment_ = __salt__['file.get_managed']( name=environment_tmp_file, template=None, source=environment, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) environment_manage_result = __salt__['file.manage_file']( name=environment_tmp_file, sfn=esfn, ret=None, source=environment, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if environment_manage_result['result']: with salt.utils.files.fopen(environment_tmp_file, 'r') as efp_: env_str = salt.utils.stringutils.to_unicode(efp_.read()) salt.utils.files.safe_rm(environment_tmp_file) try: env = _parse_environment(env_str) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open environment: {0}, {1}'.format(environment, comment_) if ret['result'] is False: return ret fields = { 'stack_name': name, 'disable_rollback': not rollback, 'parameters': parameters, 'template': template, 'environment': env, 'timeout_mins': timeout } # If one or more environments is found, pass the listing to the server try: h_client.stacks.create(**fields) except Exception as ex: # pylint: disable=W0703 log.exception('Create failed') ret['result'] = False ret['comment'] = six.text_type(ex) return ret if poll > 0: stack_status, msg = _poll_for_events(h_client, name, action='CREATE', poll_period=poll, timeout=timeout) if stack_status == 'CREATE_FAILED': ret['result'] = False ret['comment'] = 'Created stack FAILED\'{0}\'{1}.'.format(name, msg) if ret['result'] is True: ret['comment'] = 'Created stack \'{0}\'.'.format(name) return ret def update_stack(name=None, template_file=None, environment=None, parameters=None, poll=0, rollback=False, timeout=60, profile=None, enviroment=None): ''' Update a stack (heat stack-template) name Name of the stack template_file File of template environment File of environment parameters Parameter dict used to update the stack poll Poll and report events until stack complete rollback Enable rollback on update failure timeout Stack creation timeout in minutes profile Profile to build on CLI Example: .. code-block:: bash salt '*' heat.update_stack name=mystack \\ template_file=salt://template.yaml \\ environment=salt://environment.yaml \\ parameters="{"image": "Debian 8", "flavor": "m1.small"}" \\ poll=5 rollback=False timeout=60 profile=openstack1 .. versionadded:: 2017.7.5,2018.3.1 The spelling mistake in parameter `enviroment` was corrected to `environment`. The misspelled version is still supported for backward compatibility, but will be removed in Salt Neon. ''' if environment is None and enviroment is not None: salt.utils.versions.warn_until('Neon', ( "Please use the 'environment' parameter instead of the misspelled 'enviroment' " "parameter which will be removed in Salt Neon." )) environment = enviroment h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not name: ret['result'] = False ret['comment'] = 'Parameter name missing or None' return ret if not parameters: parameters = {} if template_file: template_tmp_file = salt.utils.files.mkstemp() tsfn, source_sum, comment_ = __salt__['file.get_managed']( name=template_tmp_file, template=None, source=template_file, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) template_manage_result = __salt__['file.manage_file']( name=template_tmp_file, sfn=tsfn, ret=None, source=template_file, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if template_manage_result['result']: with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_: tpl = salt.utils.stringutils.to_unicode(tfp_.read()) salt.utils.files.safe_rm(template_tmp_file) try: template = _parse_template(tpl) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open template: {0} {1}'.format(template_file, comment_) else: ret['result'] = False ret['comment'] = 'Can not open template' if ret['result'] is False: return ret kwargs = {} kwargs['template'] = template try: h_client.stacks.validate(**kwargs) except Exception as ex: # pylint: disable=W0703 log.exception('Template not valid') ret['result'] = False ret['comment'] = 'Template not valid {0}'.format(ex) return ret env = {} if environment: environment_tmp_file = salt.utils.files.mkstemp() esfn, source_sum, comment_ = __salt__['file.get_managed']( name=environment_tmp_file, template=None, source=environment, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) environment_manage_result = __salt__['file.manage_file']( name=environment_tmp_file, sfn=esfn, ret=None, source=environment, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if environment_manage_result['result']: with salt.utils.files.fopen(environment_tmp_file, 'r') as efp_: env_str = salt.utils.stringutils.to_unicode(efp_.read()) salt.utils.files.safe_rm(environment_tmp_file) try: env = _parse_environment(env_str) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open environment: {0}, {1}'.format(environment, comment_) if ret['result'] is False: return ret fields = { 'disable_rollback': not rollback, 'parameters': parameters, 'template': template, 'environment': env, 'timeout_mins': timeout } try: h_client.stacks.update(name, **fields) except Exception as ex: # pylint: disable=W0703 log.exception('Update failed') ret['result'] = False ret['comment'] = 'Update failed {0}'.format(ex) return ret if poll > 0: stack_status, msg = _poll_for_events(h_client, name, action='UPDATE', poll_period=poll, timeout=timeout) if stack_status == 'UPDATE_FAILED': ret['result'] = False ret['comment'] = 'Updated stack FAILED\'{0}\'{1}.'.format(name, msg) if ret['result'] is True: ret['comment'] = 'Updated stack \'{0}\'.'.format(name), return ret def template_stack(name=None, profile=None): ''' Return template a specific stack (heat stack-template) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.template_stack name=mystack profile=openstack1 ''' h_client = _auth(profile) if not name: return { 'result': False, 'comment': 'Parameter name missing or None' } try: get_template = h_client.stacks.template(name) except heatclient.exc.HTTPNotFound: return { 'result': False, 'comment': 'No stack with {0}'.format(name) } except heatclient.exc.BadRequest: return { 'result': False, 'comment': 'Bad request fot stack {0}'.format(name) } if 'heat_template_version' in get_template: template = salt.utils.yaml.safe_dump(get_template) else: template = jsonutils.dumps(get_template, indent=2, ensure_ascii=False) checksum = __salt__['hashutil.digest'](template) ret = { 'template': template, 'result': True, 'checksum': checksum } return ret
saltstack/salt
salt/modules/heat.py
_get_stack_events
python
def _get_stack_events(h_client, stack_id, event_args): ''' Get event for stack ''' event_args['stack_id'] = stack_id event_args['resource_name'] = None try: events = h_client.events.list(**event_args) except heatclient.exc.HTTPNotFound as exc: raise heatclient.exc.CommandError(six.text_type(exc)) else: for event in events: event.stack_name = stack_id.split('/')[0] return events
Get event for stack
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/heat.py#L219-L232
null
# -*- coding: utf-8 -*- ''' Module for handling OpenStack Heat calls .. versionadded:: 2017.7.0 :depends: - heatclient Python module :configuration: This module is not usable until the user, password, tenant, and auth URL are specified either in a pillar or in the minion's config file. For example:: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.insecure: False #(optional) keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' # Optional keystone.region_name: 'RegionOne' If configuration for multiple OpenStack accounts is required, they can be set up as different configuration profiles: For example:: openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the heat functions can make use of a configuration profile by declaring it explicitly. For example:: salt '*' heat.flavor_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time import logging # Import Salt libs from salt.exceptions import SaltInvocationError from salt.ext import six import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml # pylint: disable=import-error HAS_HEAT = False try: import heatclient HAS_HEAT = True except ImportError: pass HAS_OSLO = False try: from oslo_serialization import jsonutils HAS_OSLO = True except ImportError: pass SECTIONS = ( PARAMETER_DEFAULTS, PARAMETERS, RESOURCE_REGISTRY, EVENT_SINKS) = ( 'parameter_defaults', 'parameters', 'resource_registry', 'event_sinks') logging.basicConfig(level=logging.DEBUG) log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if heat is installed on this minion. ''' if HAS_HEAT and HAS_OSLO: return 'heat' return (False, 'The heat execution module cannot be loaded: ' 'the heatclient and oslo_serialization' # 'the heatclient and keystoneclient and oslo_serialization' ' python library is not available.') __opts__ = {} def _auth(profile=None, api_version=1, **connection_args): ''' Set up heat credentials, returns `heatclient.client.Client`. Optional parameter "api_version" defaults to 1. Only intended to be used within heat-enabled modules ''' if profile: prefix = profile + ':keystone.' else: prefix = 'keystone.' def get(key, default=None): ''' Checks connection_args, then salt-minion config, falls back to specified default value. ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', None) tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0') insecure = get('insecure', False) admin_token = get('token') region_name = get('region_name', None) if admin_token and api_version != 1 and not password: # If we had a password we could just # ignore the admin-token and move on... raise SaltInvocationError('Only can use keystone admin token ' + 'with Heat API v1') elif password: # Can't use the admin-token anyway kwargs = {'username': user, 'password': password, 'tenant_id': tenant_id, 'auth_url': auth_url, 'region_name': region_name, 'tenant_name': tenant} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True elif api_version == 1 and admin_token: kwargs = {'token': admin_token, 'auth_url': auth_url} else: raise SaltInvocationError('No credentials to authenticate with.') token = __salt__['keystone.token_get'](profile) kwargs['token'] = token['id'] # This doesn't realy prevent the password to show up # in the minion log as keystoneclient.session is # logging it anyway when in debug-mode kwargs.pop('password') try: heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['url'] except KeyError: heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['publicurl'] heat_endpoint = heat_endpoint % token log.debug('Calling heatclient.client.Client(%s, %s, **%s)', api_version, heat_endpoint, kwargs) # may raise exc.HTTPUnauthorized, exc.HTTPNotFound # but we deal with those elsewhere return heatclient.client.Client(api_version, endpoint=heat_endpoint, **kwargs) def _parse_template(tmpl_str): ''' Parsing template ''' tmpl_str = tmpl_str.strip() if tmpl_str.startswith('{'): tpl = salt.utils.json.loads(tmpl_str) else: try: tpl = salt.utils.yaml.safe_load(tmpl_str) except salt.utils.yaml.YAMLError as exc: raise ValueError(six.text_type(exc)) else: if tpl is None: tpl = {} if not ('HeatTemplateFormatVersion' in tpl or 'heat_template_version' in tpl or 'AWSTemplateFormatVersion' in tpl): raise ValueError(('Template format version not found.')) return tpl def _parse_environment(env_str): ''' Parsing template ''' try: env = salt.utils.yaml.safe_load(env_str) except salt.utils.yaml.YAMLError as exc: raise ValueError(six.text_type(exc)) else: if env is None: env = {} elif not isinstance(env, dict): raise ValueError( 'The environment is not a valid YAML mapping data type.' ) for param in env: if param not in SECTIONS: raise ValueError('environment has wrong section "{0}"'.format(param)) return env def _poll_for_events(h_client, stack_name, action=None, poll_period=5, timeout=60, marker=None): ''' Polling stack events ''' if action: stop_status = ('{0}_FAILED'.format(action), '{0}_COMPLETE'.format(action)) stop_check = lambda a: a in stop_status else: stop_check = lambda a: a.endswith('_COMPLETE') or a.endswith('_FAILED') timeout_sec = timeout * 60 no_event_polls = 0 msg_template = ('\n Stack %(name)s %(status)s \n') while True: events = _get_stack_events(h_client, stack_id=stack_name, event_args={'sort_dir': 'asc', 'marker': marker}) if not events: no_event_polls += 1 else: no_event_polls = 0 # set marker to last event that was received. marker = getattr(events[-1], 'id', None) for event in events: # check if stack event was also received if getattr(event, 'resource_name', '') == stack_name: stack_status = getattr(event, 'resource_status', '') msg = msg_template % dict( name=stack_name, status=stack_status) if stop_check(stack_status): return stack_status, msg if no_event_polls >= 2: # after 2 polls with no events, fall back to a stack get stack = h_client.stacks.get(stack_name) stack_status = stack.stack_status msg = msg_template % dict( name=stack_name, status=stack_status) if stop_check(stack_status): return stack_status, msg # go back to event polling again no_event_polls = 0 time.sleep(poll_period) timeout_sec -= poll_period if timeout_sec <= 0: stack_status = '{0}_FAILED'.format(action) msg = 'Timeout expired' return stack_status, msg def list_stack(profile=None): ''' Return a list of available stack (heat stack-list) profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.list_stack profile=openstack1 ''' ret = {} h_client = _auth(profile) for stack in h_client.stacks.list(): links = {} for link in stack.links: links[link['rel']] = link['href'] ret[stack.stack_name] = { 'status': stack.stack_status, 'id': stack.id, 'name': stack.stack_name, 'creation': stack.creation_time, 'owner': stack.stack_owner, 'reason': stack.stack_status_reason, 'links': links, } return ret def show_stack(name=None, profile=None): ''' Return details about a specific stack (heat stack-show) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.show_stack name=mystack profile=openstack1 ''' h_client = _auth(profile) if not name: return { 'result': False, 'comment': 'Parameter name missing or None' } try: ret = {} stack = h_client.stacks.get(name) links = {} for link in stack.links: links[link['rel']] = link['href'] ret[stack.stack_name] = { 'status': stack.stack_status, 'id': stack.id, 'name': stack.stack_name, 'creation': stack.creation_time, 'owner': stack.stack_owner, 'reason': stack.stack_status_reason, 'parameters': stack.parameters, 'links': links, } ret['result'] = True except heatclient.exc.HTTPNotFound: return { 'result': False, 'comment': 'No stack {0}'.format(name) } return ret def delete_stack(name=None, poll=0, timeout=60, profile=None): ''' Delete a stack (heat stack-delete) name Name of the stack poll Poll and report events until stack complete timeout Stack creation timeout in minute profile Profile to use CLI Examples: .. code-block:: bash salt '*' heat.delete_stack name=mystack poll=5 \\ profile=openstack1 ''' h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not name: ret['result'] = False ret['comment'] = 'Parameter name missing or None' return ret try: h_client.stacks.delete(name) except heatclient.exc.HTTPNotFound: ret['result'] = False ret['comment'] = 'No stack {0}'.format(name) except heatclient.exc.HTTPForbidden as forbidden: log.exception(forbidden) ret['result'] = False ret['comment'] = six.text_type(forbidden) if ret['result'] is False: return ret if poll > 0: try: stack_status, msg = _poll_for_events(h_client, name, action='DELETE', poll_period=poll, timeout=timeout) except heatclient.exc.CommandError: ret['comment'] = 'Deleted stack {0}.'.format(name) return ret except Exception as ex: # pylint: disable=W0703 log.exception('Delete failed %s', ex) ret['result'] = False ret['comment'] = '{0}'.format(ex) return ret if stack_status == 'DELETE_FAILED': ret['result'] = False ret['comment'] = 'Deleted stack FAILED\'{0}\'{1}.'.format(name, msg) else: ret['comment'] = 'Deleted stack {0}.'.format(name) return ret def create_stack(name=None, template_file=None, environment=None, parameters=None, poll=0, rollback=False, timeout=60, profile=None, enviroment=None): ''' Create a stack (heat stack-create) name Name of the new stack template_file File of template environment File of environment parameters Parameter dict used to create the stack poll Poll and report events until stack complete rollback Enable rollback on create failure timeout Stack creation timeout in minutes profile Profile to build on CLI Example: .. code-block:: bash salt '*' heat.create_stack name=mystack \\ template_file=salt://template.yaml \\ environment=salt://environment.yaml \\ parameters="{"image": "Debian 8", "flavor": "m1.small"}" \\ poll=5 rollback=False timeout=60 profile=openstack1 .. versionadded:: 2017.7.5,2018.3.1 The spelling mistake in parameter `enviroment` was corrected to `environment`. The misspelled version is still supported for backward compatibility, but will be removed in Salt Neon. ''' if environment is None and enviroment is not None: salt.utils.versions.warn_until('Neon', ( "Please use the 'environment' parameter instead of the misspelled 'enviroment' " "parameter which will be removed in Salt Neon." )) environment = enviroment h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not parameters: parameters = {} if template_file: template_tmp_file = salt.utils.files.mkstemp() tsfn, source_sum, comment_ = __salt__['file.get_managed']( name=template_tmp_file, template=None, source=template_file, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) template_manage_result = __salt__['file.manage_file']( name=template_tmp_file, sfn=tsfn, ret=None, source=template_file, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if template_manage_result['result']: with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_: tpl = salt.utils.stringutils.to_unicode(tfp_.read()) salt.utils.files.safe_rm(template_tmp_file) try: template = _parse_template(tpl) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open template: {0} {1}'.format(template_file, comment_) else: ret['result'] = False ret['comment'] = 'Can not open template' if ret['result'] is False: return ret kwargs = {} kwargs['template'] = template try: h_client.stacks.validate(**kwargs) except Exception as ex: log.exception('Template not valid') ret['result'] = False ret['comment'] = 'Template not valid: {0}'.format(ex) return ret env = {} if environment: environment_tmp_file = salt.utils.files.mkstemp() esfn, source_sum, comment_ = __salt__['file.get_managed']( name=environment_tmp_file, template=None, source=environment, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) environment_manage_result = __salt__['file.manage_file']( name=environment_tmp_file, sfn=esfn, ret=None, source=environment, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if environment_manage_result['result']: with salt.utils.files.fopen(environment_tmp_file, 'r') as efp_: env_str = salt.utils.stringutils.to_unicode(efp_.read()) salt.utils.files.safe_rm(environment_tmp_file) try: env = _parse_environment(env_str) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open environment: {0}, {1}'.format(environment, comment_) if ret['result'] is False: return ret fields = { 'stack_name': name, 'disable_rollback': not rollback, 'parameters': parameters, 'template': template, 'environment': env, 'timeout_mins': timeout } # If one or more environments is found, pass the listing to the server try: h_client.stacks.create(**fields) except Exception as ex: # pylint: disable=W0703 log.exception('Create failed') ret['result'] = False ret['comment'] = six.text_type(ex) return ret if poll > 0: stack_status, msg = _poll_for_events(h_client, name, action='CREATE', poll_period=poll, timeout=timeout) if stack_status == 'CREATE_FAILED': ret['result'] = False ret['comment'] = 'Created stack FAILED\'{0}\'{1}.'.format(name, msg) if ret['result'] is True: ret['comment'] = 'Created stack \'{0}\'.'.format(name) return ret def update_stack(name=None, template_file=None, environment=None, parameters=None, poll=0, rollback=False, timeout=60, profile=None, enviroment=None): ''' Update a stack (heat stack-template) name Name of the stack template_file File of template environment File of environment parameters Parameter dict used to update the stack poll Poll and report events until stack complete rollback Enable rollback on update failure timeout Stack creation timeout in minutes profile Profile to build on CLI Example: .. code-block:: bash salt '*' heat.update_stack name=mystack \\ template_file=salt://template.yaml \\ environment=salt://environment.yaml \\ parameters="{"image": "Debian 8", "flavor": "m1.small"}" \\ poll=5 rollback=False timeout=60 profile=openstack1 .. versionadded:: 2017.7.5,2018.3.1 The spelling mistake in parameter `enviroment` was corrected to `environment`. The misspelled version is still supported for backward compatibility, but will be removed in Salt Neon. ''' if environment is None and enviroment is not None: salt.utils.versions.warn_until('Neon', ( "Please use the 'environment' parameter instead of the misspelled 'enviroment' " "parameter which will be removed in Salt Neon." )) environment = enviroment h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not name: ret['result'] = False ret['comment'] = 'Parameter name missing or None' return ret if not parameters: parameters = {} if template_file: template_tmp_file = salt.utils.files.mkstemp() tsfn, source_sum, comment_ = __salt__['file.get_managed']( name=template_tmp_file, template=None, source=template_file, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) template_manage_result = __salt__['file.manage_file']( name=template_tmp_file, sfn=tsfn, ret=None, source=template_file, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if template_manage_result['result']: with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_: tpl = salt.utils.stringutils.to_unicode(tfp_.read()) salt.utils.files.safe_rm(template_tmp_file) try: template = _parse_template(tpl) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open template: {0} {1}'.format(template_file, comment_) else: ret['result'] = False ret['comment'] = 'Can not open template' if ret['result'] is False: return ret kwargs = {} kwargs['template'] = template try: h_client.stacks.validate(**kwargs) except Exception as ex: # pylint: disable=W0703 log.exception('Template not valid') ret['result'] = False ret['comment'] = 'Template not valid {0}'.format(ex) return ret env = {} if environment: environment_tmp_file = salt.utils.files.mkstemp() esfn, source_sum, comment_ = __salt__['file.get_managed']( name=environment_tmp_file, template=None, source=environment, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) environment_manage_result = __salt__['file.manage_file']( name=environment_tmp_file, sfn=esfn, ret=None, source=environment, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if environment_manage_result['result']: with salt.utils.files.fopen(environment_tmp_file, 'r') as efp_: env_str = salt.utils.stringutils.to_unicode(efp_.read()) salt.utils.files.safe_rm(environment_tmp_file) try: env = _parse_environment(env_str) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open environment: {0}, {1}'.format(environment, comment_) if ret['result'] is False: return ret fields = { 'disable_rollback': not rollback, 'parameters': parameters, 'template': template, 'environment': env, 'timeout_mins': timeout } try: h_client.stacks.update(name, **fields) except Exception as ex: # pylint: disable=W0703 log.exception('Update failed') ret['result'] = False ret['comment'] = 'Update failed {0}'.format(ex) return ret if poll > 0: stack_status, msg = _poll_for_events(h_client, name, action='UPDATE', poll_period=poll, timeout=timeout) if stack_status == 'UPDATE_FAILED': ret['result'] = False ret['comment'] = 'Updated stack FAILED\'{0}\'{1}.'.format(name, msg) if ret['result'] is True: ret['comment'] = 'Updated stack \'{0}\'.'.format(name), return ret def template_stack(name=None, profile=None): ''' Return template a specific stack (heat stack-template) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.template_stack name=mystack profile=openstack1 ''' h_client = _auth(profile) if not name: return { 'result': False, 'comment': 'Parameter name missing or None' } try: get_template = h_client.stacks.template(name) except heatclient.exc.HTTPNotFound: return { 'result': False, 'comment': 'No stack with {0}'.format(name) } except heatclient.exc.BadRequest: return { 'result': False, 'comment': 'Bad request fot stack {0}'.format(name) } if 'heat_template_version' in get_template: template = salt.utils.yaml.safe_dump(get_template) else: template = jsonutils.dumps(get_template, indent=2, ensure_ascii=False) checksum = __salt__['hashutil.digest'](template) ret = { 'template': template, 'result': True, 'checksum': checksum } return ret
saltstack/salt
salt/modules/heat.py
_poll_for_events
python
def _poll_for_events(h_client, stack_name, action=None, poll_period=5, timeout=60, marker=None): ''' Polling stack events ''' if action: stop_status = ('{0}_FAILED'.format(action), '{0}_COMPLETE'.format(action)) stop_check = lambda a: a in stop_status else: stop_check = lambda a: a.endswith('_COMPLETE') or a.endswith('_FAILED') timeout_sec = timeout * 60 no_event_polls = 0 msg_template = ('\n Stack %(name)s %(status)s \n') while True: events = _get_stack_events(h_client, stack_id=stack_name, event_args={'sort_dir': 'asc', 'marker': marker}) if not events: no_event_polls += 1 else: no_event_polls = 0 # set marker to last event that was received. marker = getattr(events[-1], 'id', None) for event in events: # check if stack event was also received if getattr(event, 'resource_name', '') == stack_name: stack_status = getattr(event, 'resource_status', '') msg = msg_template % dict( name=stack_name, status=stack_status) if stop_check(stack_status): return stack_status, msg if no_event_polls >= 2: # after 2 polls with no events, fall back to a stack get stack = h_client.stacks.get(stack_name) stack_status = stack.stack_status msg = msg_template % dict( name=stack_name, status=stack_status) if stop_check(stack_status): return stack_status, msg # go back to event polling again no_event_polls = 0 time.sleep(poll_period) timeout_sec -= poll_period if timeout_sec <= 0: stack_status = '{0}_FAILED'.format(action) msg = 'Timeout expired' return stack_status, msg
Polling stack events
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/heat.py#L235-L283
[ "def _get_stack_events(h_client, stack_id, event_args):\n '''\n Get event for stack\n '''\n event_args['stack_id'] = stack_id\n event_args['resource_name'] = None\n try:\n events = h_client.events.list(**event_args)\n except heatclient.exc.HTTPNotFound as exc:\n raise heatclient.exc.CommandError(six.text_type(exc))\n else:\n for event in events:\n event.stack_name = stack_id.split('/')[0]\n return events\n", "stop_check = lambda a: a in stop_status\n" ]
# -*- coding: utf-8 -*- ''' Module for handling OpenStack Heat calls .. versionadded:: 2017.7.0 :depends: - heatclient Python module :configuration: This module is not usable until the user, password, tenant, and auth URL are specified either in a pillar or in the minion's config file. For example:: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.insecure: False #(optional) keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' # Optional keystone.region_name: 'RegionOne' If configuration for multiple OpenStack accounts is required, they can be set up as different configuration profiles: For example:: openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the heat functions can make use of a configuration profile by declaring it explicitly. For example:: salt '*' heat.flavor_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time import logging # Import Salt libs from salt.exceptions import SaltInvocationError from salt.ext import six import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml # pylint: disable=import-error HAS_HEAT = False try: import heatclient HAS_HEAT = True except ImportError: pass HAS_OSLO = False try: from oslo_serialization import jsonutils HAS_OSLO = True except ImportError: pass SECTIONS = ( PARAMETER_DEFAULTS, PARAMETERS, RESOURCE_REGISTRY, EVENT_SINKS) = ( 'parameter_defaults', 'parameters', 'resource_registry', 'event_sinks') logging.basicConfig(level=logging.DEBUG) log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if heat is installed on this minion. ''' if HAS_HEAT and HAS_OSLO: return 'heat' return (False, 'The heat execution module cannot be loaded: ' 'the heatclient and oslo_serialization' # 'the heatclient and keystoneclient and oslo_serialization' ' python library is not available.') __opts__ = {} def _auth(profile=None, api_version=1, **connection_args): ''' Set up heat credentials, returns `heatclient.client.Client`. Optional parameter "api_version" defaults to 1. Only intended to be used within heat-enabled modules ''' if profile: prefix = profile + ':keystone.' else: prefix = 'keystone.' def get(key, default=None): ''' Checks connection_args, then salt-minion config, falls back to specified default value. ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', None) tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0') insecure = get('insecure', False) admin_token = get('token') region_name = get('region_name', None) if admin_token and api_version != 1 and not password: # If we had a password we could just # ignore the admin-token and move on... raise SaltInvocationError('Only can use keystone admin token ' + 'with Heat API v1') elif password: # Can't use the admin-token anyway kwargs = {'username': user, 'password': password, 'tenant_id': tenant_id, 'auth_url': auth_url, 'region_name': region_name, 'tenant_name': tenant} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True elif api_version == 1 and admin_token: kwargs = {'token': admin_token, 'auth_url': auth_url} else: raise SaltInvocationError('No credentials to authenticate with.') token = __salt__['keystone.token_get'](profile) kwargs['token'] = token['id'] # This doesn't realy prevent the password to show up # in the minion log as keystoneclient.session is # logging it anyway when in debug-mode kwargs.pop('password') try: heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['url'] except KeyError: heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['publicurl'] heat_endpoint = heat_endpoint % token log.debug('Calling heatclient.client.Client(%s, %s, **%s)', api_version, heat_endpoint, kwargs) # may raise exc.HTTPUnauthorized, exc.HTTPNotFound # but we deal with those elsewhere return heatclient.client.Client(api_version, endpoint=heat_endpoint, **kwargs) def _parse_template(tmpl_str): ''' Parsing template ''' tmpl_str = tmpl_str.strip() if tmpl_str.startswith('{'): tpl = salt.utils.json.loads(tmpl_str) else: try: tpl = salt.utils.yaml.safe_load(tmpl_str) except salt.utils.yaml.YAMLError as exc: raise ValueError(six.text_type(exc)) else: if tpl is None: tpl = {} if not ('HeatTemplateFormatVersion' in tpl or 'heat_template_version' in tpl or 'AWSTemplateFormatVersion' in tpl): raise ValueError(('Template format version not found.')) return tpl def _parse_environment(env_str): ''' Parsing template ''' try: env = salt.utils.yaml.safe_load(env_str) except salt.utils.yaml.YAMLError as exc: raise ValueError(six.text_type(exc)) else: if env is None: env = {} elif not isinstance(env, dict): raise ValueError( 'The environment is not a valid YAML mapping data type.' ) for param in env: if param not in SECTIONS: raise ValueError('environment has wrong section "{0}"'.format(param)) return env def _get_stack_events(h_client, stack_id, event_args): ''' Get event for stack ''' event_args['stack_id'] = stack_id event_args['resource_name'] = None try: events = h_client.events.list(**event_args) except heatclient.exc.HTTPNotFound as exc: raise heatclient.exc.CommandError(six.text_type(exc)) else: for event in events: event.stack_name = stack_id.split('/')[0] return events def list_stack(profile=None): ''' Return a list of available stack (heat stack-list) profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.list_stack profile=openstack1 ''' ret = {} h_client = _auth(profile) for stack in h_client.stacks.list(): links = {} for link in stack.links: links[link['rel']] = link['href'] ret[stack.stack_name] = { 'status': stack.stack_status, 'id': stack.id, 'name': stack.stack_name, 'creation': stack.creation_time, 'owner': stack.stack_owner, 'reason': stack.stack_status_reason, 'links': links, } return ret def show_stack(name=None, profile=None): ''' Return details about a specific stack (heat stack-show) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.show_stack name=mystack profile=openstack1 ''' h_client = _auth(profile) if not name: return { 'result': False, 'comment': 'Parameter name missing or None' } try: ret = {} stack = h_client.stacks.get(name) links = {} for link in stack.links: links[link['rel']] = link['href'] ret[stack.stack_name] = { 'status': stack.stack_status, 'id': stack.id, 'name': stack.stack_name, 'creation': stack.creation_time, 'owner': stack.stack_owner, 'reason': stack.stack_status_reason, 'parameters': stack.parameters, 'links': links, } ret['result'] = True except heatclient.exc.HTTPNotFound: return { 'result': False, 'comment': 'No stack {0}'.format(name) } return ret def delete_stack(name=None, poll=0, timeout=60, profile=None): ''' Delete a stack (heat stack-delete) name Name of the stack poll Poll and report events until stack complete timeout Stack creation timeout in minute profile Profile to use CLI Examples: .. code-block:: bash salt '*' heat.delete_stack name=mystack poll=5 \\ profile=openstack1 ''' h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not name: ret['result'] = False ret['comment'] = 'Parameter name missing or None' return ret try: h_client.stacks.delete(name) except heatclient.exc.HTTPNotFound: ret['result'] = False ret['comment'] = 'No stack {0}'.format(name) except heatclient.exc.HTTPForbidden as forbidden: log.exception(forbidden) ret['result'] = False ret['comment'] = six.text_type(forbidden) if ret['result'] is False: return ret if poll > 0: try: stack_status, msg = _poll_for_events(h_client, name, action='DELETE', poll_period=poll, timeout=timeout) except heatclient.exc.CommandError: ret['comment'] = 'Deleted stack {0}.'.format(name) return ret except Exception as ex: # pylint: disable=W0703 log.exception('Delete failed %s', ex) ret['result'] = False ret['comment'] = '{0}'.format(ex) return ret if stack_status == 'DELETE_FAILED': ret['result'] = False ret['comment'] = 'Deleted stack FAILED\'{0}\'{1}.'.format(name, msg) else: ret['comment'] = 'Deleted stack {0}.'.format(name) return ret def create_stack(name=None, template_file=None, environment=None, parameters=None, poll=0, rollback=False, timeout=60, profile=None, enviroment=None): ''' Create a stack (heat stack-create) name Name of the new stack template_file File of template environment File of environment parameters Parameter dict used to create the stack poll Poll and report events until stack complete rollback Enable rollback on create failure timeout Stack creation timeout in minutes profile Profile to build on CLI Example: .. code-block:: bash salt '*' heat.create_stack name=mystack \\ template_file=salt://template.yaml \\ environment=salt://environment.yaml \\ parameters="{"image": "Debian 8", "flavor": "m1.small"}" \\ poll=5 rollback=False timeout=60 profile=openstack1 .. versionadded:: 2017.7.5,2018.3.1 The spelling mistake in parameter `enviroment` was corrected to `environment`. The misspelled version is still supported for backward compatibility, but will be removed in Salt Neon. ''' if environment is None and enviroment is not None: salt.utils.versions.warn_until('Neon', ( "Please use the 'environment' parameter instead of the misspelled 'enviroment' " "parameter which will be removed in Salt Neon." )) environment = enviroment h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not parameters: parameters = {} if template_file: template_tmp_file = salt.utils.files.mkstemp() tsfn, source_sum, comment_ = __salt__['file.get_managed']( name=template_tmp_file, template=None, source=template_file, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) template_manage_result = __salt__['file.manage_file']( name=template_tmp_file, sfn=tsfn, ret=None, source=template_file, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if template_manage_result['result']: with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_: tpl = salt.utils.stringutils.to_unicode(tfp_.read()) salt.utils.files.safe_rm(template_tmp_file) try: template = _parse_template(tpl) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open template: {0} {1}'.format(template_file, comment_) else: ret['result'] = False ret['comment'] = 'Can not open template' if ret['result'] is False: return ret kwargs = {} kwargs['template'] = template try: h_client.stacks.validate(**kwargs) except Exception as ex: log.exception('Template not valid') ret['result'] = False ret['comment'] = 'Template not valid: {0}'.format(ex) return ret env = {} if environment: environment_tmp_file = salt.utils.files.mkstemp() esfn, source_sum, comment_ = __salt__['file.get_managed']( name=environment_tmp_file, template=None, source=environment, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) environment_manage_result = __salt__['file.manage_file']( name=environment_tmp_file, sfn=esfn, ret=None, source=environment, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if environment_manage_result['result']: with salt.utils.files.fopen(environment_tmp_file, 'r') as efp_: env_str = salt.utils.stringutils.to_unicode(efp_.read()) salt.utils.files.safe_rm(environment_tmp_file) try: env = _parse_environment(env_str) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open environment: {0}, {1}'.format(environment, comment_) if ret['result'] is False: return ret fields = { 'stack_name': name, 'disable_rollback': not rollback, 'parameters': parameters, 'template': template, 'environment': env, 'timeout_mins': timeout } # If one or more environments is found, pass the listing to the server try: h_client.stacks.create(**fields) except Exception as ex: # pylint: disable=W0703 log.exception('Create failed') ret['result'] = False ret['comment'] = six.text_type(ex) return ret if poll > 0: stack_status, msg = _poll_for_events(h_client, name, action='CREATE', poll_period=poll, timeout=timeout) if stack_status == 'CREATE_FAILED': ret['result'] = False ret['comment'] = 'Created stack FAILED\'{0}\'{1}.'.format(name, msg) if ret['result'] is True: ret['comment'] = 'Created stack \'{0}\'.'.format(name) return ret def update_stack(name=None, template_file=None, environment=None, parameters=None, poll=0, rollback=False, timeout=60, profile=None, enviroment=None): ''' Update a stack (heat stack-template) name Name of the stack template_file File of template environment File of environment parameters Parameter dict used to update the stack poll Poll and report events until stack complete rollback Enable rollback on update failure timeout Stack creation timeout in minutes profile Profile to build on CLI Example: .. code-block:: bash salt '*' heat.update_stack name=mystack \\ template_file=salt://template.yaml \\ environment=salt://environment.yaml \\ parameters="{"image": "Debian 8", "flavor": "m1.small"}" \\ poll=5 rollback=False timeout=60 profile=openstack1 .. versionadded:: 2017.7.5,2018.3.1 The spelling mistake in parameter `enviroment` was corrected to `environment`. The misspelled version is still supported for backward compatibility, but will be removed in Salt Neon. ''' if environment is None and enviroment is not None: salt.utils.versions.warn_until('Neon', ( "Please use the 'environment' parameter instead of the misspelled 'enviroment' " "parameter which will be removed in Salt Neon." )) environment = enviroment h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not name: ret['result'] = False ret['comment'] = 'Parameter name missing or None' return ret if not parameters: parameters = {} if template_file: template_tmp_file = salt.utils.files.mkstemp() tsfn, source_sum, comment_ = __salt__['file.get_managed']( name=template_tmp_file, template=None, source=template_file, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) template_manage_result = __salt__['file.manage_file']( name=template_tmp_file, sfn=tsfn, ret=None, source=template_file, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if template_manage_result['result']: with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_: tpl = salt.utils.stringutils.to_unicode(tfp_.read()) salt.utils.files.safe_rm(template_tmp_file) try: template = _parse_template(tpl) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open template: {0} {1}'.format(template_file, comment_) else: ret['result'] = False ret['comment'] = 'Can not open template' if ret['result'] is False: return ret kwargs = {} kwargs['template'] = template try: h_client.stacks.validate(**kwargs) except Exception as ex: # pylint: disable=W0703 log.exception('Template not valid') ret['result'] = False ret['comment'] = 'Template not valid {0}'.format(ex) return ret env = {} if environment: environment_tmp_file = salt.utils.files.mkstemp() esfn, source_sum, comment_ = __salt__['file.get_managed']( name=environment_tmp_file, template=None, source=environment, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) environment_manage_result = __salt__['file.manage_file']( name=environment_tmp_file, sfn=esfn, ret=None, source=environment, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if environment_manage_result['result']: with salt.utils.files.fopen(environment_tmp_file, 'r') as efp_: env_str = salt.utils.stringutils.to_unicode(efp_.read()) salt.utils.files.safe_rm(environment_tmp_file) try: env = _parse_environment(env_str) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open environment: {0}, {1}'.format(environment, comment_) if ret['result'] is False: return ret fields = { 'disable_rollback': not rollback, 'parameters': parameters, 'template': template, 'environment': env, 'timeout_mins': timeout } try: h_client.stacks.update(name, **fields) except Exception as ex: # pylint: disable=W0703 log.exception('Update failed') ret['result'] = False ret['comment'] = 'Update failed {0}'.format(ex) return ret if poll > 0: stack_status, msg = _poll_for_events(h_client, name, action='UPDATE', poll_period=poll, timeout=timeout) if stack_status == 'UPDATE_FAILED': ret['result'] = False ret['comment'] = 'Updated stack FAILED\'{0}\'{1}.'.format(name, msg) if ret['result'] is True: ret['comment'] = 'Updated stack \'{0}\'.'.format(name), return ret def template_stack(name=None, profile=None): ''' Return template a specific stack (heat stack-template) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.template_stack name=mystack profile=openstack1 ''' h_client = _auth(profile) if not name: return { 'result': False, 'comment': 'Parameter name missing or None' } try: get_template = h_client.stacks.template(name) except heatclient.exc.HTTPNotFound: return { 'result': False, 'comment': 'No stack with {0}'.format(name) } except heatclient.exc.BadRequest: return { 'result': False, 'comment': 'Bad request fot stack {0}'.format(name) } if 'heat_template_version' in get_template: template = salt.utils.yaml.safe_dump(get_template) else: template = jsonutils.dumps(get_template, indent=2, ensure_ascii=False) checksum = __salt__['hashutil.digest'](template) ret = { 'template': template, 'result': True, 'checksum': checksum } return ret
saltstack/salt
salt/modules/heat.py
list_stack
python
def list_stack(profile=None): ''' Return a list of available stack (heat stack-list) profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.list_stack profile=openstack1 ''' ret = {} h_client = _auth(profile) for stack in h_client.stacks.list(): links = {} for link in stack.links: links[link['rel']] = link['href'] ret[stack.stack_name] = { 'status': stack.stack_status, 'id': stack.id, 'name': stack.stack_name, 'creation': stack.creation_time, 'owner': stack.stack_owner, 'reason': stack.stack_status_reason, 'links': links, } return ret
Return a list of available stack (heat stack-list) profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.list_stack profile=openstack1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/heat.py#L286-L314
[ "def _auth(profile=None, api_version=1, **connection_args):\n '''\n Set up heat credentials, returns\n `heatclient.client.Client`. Optional parameter\n \"api_version\" defaults to 1.\n\n Only intended to be used within heat-enabled modules\n '''\n\n if profile:\n prefix = profile + ':keystone.'\n else:\n prefix = 'keystone.'\n\n def get(key, default=None):\n '''\n Checks connection_args, then salt-minion config,\n falls back to specified default value.\n '''\n return connection_args.get('connection_' + key,\n __salt__['config.get'](prefix + key, default))\n\n user = get('user', 'admin')\n password = get('password', None)\n tenant = get('tenant', 'admin')\n tenant_id = get('tenant_id')\n auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0')\n insecure = get('insecure', False)\n admin_token = get('token')\n region_name = get('region_name', None)\n\n if admin_token and api_version != 1 and not password:\n # If we had a password we could just\n # ignore the admin-token and move on...\n raise SaltInvocationError('Only can use keystone admin token ' +\n 'with Heat API v1')\n elif password:\n # Can't use the admin-token anyway\n kwargs = {'username': user,\n 'password': password,\n 'tenant_id': tenant_id,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'tenant_name': tenant}\n # 'insecure' keyword not supported by all v2.0 keystone clients\n # this ensures it's only passed in when defined\n if insecure:\n kwargs['insecure'] = True\n elif api_version == 1 and admin_token:\n kwargs = {'token': admin_token,\n 'auth_url': auth_url}\n else:\n raise SaltInvocationError('No credentials to authenticate with.')\n\n token = __salt__['keystone.token_get'](profile)\n kwargs['token'] = token['id']\n # This doesn't realy prevent the password to show up\n # in the minion log as keystoneclient.session is\n # logging it anyway when in debug-mode\n kwargs.pop('password')\n try:\n heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['url']\n except KeyError:\n heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['publicurl']\n heat_endpoint = heat_endpoint % token\n log.debug('Calling heatclient.client.Client(%s, %s, **%s)',\n api_version, heat_endpoint, kwargs)\n # may raise exc.HTTPUnauthorized, exc.HTTPNotFound\n # but we deal with those elsewhere\n return heatclient.client.Client(api_version, endpoint=heat_endpoint, **kwargs)\n" ]
# -*- coding: utf-8 -*- ''' Module for handling OpenStack Heat calls .. versionadded:: 2017.7.0 :depends: - heatclient Python module :configuration: This module is not usable until the user, password, tenant, and auth URL are specified either in a pillar or in the minion's config file. For example:: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.insecure: False #(optional) keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' # Optional keystone.region_name: 'RegionOne' If configuration for multiple OpenStack accounts is required, they can be set up as different configuration profiles: For example:: openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the heat functions can make use of a configuration profile by declaring it explicitly. For example:: salt '*' heat.flavor_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time import logging # Import Salt libs from salt.exceptions import SaltInvocationError from salt.ext import six import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml # pylint: disable=import-error HAS_HEAT = False try: import heatclient HAS_HEAT = True except ImportError: pass HAS_OSLO = False try: from oslo_serialization import jsonutils HAS_OSLO = True except ImportError: pass SECTIONS = ( PARAMETER_DEFAULTS, PARAMETERS, RESOURCE_REGISTRY, EVENT_SINKS) = ( 'parameter_defaults', 'parameters', 'resource_registry', 'event_sinks') logging.basicConfig(level=logging.DEBUG) log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if heat is installed on this minion. ''' if HAS_HEAT and HAS_OSLO: return 'heat' return (False, 'The heat execution module cannot be loaded: ' 'the heatclient and oslo_serialization' # 'the heatclient and keystoneclient and oslo_serialization' ' python library is not available.') __opts__ = {} def _auth(profile=None, api_version=1, **connection_args): ''' Set up heat credentials, returns `heatclient.client.Client`. Optional parameter "api_version" defaults to 1. Only intended to be used within heat-enabled modules ''' if profile: prefix = profile + ':keystone.' else: prefix = 'keystone.' def get(key, default=None): ''' Checks connection_args, then salt-minion config, falls back to specified default value. ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', None) tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0') insecure = get('insecure', False) admin_token = get('token') region_name = get('region_name', None) if admin_token and api_version != 1 and not password: # If we had a password we could just # ignore the admin-token and move on... raise SaltInvocationError('Only can use keystone admin token ' + 'with Heat API v1') elif password: # Can't use the admin-token anyway kwargs = {'username': user, 'password': password, 'tenant_id': tenant_id, 'auth_url': auth_url, 'region_name': region_name, 'tenant_name': tenant} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True elif api_version == 1 and admin_token: kwargs = {'token': admin_token, 'auth_url': auth_url} else: raise SaltInvocationError('No credentials to authenticate with.') token = __salt__['keystone.token_get'](profile) kwargs['token'] = token['id'] # This doesn't realy prevent the password to show up # in the minion log as keystoneclient.session is # logging it anyway when in debug-mode kwargs.pop('password') try: heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['url'] except KeyError: heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['publicurl'] heat_endpoint = heat_endpoint % token log.debug('Calling heatclient.client.Client(%s, %s, **%s)', api_version, heat_endpoint, kwargs) # may raise exc.HTTPUnauthorized, exc.HTTPNotFound # but we deal with those elsewhere return heatclient.client.Client(api_version, endpoint=heat_endpoint, **kwargs) def _parse_template(tmpl_str): ''' Parsing template ''' tmpl_str = tmpl_str.strip() if tmpl_str.startswith('{'): tpl = salt.utils.json.loads(tmpl_str) else: try: tpl = salt.utils.yaml.safe_load(tmpl_str) except salt.utils.yaml.YAMLError as exc: raise ValueError(six.text_type(exc)) else: if tpl is None: tpl = {} if not ('HeatTemplateFormatVersion' in tpl or 'heat_template_version' in tpl or 'AWSTemplateFormatVersion' in tpl): raise ValueError(('Template format version not found.')) return tpl def _parse_environment(env_str): ''' Parsing template ''' try: env = salt.utils.yaml.safe_load(env_str) except salt.utils.yaml.YAMLError as exc: raise ValueError(six.text_type(exc)) else: if env is None: env = {} elif not isinstance(env, dict): raise ValueError( 'The environment is not a valid YAML mapping data type.' ) for param in env: if param not in SECTIONS: raise ValueError('environment has wrong section "{0}"'.format(param)) return env def _get_stack_events(h_client, stack_id, event_args): ''' Get event for stack ''' event_args['stack_id'] = stack_id event_args['resource_name'] = None try: events = h_client.events.list(**event_args) except heatclient.exc.HTTPNotFound as exc: raise heatclient.exc.CommandError(six.text_type(exc)) else: for event in events: event.stack_name = stack_id.split('/')[0] return events def _poll_for_events(h_client, stack_name, action=None, poll_period=5, timeout=60, marker=None): ''' Polling stack events ''' if action: stop_status = ('{0}_FAILED'.format(action), '{0}_COMPLETE'.format(action)) stop_check = lambda a: a in stop_status else: stop_check = lambda a: a.endswith('_COMPLETE') or a.endswith('_FAILED') timeout_sec = timeout * 60 no_event_polls = 0 msg_template = ('\n Stack %(name)s %(status)s \n') while True: events = _get_stack_events(h_client, stack_id=stack_name, event_args={'sort_dir': 'asc', 'marker': marker}) if not events: no_event_polls += 1 else: no_event_polls = 0 # set marker to last event that was received. marker = getattr(events[-1], 'id', None) for event in events: # check if stack event was also received if getattr(event, 'resource_name', '') == stack_name: stack_status = getattr(event, 'resource_status', '') msg = msg_template % dict( name=stack_name, status=stack_status) if stop_check(stack_status): return stack_status, msg if no_event_polls >= 2: # after 2 polls with no events, fall back to a stack get stack = h_client.stacks.get(stack_name) stack_status = stack.stack_status msg = msg_template % dict( name=stack_name, status=stack_status) if stop_check(stack_status): return stack_status, msg # go back to event polling again no_event_polls = 0 time.sleep(poll_period) timeout_sec -= poll_period if timeout_sec <= 0: stack_status = '{0}_FAILED'.format(action) msg = 'Timeout expired' return stack_status, msg def show_stack(name=None, profile=None): ''' Return details about a specific stack (heat stack-show) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.show_stack name=mystack profile=openstack1 ''' h_client = _auth(profile) if not name: return { 'result': False, 'comment': 'Parameter name missing or None' } try: ret = {} stack = h_client.stacks.get(name) links = {} for link in stack.links: links[link['rel']] = link['href'] ret[stack.stack_name] = { 'status': stack.stack_status, 'id': stack.id, 'name': stack.stack_name, 'creation': stack.creation_time, 'owner': stack.stack_owner, 'reason': stack.stack_status_reason, 'parameters': stack.parameters, 'links': links, } ret['result'] = True except heatclient.exc.HTTPNotFound: return { 'result': False, 'comment': 'No stack {0}'.format(name) } return ret def delete_stack(name=None, poll=0, timeout=60, profile=None): ''' Delete a stack (heat stack-delete) name Name of the stack poll Poll and report events until stack complete timeout Stack creation timeout in minute profile Profile to use CLI Examples: .. code-block:: bash salt '*' heat.delete_stack name=mystack poll=5 \\ profile=openstack1 ''' h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not name: ret['result'] = False ret['comment'] = 'Parameter name missing or None' return ret try: h_client.stacks.delete(name) except heatclient.exc.HTTPNotFound: ret['result'] = False ret['comment'] = 'No stack {0}'.format(name) except heatclient.exc.HTTPForbidden as forbidden: log.exception(forbidden) ret['result'] = False ret['comment'] = six.text_type(forbidden) if ret['result'] is False: return ret if poll > 0: try: stack_status, msg = _poll_for_events(h_client, name, action='DELETE', poll_period=poll, timeout=timeout) except heatclient.exc.CommandError: ret['comment'] = 'Deleted stack {0}.'.format(name) return ret except Exception as ex: # pylint: disable=W0703 log.exception('Delete failed %s', ex) ret['result'] = False ret['comment'] = '{0}'.format(ex) return ret if stack_status == 'DELETE_FAILED': ret['result'] = False ret['comment'] = 'Deleted stack FAILED\'{0}\'{1}.'.format(name, msg) else: ret['comment'] = 'Deleted stack {0}.'.format(name) return ret def create_stack(name=None, template_file=None, environment=None, parameters=None, poll=0, rollback=False, timeout=60, profile=None, enviroment=None): ''' Create a stack (heat stack-create) name Name of the new stack template_file File of template environment File of environment parameters Parameter dict used to create the stack poll Poll and report events until stack complete rollback Enable rollback on create failure timeout Stack creation timeout in minutes profile Profile to build on CLI Example: .. code-block:: bash salt '*' heat.create_stack name=mystack \\ template_file=salt://template.yaml \\ environment=salt://environment.yaml \\ parameters="{"image": "Debian 8", "flavor": "m1.small"}" \\ poll=5 rollback=False timeout=60 profile=openstack1 .. versionadded:: 2017.7.5,2018.3.1 The spelling mistake in parameter `enviroment` was corrected to `environment`. The misspelled version is still supported for backward compatibility, but will be removed in Salt Neon. ''' if environment is None and enviroment is not None: salt.utils.versions.warn_until('Neon', ( "Please use the 'environment' parameter instead of the misspelled 'enviroment' " "parameter which will be removed in Salt Neon." )) environment = enviroment h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not parameters: parameters = {} if template_file: template_tmp_file = salt.utils.files.mkstemp() tsfn, source_sum, comment_ = __salt__['file.get_managed']( name=template_tmp_file, template=None, source=template_file, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) template_manage_result = __salt__['file.manage_file']( name=template_tmp_file, sfn=tsfn, ret=None, source=template_file, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if template_manage_result['result']: with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_: tpl = salt.utils.stringutils.to_unicode(tfp_.read()) salt.utils.files.safe_rm(template_tmp_file) try: template = _parse_template(tpl) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open template: {0} {1}'.format(template_file, comment_) else: ret['result'] = False ret['comment'] = 'Can not open template' if ret['result'] is False: return ret kwargs = {} kwargs['template'] = template try: h_client.stacks.validate(**kwargs) except Exception as ex: log.exception('Template not valid') ret['result'] = False ret['comment'] = 'Template not valid: {0}'.format(ex) return ret env = {} if environment: environment_tmp_file = salt.utils.files.mkstemp() esfn, source_sum, comment_ = __salt__['file.get_managed']( name=environment_tmp_file, template=None, source=environment, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) environment_manage_result = __salt__['file.manage_file']( name=environment_tmp_file, sfn=esfn, ret=None, source=environment, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if environment_manage_result['result']: with salt.utils.files.fopen(environment_tmp_file, 'r') as efp_: env_str = salt.utils.stringutils.to_unicode(efp_.read()) salt.utils.files.safe_rm(environment_tmp_file) try: env = _parse_environment(env_str) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open environment: {0}, {1}'.format(environment, comment_) if ret['result'] is False: return ret fields = { 'stack_name': name, 'disable_rollback': not rollback, 'parameters': parameters, 'template': template, 'environment': env, 'timeout_mins': timeout } # If one or more environments is found, pass the listing to the server try: h_client.stacks.create(**fields) except Exception as ex: # pylint: disable=W0703 log.exception('Create failed') ret['result'] = False ret['comment'] = six.text_type(ex) return ret if poll > 0: stack_status, msg = _poll_for_events(h_client, name, action='CREATE', poll_period=poll, timeout=timeout) if stack_status == 'CREATE_FAILED': ret['result'] = False ret['comment'] = 'Created stack FAILED\'{0}\'{1}.'.format(name, msg) if ret['result'] is True: ret['comment'] = 'Created stack \'{0}\'.'.format(name) return ret def update_stack(name=None, template_file=None, environment=None, parameters=None, poll=0, rollback=False, timeout=60, profile=None, enviroment=None): ''' Update a stack (heat stack-template) name Name of the stack template_file File of template environment File of environment parameters Parameter dict used to update the stack poll Poll and report events until stack complete rollback Enable rollback on update failure timeout Stack creation timeout in minutes profile Profile to build on CLI Example: .. code-block:: bash salt '*' heat.update_stack name=mystack \\ template_file=salt://template.yaml \\ environment=salt://environment.yaml \\ parameters="{"image": "Debian 8", "flavor": "m1.small"}" \\ poll=5 rollback=False timeout=60 profile=openstack1 .. versionadded:: 2017.7.5,2018.3.1 The spelling mistake in parameter `enviroment` was corrected to `environment`. The misspelled version is still supported for backward compatibility, but will be removed in Salt Neon. ''' if environment is None and enviroment is not None: salt.utils.versions.warn_until('Neon', ( "Please use the 'environment' parameter instead of the misspelled 'enviroment' " "parameter which will be removed in Salt Neon." )) environment = enviroment h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not name: ret['result'] = False ret['comment'] = 'Parameter name missing or None' return ret if not parameters: parameters = {} if template_file: template_tmp_file = salt.utils.files.mkstemp() tsfn, source_sum, comment_ = __salt__['file.get_managed']( name=template_tmp_file, template=None, source=template_file, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) template_manage_result = __salt__['file.manage_file']( name=template_tmp_file, sfn=tsfn, ret=None, source=template_file, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if template_manage_result['result']: with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_: tpl = salt.utils.stringutils.to_unicode(tfp_.read()) salt.utils.files.safe_rm(template_tmp_file) try: template = _parse_template(tpl) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open template: {0} {1}'.format(template_file, comment_) else: ret['result'] = False ret['comment'] = 'Can not open template' if ret['result'] is False: return ret kwargs = {} kwargs['template'] = template try: h_client.stacks.validate(**kwargs) except Exception as ex: # pylint: disable=W0703 log.exception('Template not valid') ret['result'] = False ret['comment'] = 'Template not valid {0}'.format(ex) return ret env = {} if environment: environment_tmp_file = salt.utils.files.mkstemp() esfn, source_sum, comment_ = __salt__['file.get_managed']( name=environment_tmp_file, template=None, source=environment, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) environment_manage_result = __salt__['file.manage_file']( name=environment_tmp_file, sfn=esfn, ret=None, source=environment, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if environment_manage_result['result']: with salt.utils.files.fopen(environment_tmp_file, 'r') as efp_: env_str = salt.utils.stringutils.to_unicode(efp_.read()) salt.utils.files.safe_rm(environment_tmp_file) try: env = _parse_environment(env_str) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open environment: {0}, {1}'.format(environment, comment_) if ret['result'] is False: return ret fields = { 'disable_rollback': not rollback, 'parameters': parameters, 'template': template, 'environment': env, 'timeout_mins': timeout } try: h_client.stacks.update(name, **fields) except Exception as ex: # pylint: disable=W0703 log.exception('Update failed') ret['result'] = False ret['comment'] = 'Update failed {0}'.format(ex) return ret if poll > 0: stack_status, msg = _poll_for_events(h_client, name, action='UPDATE', poll_period=poll, timeout=timeout) if stack_status == 'UPDATE_FAILED': ret['result'] = False ret['comment'] = 'Updated stack FAILED\'{0}\'{1}.'.format(name, msg) if ret['result'] is True: ret['comment'] = 'Updated stack \'{0}\'.'.format(name), return ret def template_stack(name=None, profile=None): ''' Return template a specific stack (heat stack-template) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.template_stack name=mystack profile=openstack1 ''' h_client = _auth(profile) if not name: return { 'result': False, 'comment': 'Parameter name missing or None' } try: get_template = h_client.stacks.template(name) except heatclient.exc.HTTPNotFound: return { 'result': False, 'comment': 'No stack with {0}'.format(name) } except heatclient.exc.BadRequest: return { 'result': False, 'comment': 'Bad request fot stack {0}'.format(name) } if 'heat_template_version' in get_template: template = salt.utils.yaml.safe_dump(get_template) else: template = jsonutils.dumps(get_template, indent=2, ensure_ascii=False) checksum = __salt__['hashutil.digest'](template) ret = { 'template': template, 'result': True, 'checksum': checksum } return ret
saltstack/salt
salt/modules/heat.py
show_stack
python
def show_stack(name=None, profile=None): ''' Return details about a specific stack (heat stack-show) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.show_stack name=mystack profile=openstack1 ''' h_client = _auth(profile) if not name: return { 'result': False, 'comment': 'Parameter name missing or None' } try: ret = {} stack = h_client.stacks.get(name) links = {} for link in stack.links: links[link['rel']] = link['href'] ret[stack.stack_name] = { 'status': stack.stack_status, 'id': stack.id, 'name': stack.stack_name, 'creation': stack.creation_time, 'owner': stack.stack_owner, 'reason': stack.stack_status_reason, 'parameters': stack.parameters, 'links': links, } ret['result'] = True except heatclient.exc.HTTPNotFound: return { 'result': False, 'comment': 'No stack {0}'.format(name) } return ret
Return details about a specific stack (heat stack-show) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.show_stack name=mystack profile=openstack1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/heat.py#L317-L362
[ "def _auth(profile=None, api_version=1, **connection_args):\n '''\n Set up heat credentials, returns\n `heatclient.client.Client`. Optional parameter\n \"api_version\" defaults to 1.\n\n Only intended to be used within heat-enabled modules\n '''\n\n if profile:\n prefix = profile + ':keystone.'\n else:\n prefix = 'keystone.'\n\n def get(key, default=None):\n '''\n Checks connection_args, then salt-minion config,\n falls back to specified default value.\n '''\n return connection_args.get('connection_' + key,\n __salt__['config.get'](prefix + key, default))\n\n user = get('user', 'admin')\n password = get('password', None)\n tenant = get('tenant', 'admin')\n tenant_id = get('tenant_id')\n auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0')\n insecure = get('insecure', False)\n admin_token = get('token')\n region_name = get('region_name', None)\n\n if admin_token and api_version != 1 and not password:\n # If we had a password we could just\n # ignore the admin-token and move on...\n raise SaltInvocationError('Only can use keystone admin token ' +\n 'with Heat API v1')\n elif password:\n # Can't use the admin-token anyway\n kwargs = {'username': user,\n 'password': password,\n 'tenant_id': tenant_id,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'tenant_name': tenant}\n # 'insecure' keyword not supported by all v2.0 keystone clients\n # this ensures it's only passed in when defined\n if insecure:\n kwargs['insecure'] = True\n elif api_version == 1 and admin_token:\n kwargs = {'token': admin_token,\n 'auth_url': auth_url}\n else:\n raise SaltInvocationError('No credentials to authenticate with.')\n\n token = __salt__['keystone.token_get'](profile)\n kwargs['token'] = token['id']\n # This doesn't realy prevent the password to show up\n # in the minion log as keystoneclient.session is\n # logging it anyway when in debug-mode\n kwargs.pop('password')\n try:\n heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['url']\n except KeyError:\n heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['publicurl']\n heat_endpoint = heat_endpoint % token\n log.debug('Calling heatclient.client.Client(%s, %s, **%s)',\n api_version, heat_endpoint, kwargs)\n # may raise exc.HTTPUnauthorized, exc.HTTPNotFound\n # but we deal with those elsewhere\n return heatclient.client.Client(api_version, endpoint=heat_endpoint, **kwargs)\n" ]
# -*- coding: utf-8 -*- ''' Module for handling OpenStack Heat calls .. versionadded:: 2017.7.0 :depends: - heatclient Python module :configuration: This module is not usable until the user, password, tenant, and auth URL are specified either in a pillar or in the minion's config file. For example:: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.insecure: False #(optional) keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' # Optional keystone.region_name: 'RegionOne' If configuration for multiple OpenStack accounts is required, they can be set up as different configuration profiles: For example:: openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the heat functions can make use of a configuration profile by declaring it explicitly. For example:: salt '*' heat.flavor_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time import logging # Import Salt libs from salt.exceptions import SaltInvocationError from salt.ext import six import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml # pylint: disable=import-error HAS_HEAT = False try: import heatclient HAS_HEAT = True except ImportError: pass HAS_OSLO = False try: from oslo_serialization import jsonutils HAS_OSLO = True except ImportError: pass SECTIONS = ( PARAMETER_DEFAULTS, PARAMETERS, RESOURCE_REGISTRY, EVENT_SINKS) = ( 'parameter_defaults', 'parameters', 'resource_registry', 'event_sinks') logging.basicConfig(level=logging.DEBUG) log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if heat is installed on this minion. ''' if HAS_HEAT and HAS_OSLO: return 'heat' return (False, 'The heat execution module cannot be loaded: ' 'the heatclient and oslo_serialization' # 'the heatclient and keystoneclient and oslo_serialization' ' python library is not available.') __opts__ = {} def _auth(profile=None, api_version=1, **connection_args): ''' Set up heat credentials, returns `heatclient.client.Client`. Optional parameter "api_version" defaults to 1. Only intended to be used within heat-enabled modules ''' if profile: prefix = profile + ':keystone.' else: prefix = 'keystone.' def get(key, default=None): ''' Checks connection_args, then salt-minion config, falls back to specified default value. ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', None) tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0') insecure = get('insecure', False) admin_token = get('token') region_name = get('region_name', None) if admin_token and api_version != 1 and not password: # If we had a password we could just # ignore the admin-token and move on... raise SaltInvocationError('Only can use keystone admin token ' + 'with Heat API v1') elif password: # Can't use the admin-token anyway kwargs = {'username': user, 'password': password, 'tenant_id': tenant_id, 'auth_url': auth_url, 'region_name': region_name, 'tenant_name': tenant} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True elif api_version == 1 and admin_token: kwargs = {'token': admin_token, 'auth_url': auth_url} else: raise SaltInvocationError('No credentials to authenticate with.') token = __salt__['keystone.token_get'](profile) kwargs['token'] = token['id'] # This doesn't realy prevent the password to show up # in the minion log as keystoneclient.session is # logging it anyway when in debug-mode kwargs.pop('password') try: heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['url'] except KeyError: heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['publicurl'] heat_endpoint = heat_endpoint % token log.debug('Calling heatclient.client.Client(%s, %s, **%s)', api_version, heat_endpoint, kwargs) # may raise exc.HTTPUnauthorized, exc.HTTPNotFound # but we deal with those elsewhere return heatclient.client.Client(api_version, endpoint=heat_endpoint, **kwargs) def _parse_template(tmpl_str): ''' Parsing template ''' tmpl_str = tmpl_str.strip() if tmpl_str.startswith('{'): tpl = salt.utils.json.loads(tmpl_str) else: try: tpl = salt.utils.yaml.safe_load(tmpl_str) except salt.utils.yaml.YAMLError as exc: raise ValueError(six.text_type(exc)) else: if tpl is None: tpl = {} if not ('HeatTemplateFormatVersion' in tpl or 'heat_template_version' in tpl or 'AWSTemplateFormatVersion' in tpl): raise ValueError(('Template format version not found.')) return tpl def _parse_environment(env_str): ''' Parsing template ''' try: env = salt.utils.yaml.safe_load(env_str) except salt.utils.yaml.YAMLError as exc: raise ValueError(six.text_type(exc)) else: if env is None: env = {} elif not isinstance(env, dict): raise ValueError( 'The environment is not a valid YAML mapping data type.' ) for param in env: if param not in SECTIONS: raise ValueError('environment has wrong section "{0}"'.format(param)) return env def _get_stack_events(h_client, stack_id, event_args): ''' Get event for stack ''' event_args['stack_id'] = stack_id event_args['resource_name'] = None try: events = h_client.events.list(**event_args) except heatclient.exc.HTTPNotFound as exc: raise heatclient.exc.CommandError(six.text_type(exc)) else: for event in events: event.stack_name = stack_id.split('/')[0] return events def _poll_for_events(h_client, stack_name, action=None, poll_period=5, timeout=60, marker=None): ''' Polling stack events ''' if action: stop_status = ('{0}_FAILED'.format(action), '{0}_COMPLETE'.format(action)) stop_check = lambda a: a in stop_status else: stop_check = lambda a: a.endswith('_COMPLETE') or a.endswith('_FAILED') timeout_sec = timeout * 60 no_event_polls = 0 msg_template = ('\n Stack %(name)s %(status)s \n') while True: events = _get_stack_events(h_client, stack_id=stack_name, event_args={'sort_dir': 'asc', 'marker': marker}) if not events: no_event_polls += 1 else: no_event_polls = 0 # set marker to last event that was received. marker = getattr(events[-1], 'id', None) for event in events: # check if stack event was also received if getattr(event, 'resource_name', '') == stack_name: stack_status = getattr(event, 'resource_status', '') msg = msg_template % dict( name=stack_name, status=stack_status) if stop_check(stack_status): return stack_status, msg if no_event_polls >= 2: # after 2 polls with no events, fall back to a stack get stack = h_client.stacks.get(stack_name) stack_status = stack.stack_status msg = msg_template % dict( name=stack_name, status=stack_status) if stop_check(stack_status): return stack_status, msg # go back to event polling again no_event_polls = 0 time.sleep(poll_period) timeout_sec -= poll_period if timeout_sec <= 0: stack_status = '{0}_FAILED'.format(action) msg = 'Timeout expired' return stack_status, msg def list_stack(profile=None): ''' Return a list of available stack (heat stack-list) profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.list_stack profile=openstack1 ''' ret = {} h_client = _auth(profile) for stack in h_client.stacks.list(): links = {} for link in stack.links: links[link['rel']] = link['href'] ret[stack.stack_name] = { 'status': stack.stack_status, 'id': stack.id, 'name': stack.stack_name, 'creation': stack.creation_time, 'owner': stack.stack_owner, 'reason': stack.stack_status_reason, 'links': links, } return ret def delete_stack(name=None, poll=0, timeout=60, profile=None): ''' Delete a stack (heat stack-delete) name Name of the stack poll Poll and report events until stack complete timeout Stack creation timeout in minute profile Profile to use CLI Examples: .. code-block:: bash salt '*' heat.delete_stack name=mystack poll=5 \\ profile=openstack1 ''' h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not name: ret['result'] = False ret['comment'] = 'Parameter name missing or None' return ret try: h_client.stacks.delete(name) except heatclient.exc.HTTPNotFound: ret['result'] = False ret['comment'] = 'No stack {0}'.format(name) except heatclient.exc.HTTPForbidden as forbidden: log.exception(forbidden) ret['result'] = False ret['comment'] = six.text_type(forbidden) if ret['result'] is False: return ret if poll > 0: try: stack_status, msg = _poll_for_events(h_client, name, action='DELETE', poll_period=poll, timeout=timeout) except heatclient.exc.CommandError: ret['comment'] = 'Deleted stack {0}.'.format(name) return ret except Exception as ex: # pylint: disable=W0703 log.exception('Delete failed %s', ex) ret['result'] = False ret['comment'] = '{0}'.format(ex) return ret if stack_status == 'DELETE_FAILED': ret['result'] = False ret['comment'] = 'Deleted stack FAILED\'{0}\'{1}.'.format(name, msg) else: ret['comment'] = 'Deleted stack {0}.'.format(name) return ret def create_stack(name=None, template_file=None, environment=None, parameters=None, poll=0, rollback=False, timeout=60, profile=None, enviroment=None): ''' Create a stack (heat stack-create) name Name of the new stack template_file File of template environment File of environment parameters Parameter dict used to create the stack poll Poll and report events until stack complete rollback Enable rollback on create failure timeout Stack creation timeout in minutes profile Profile to build on CLI Example: .. code-block:: bash salt '*' heat.create_stack name=mystack \\ template_file=salt://template.yaml \\ environment=salt://environment.yaml \\ parameters="{"image": "Debian 8", "flavor": "m1.small"}" \\ poll=5 rollback=False timeout=60 profile=openstack1 .. versionadded:: 2017.7.5,2018.3.1 The spelling mistake in parameter `enviroment` was corrected to `environment`. The misspelled version is still supported for backward compatibility, but will be removed in Salt Neon. ''' if environment is None and enviroment is not None: salt.utils.versions.warn_until('Neon', ( "Please use the 'environment' parameter instead of the misspelled 'enviroment' " "parameter which will be removed in Salt Neon." )) environment = enviroment h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not parameters: parameters = {} if template_file: template_tmp_file = salt.utils.files.mkstemp() tsfn, source_sum, comment_ = __salt__['file.get_managed']( name=template_tmp_file, template=None, source=template_file, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) template_manage_result = __salt__['file.manage_file']( name=template_tmp_file, sfn=tsfn, ret=None, source=template_file, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if template_manage_result['result']: with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_: tpl = salt.utils.stringutils.to_unicode(tfp_.read()) salt.utils.files.safe_rm(template_tmp_file) try: template = _parse_template(tpl) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open template: {0} {1}'.format(template_file, comment_) else: ret['result'] = False ret['comment'] = 'Can not open template' if ret['result'] is False: return ret kwargs = {} kwargs['template'] = template try: h_client.stacks.validate(**kwargs) except Exception as ex: log.exception('Template not valid') ret['result'] = False ret['comment'] = 'Template not valid: {0}'.format(ex) return ret env = {} if environment: environment_tmp_file = salt.utils.files.mkstemp() esfn, source_sum, comment_ = __salt__['file.get_managed']( name=environment_tmp_file, template=None, source=environment, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) environment_manage_result = __salt__['file.manage_file']( name=environment_tmp_file, sfn=esfn, ret=None, source=environment, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if environment_manage_result['result']: with salt.utils.files.fopen(environment_tmp_file, 'r') as efp_: env_str = salt.utils.stringutils.to_unicode(efp_.read()) salt.utils.files.safe_rm(environment_tmp_file) try: env = _parse_environment(env_str) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open environment: {0}, {1}'.format(environment, comment_) if ret['result'] is False: return ret fields = { 'stack_name': name, 'disable_rollback': not rollback, 'parameters': parameters, 'template': template, 'environment': env, 'timeout_mins': timeout } # If one or more environments is found, pass the listing to the server try: h_client.stacks.create(**fields) except Exception as ex: # pylint: disable=W0703 log.exception('Create failed') ret['result'] = False ret['comment'] = six.text_type(ex) return ret if poll > 0: stack_status, msg = _poll_for_events(h_client, name, action='CREATE', poll_period=poll, timeout=timeout) if stack_status == 'CREATE_FAILED': ret['result'] = False ret['comment'] = 'Created stack FAILED\'{0}\'{1}.'.format(name, msg) if ret['result'] is True: ret['comment'] = 'Created stack \'{0}\'.'.format(name) return ret def update_stack(name=None, template_file=None, environment=None, parameters=None, poll=0, rollback=False, timeout=60, profile=None, enviroment=None): ''' Update a stack (heat stack-template) name Name of the stack template_file File of template environment File of environment parameters Parameter dict used to update the stack poll Poll and report events until stack complete rollback Enable rollback on update failure timeout Stack creation timeout in minutes profile Profile to build on CLI Example: .. code-block:: bash salt '*' heat.update_stack name=mystack \\ template_file=salt://template.yaml \\ environment=salt://environment.yaml \\ parameters="{"image": "Debian 8", "flavor": "m1.small"}" \\ poll=5 rollback=False timeout=60 profile=openstack1 .. versionadded:: 2017.7.5,2018.3.1 The spelling mistake in parameter `enviroment` was corrected to `environment`. The misspelled version is still supported for backward compatibility, but will be removed in Salt Neon. ''' if environment is None and enviroment is not None: salt.utils.versions.warn_until('Neon', ( "Please use the 'environment' parameter instead of the misspelled 'enviroment' " "parameter which will be removed in Salt Neon." )) environment = enviroment h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not name: ret['result'] = False ret['comment'] = 'Parameter name missing or None' return ret if not parameters: parameters = {} if template_file: template_tmp_file = salt.utils.files.mkstemp() tsfn, source_sum, comment_ = __salt__['file.get_managed']( name=template_tmp_file, template=None, source=template_file, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) template_manage_result = __salt__['file.manage_file']( name=template_tmp_file, sfn=tsfn, ret=None, source=template_file, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if template_manage_result['result']: with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_: tpl = salt.utils.stringutils.to_unicode(tfp_.read()) salt.utils.files.safe_rm(template_tmp_file) try: template = _parse_template(tpl) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open template: {0} {1}'.format(template_file, comment_) else: ret['result'] = False ret['comment'] = 'Can not open template' if ret['result'] is False: return ret kwargs = {} kwargs['template'] = template try: h_client.stacks.validate(**kwargs) except Exception as ex: # pylint: disable=W0703 log.exception('Template not valid') ret['result'] = False ret['comment'] = 'Template not valid {0}'.format(ex) return ret env = {} if environment: environment_tmp_file = salt.utils.files.mkstemp() esfn, source_sum, comment_ = __salt__['file.get_managed']( name=environment_tmp_file, template=None, source=environment, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) environment_manage_result = __salt__['file.manage_file']( name=environment_tmp_file, sfn=esfn, ret=None, source=environment, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if environment_manage_result['result']: with salt.utils.files.fopen(environment_tmp_file, 'r') as efp_: env_str = salt.utils.stringutils.to_unicode(efp_.read()) salt.utils.files.safe_rm(environment_tmp_file) try: env = _parse_environment(env_str) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open environment: {0}, {1}'.format(environment, comment_) if ret['result'] is False: return ret fields = { 'disable_rollback': not rollback, 'parameters': parameters, 'template': template, 'environment': env, 'timeout_mins': timeout } try: h_client.stacks.update(name, **fields) except Exception as ex: # pylint: disable=W0703 log.exception('Update failed') ret['result'] = False ret['comment'] = 'Update failed {0}'.format(ex) return ret if poll > 0: stack_status, msg = _poll_for_events(h_client, name, action='UPDATE', poll_period=poll, timeout=timeout) if stack_status == 'UPDATE_FAILED': ret['result'] = False ret['comment'] = 'Updated stack FAILED\'{0}\'{1}.'.format(name, msg) if ret['result'] is True: ret['comment'] = 'Updated stack \'{0}\'.'.format(name), return ret def template_stack(name=None, profile=None): ''' Return template a specific stack (heat stack-template) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.template_stack name=mystack profile=openstack1 ''' h_client = _auth(profile) if not name: return { 'result': False, 'comment': 'Parameter name missing or None' } try: get_template = h_client.stacks.template(name) except heatclient.exc.HTTPNotFound: return { 'result': False, 'comment': 'No stack with {0}'.format(name) } except heatclient.exc.BadRequest: return { 'result': False, 'comment': 'Bad request fot stack {0}'.format(name) } if 'heat_template_version' in get_template: template = salt.utils.yaml.safe_dump(get_template) else: template = jsonutils.dumps(get_template, indent=2, ensure_ascii=False) checksum = __salt__['hashutil.digest'](template) ret = { 'template': template, 'result': True, 'checksum': checksum } return ret
saltstack/salt
salt/modules/heat.py
delete_stack
python
def delete_stack(name=None, poll=0, timeout=60, profile=None): ''' Delete a stack (heat stack-delete) name Name of the stack poll Poll and report events until stack complete timeout Stack creation timeout in minute profile Profile to use CLI Examples: .. code-block:: bash salt '*' heat.delete_stack name=mystack poll=5 \\ profile=openstack1 ''' h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not name: ret['result'] = False ret['comment'] = 'Parameter name missing or None' return ret try: h_client.stacks.delete(name) except heatclient.exc.HTTPNotFound: ret['result'] = False ret['comment'] = 'No stack {0}'.format(name) except heatclient.exc.HTTPForbidden as forbidden: log.exception(forbidden) ret['result'] = False ret['comment'] = six.text_type(forbidden) if ret['result'] is False: return ret if poll > 0: try: stack_status, msg = _poll_for_events(h_client, name, action='DELETE', poll_period=poll, timeout=timeout) except heatclient.exc.CommandError: ret['comment'] = 'Deleted stack {0}.'.format(name) return ret except Exception as ex: # pylint: disable=W0703 log.exception('Delete failed %s', ex) ret['result'] = False ret['comment'] = '{0}'.format(ex) return ret if stack_status == 'DELETE_FAILED': ret['result'] = False ret['comment'] = 'Deleted stack FAILED\'{0}\'{1}.'.format(name, msg) else: ret['comment'] = 'Deleted stack {0}.'.format(name) return ret
Delete a stack (heat stack-delete) name Name of the stack poll Poll and report events until stack complete timeout Stack creation timeout in minute profile Profile to use CLI Examples: .. code-block:: bash salt '*' heat.delete_stack name=mystack poll=5 \\ profile=openstack1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/heat.py#L365-L428
[ "def _auth(profile=None, api_version=1, **connection_args):\n '''\n Set up heat credentials, returns\n `heatclient.client.Client`. Optional parameter\n \"api_version\" defaults to 1.\n\n Only intended to be used within heat-enabled modules\n '''\n\n if profile:\n prefix = profile + ':keystone.'\n else:\n prefix = 'keystone.'\n\n def get(key, default=None):\n '''\n Checks connection_args, then salt-minion config,\n falls back to specified default value.\n '''\n return connection_args.get('connection_' + key,\n __salt__['config.get'](prefix + key, default))\n\n user = get('user', 'admin')\n password = get('password', None)\n tenant = get('tenant', 'admin')\n tenant_id = get('tenant_id')\n auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0')\n insecure = get('insecure', False)\n admin_token = get('token')\n region_name = get('region_name', None)\n\n if admin_token and api_version != 1 and not password:\n # If we had a password we could just\n # ignore the admin-token and move on...\n raise SaltInvocationError('Only can use keystone admin token ' +\n 'with Heat API v1')\n elif password:\n # Can't use the admin-token anyway\n kwargs = {'username': user,\n 'password': password,\n 'tenant_id': tenant_id,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'tenant_name': tenant}\n # 'insecure' keyword not supported by all v2.0 keystone clients\n # this ensures it's only passed in when defined\n if insecure:\n kwargs['insecure'] = True\n elif api_version == 1 and admin_token:\n kwargs = {'token': admin_token,\n 'auth_url': auth_url}\n else:\n raise SaltInvocationError('No credentials to authenticate with.')\n\n token = __salt__['keystone.token_get'](profile)\n kwargs['token'] = token['id']\n # This doesn't realy prevent the password to show up\n # in the minion log as keystoneclient.session is\n # logging it anyway when in debug-mode\n kwargs.pop('password')\n try:\n heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['url']\n except KeyError:\n heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['publicurl']\n heat_endpoint = heat_endpoint % token\n log.debug('Calling heatclient.client.Client(%s, %s, **%s)',\n api_version, heat_endpoint, kwargs)\n # may raise exc.HTTPUnauthorized, exc.HTTPNotFound\n # but we deal with those elsewhere\n return heatclient.client.Client(api_version, endpoint=heat_endpoint, **kwargs)\n", "def _poll_for_events(h_client, stack_name, action=None, poll_period=5,\n timeout=60, marker=None):\n '''\n Polling stack events\n '''\n if action:\n stop_status = ('{0}_FAILED'.format(action), '{0}_COMPLETE'.format(action))\n stop_check = lambda a: a in stop_status\n else:\n stop_check = lambda a: a.endswith('_COMPLETE') or a.endswith('_FAILED')\n timeout_sec = timeout * 60\n no_event_polls = 0\n msg_template = ('\\n Stack %(name)s %(status)s \\n')\n while True:\n events = _get_stack_events(h_client, stack_id=stack_name,\n event_args={'sort_dir': 'asc', 'marker': marker})\n\n if not events:\n no_event_polls += 1\n else:\n no_event_polls = 0\n # set marker to last event that was received.\n marker = getattr(events[-1], 'id', None)\n for event in events:\n # check if stack event was also received\n if getattr(event, 'resource_name', '') == stack_name:\n stack_status = getattr(event, 'resource_status', '')\n msg = msg_template % dict(\n name=stack_name, status=stack_status)\n if stop_check(stack_status):\n return stack_status, msg\n\n if no_event_polls >= 2:\n # after 2 polls with no events, fall back to a stack get\n stack = h_client.stacks.get(stack_name)\n stack_status = stack.stack_status\n msg = msg_template % dict(\n name=stack_name, status=stack_status)\n if stop_check(stack_status):\n return stack_status, msg\n # go back to event polling again\n no_event_polls = 0\n\n time.sleep(poll_period)\n timeout_sec -= poll_period\n if timeout_sec <= 0:\n stack_status = '{0}_FAILED'.format(action)\n msg = 'Timeout expired'\n return stack_status, msg\n" ]
# -*- coding: utf-8 -*- ''' Module for handling OpenStack Heat calls .. versionadded:: 2017.7.0 :depends: - heatclient Python module :configuration: This module is not usable until the user, password, tenant, and auth URL are specified either in a pillar or in the minion's config file. For example:: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.insecure: False #(optional) keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' # Optional keystone.region_name: 'RegionOne' If configuration for multiple OpenStack accounts is required, they can be set up as different configuration profiles: For example:: openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the heat functions can make use of a configuration profile by declaring it explicitly. For example:: salt '*' heat.flavor_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time import logging # Import Salt libs from salt.exceptions import SaltInvocationError from salt.ext import six import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml # pylint: disable=import-error HAS_HEAT = False try: import heatclient HAS_HEAT = True except ImportError: pass HAS_OSLO = False try: from oslo_serialization import jsonutils HAS_OSLO = True except ImportError: pass SECTIONS = ( PARAMETER_DEFAULTS, PARAMETERS, RESOURCE_REGISTRY, EVENT_SINKS) = ( 'parameter_defaults', 'parameters', 'resource_registry', 'event_sinks') logging.basicConfig(level=logging.DEBUG) log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if heat is installed on this minion. ''' if HAS_HEAT and HAS_OSLO: return 'heat' return (False, 'The heat execution module cannot be loaded: ' 'the heatclient and oslo_serialization' # 'the heatclient and keystoneclient and oslo_serialization' ' python library is not available.') __opts__ = {} def _auth(profile=None, api_version=1, **connection_args): ''' Set up heat credentials, returns `heatclient.client.Client`. Optional parameter "api_version" defaults to 1. Only intended to be used within heat-enabled modules ''' if profile: prefix = profile + ':keystone.' else: prefix = 'keystone.' def get(key, default=None): ''' Checks connection_args, then salt-minion config, falls back to specified default value. ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', None) tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0') insecure = get('insecure', False) admin_token = get('token') region_name = get('region_name', None) if admin_token and api_version != 1 and not password: # If we had a password we could just # ignore the admin-token and move on... raise SaltInvocationError('Only can use keystone admin token ' + 'with Heat API v1') elif password: # Can't use the admin-token anyway kwargs = {'username': user, 'password': password, 'tenant_id': tenant_id, 'auth_url': auth_url, 'region_name': region_name, 'tenant_name': tenant} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True elif api_version == 1 and admin_token: kwargs = {'token': admin_token, 'auth_url': auth_url} else: raise SaltInvocationError('No credentials to authenticate with.') token = __salt__['keystone.token_get'](profile) kwargs['token'] = token['id'] # This doesn't realy prevent the password to show up # in the minion log as keystoneclient.session is # logging it anyway when in debug-mode kwargs.pop('password') try: heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['url'] except KeyError: heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['publicurl'] heat_endpoint = heat_endpoint % token log.debug('Calling heatclient.client.Client(%s, %s, **%s)', api_version, heat_endpoint, kwargs) # may raise exc.HTTPUnauthorized, exc.HTTPNotFound # but we deal with those elsewhere return heatclient.client.Client(api_version, endpoint=heat_endpoint, **kwargs) def _parse_template(tmpl_str): ''' Parsing template ''' tmpl_str = tmpl_str.strip() if tmpl_str.startswith('{'): tpl = salt.utils.json.loads(tmpl_str) else: try: tpl = salt.utils.yaml.safe_load(tmpl_str) except salt.utils.yaml.YAMLError as exc: raise ValueError(six.text_type(exc)) else: if tpl is None: tpl = {} if not ('HeatTemplateFormatVersion' in tpl or 'heat_template_version' in tpl or 'AWSTemplateFormatVersion' in tpl): raise ValueError(('Template format version not found.')) return tpl def _parse_environment(env_str): ''' Parsing template ''' try: env = salt.utils.yaml.safe_load(env_str) except salt.utils.yaml.YAMLError as exc: raise ValueError(six.text_type(exc)) else: if env is None: env = {} elif not isinstance(env, dict): raise ValueError( 'The environment is not a valid YAML mapping data type.' ) for param in env: if param not in SECTIONS: raise ValueError('environment has wrong section "{0}"'.format(param)) return env def _get_stack_events(h_client, stack_id, event_args): ''' Get event for stack ''' event_args['stack_id'] = stack_id event_args['resource_name'] = None try: events = h_client.events.list(**event_args) except heatclient.exc.HTTPNotFound as exc: raise heatclient.exc.CommandError(six.text_type(exc)) else: for event in events: event.stack_name = stack_id.split('/')[0] return events def _poll_for_events(h_client, stack_name, action=None, poll_period=5, timeout=60, marker=None): ''' Polling stack events ''' if action: stop_status = ('{0}_FAILED'.format(action), '{0}_COMPLETE'.format(action)) stop_check = lambda a: a in stop_status else: stop_check = lambda a: a.endswith('_COMPLETE') or a.endswith('_FAILED') timeout_sec = timeout * 60 no_event_polls = 0 msg_template = ('\n Stack %(name)s %(status)s \n') while True: events = _get_stack_events(h_client, stack_id=stack_name, event_args={'sort_dir': 'asc', 'marker': marker}) if not events: no_event_polls += 1 else: no_event_polls = 0 # set marker to last event that was received. marker = getattr(events[-1], 'id', None) for event in events: # check if stack event was also received if getattr(event, 'resource_name', '') == stack_name: stack_status = getattr(event, 'resource_status', '') msg = msg_template % dict( name=stack_name, status=stack_status) if stop_check(stack_status): return stack_status, msg if no_event_polls >= 2: # after 2 polls with no events, fall back to a stack get stack = h_client.stacks.get(stack_name) stack_status = stack.stack_status msg = msg_template % dict( name=stack_name, status=stack_status) if stop_check(stack_status): return stack_status, msg # go back to event polling again no_event_polls = 0 time.sleep(poll_period) timeout_sec -= poll_period if timeout_sec <= 0: stack_status = '{0}_FAILED'.format(action) msg = 'Timeout expired' return stack_status, msg def list_stack(profile=None): ''' Return a list of available stack (heat stack-list) profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.list_stack profile=openstack1 ''' ret = {} h_client = _auth(profile) for stack in h_client.stacks.list(): links = {} for link in stack.links: links[link['rel']] = link['href'] ret[stack.stack_name] = { 'status': stack.stack_status, 'id': stack.id, 'name': stack.stack_name, 'creation': stack.creation_time, 'owner': stack.stack_owner, 'reason': stack.stack_status_reason, 'links': links, } return ret def show_stack(name=None, profile=None): ''' Return details about a specific stack (heat stack-show) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.show_stack name=mystack profile=openstack1 ''' h_client = _auth(profile) if not name: return { 'result': False, 'comment': 'Parameter name missing or None' } try: ret = {} stack = h_client.stacks.get(name) links = {} for link in stack.links: links[link['rel']] = link['href'] ret[stack.stack_name] = { 'status': stack.stack_status, 'id': stack.id, 'name': stack.stack_name, 'creation': stack.creation_time, 'owner': stack.stack_owner, 'reason': stack.stack_status_reason, 'parameters': stack.parameters, 'links': links, } ret['result'] = True except heatclient.exc.HTTPNotFound: return { 'result': False, 'comment': 'No stack {0}'.format(name) } return ret def create_stack(name=None, template_file=None, environment=None, parameters=None, poll=0, rollback=False, timeout=60, profile=None, enviroment=None): ''' Create a stack (heat stack-create) name Name of the new stack template_file File of template environment File of environment parameters Parameter dict used to create the stack poll Poll and report events until stack complete rollback Enable rollback on create failure timeout Stack creation timeout in minutes profile Profile to build on CLI Example: .. code-block:: bash salt '*' heat.create_stack name=mystack \\ template_file=salt://template.yaml \\ environment=salt://environment.yaml \\ parameters="{"image": "Debian 8", "flavor": "m1.small"}" \\ poll=5 rollback=False timeout=60 profile=openstack1 .. versionadded:: 2017.7.5,2018.3.1 The spelling mistake in parameter `enviroment` was corrected to `environment`. The misspelled version is still supported for backward compatibility, but will be removed in Salt Neon. ''' if environment is None and enviroment is not None: salt.utils.versions.warn_until('Neon', ( "Please use the 'environment' parameter instead of the misspelled 'enviroment' " "parameter which will be removed in Salt Neon." )) environment = enviroment h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not parameters: parameters = {} if template_file: template_tmp_file = salt.utils.files.mkstemp() tsfn, source_sum, comment_ = __salt__['file.get_managed']( name=template_tmp_file, template=None, source=template_file, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) template_manage_result = __salt__['file.manage_file']( name=template_tmp_file, sfn=tsfn, ret=None, source=template_file, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if template_manage_result['result']: with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_: tpl = salt.utils.stringutils.to_unicode(tfp_.read()) salt.utils.files.safe_rm(template_tmp_file) try: template = _parse_template(tpl) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open template: {0} {1}'.format(template_file, comment_) else: ret['result'] = False ret['comment'] = 'Can not open template' if ret['result'] is False: return ret kwargs = {} kwargs['template'] = template try: h_client.stacks.validate(**kwargs) except Exception as ex: log.exception('Template not valid') ret['result'] = False ret['comment'] = 'Template not valid: {0}'.format(ex) return ret env = {} if environment: environment_tmp_file = salt.utils.files.mkstemp() esfn, source_sum, comment_ = __salt__['file.get_managed']( name=environment_tmp_file, template=None, source=environment, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) environment_manage_result = __salt__['file.manage_file']( name=environment_tmp_file, sfn=esfn, ret=None, source=environment, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if environment_manage_result['result']: with salt.utils.files.fopen(environment_tmp_file, 'r') as efp_: env_str = salt.utils.stringutils.to_unicode(efp_.read()) salt.utils.files.safe_rm(environment_tmp_file) try: env = _parse_environment(env_str) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open environment: {0}, {1}'.format(environment, comment_) if ret['result'] is False: return ret fields = { 'stack_name': name, 'disable_rollback': not rollback, 'parameters': parameters, 'template': template, 'environment': env, 'timeout_mins': timeout } # If one or more environments is found, pass the listing to the server try: h_client.stacks.create(**fields) except Exception as ex: # pylint: disable=W0703 log.exception('Create failed') ret['result'] = False ret['comment'] = six.text_type(ex) return ret if poll > 0: stack_status, msg = _poll_for_events(h_client, name, action='CREATE', poll_period=poll, timeout=timeout) if stack_status == 'CREATE_FAILED': ret['result'] = False ret['comment'] = 'Created stack FAILED\'{0}\'{1}.'.format(name, msg) if ret['result'] is True: ret['comment'] = 'Created stack \'{0}\'.'.format(name) return ret def update_stack(name=None, template_file=None, environment=None, parameters=None, poll=0, rollback=False, timeout=60, profile=None, enviroment=None): ''' Update a stack (heat stack-template) name Name of the stack template_file File of template environment File of environment parameters Parameter dict used to update the stack poll Poll and report events until stack complete rollback Enable rollback on update failure timeout Stack creation timeout in minutes profile Profile to build on CLI Example: .. code-block:: bash salt '*' heat.update_stack name=mystack \\ template_file=salt://template.yaml \\ environment=salt://environment.yaml \\ parameters="{"image": "Debian 8", "flavor": "m1.small"}" \\ poll=5 rollback=False timeout=60 profile=openstack1 .. versionadded:: 2017.7.5,2018.3.1 The spelling mistake in parameter `enviroment` was corrected to `environment`. The misspelled version is still supported for backward compatibility, but will be removed in Salt Neon. ''' if environment is None and enviroment is not None: salt.utils.versions.warn_until('Neon', ( "Please use the 'environment' parameter instead of the misspelled 'enviroment' " "parameter which will be removed in Salt Neon." )) environment = enviroment h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not name: ret['result'] = False ret['comment'] = 'Parameter name missing or None' return ret if not parameters: parameters = {} if template_file: template_tmp_file = salt.utils.files.mkstemp() tsfn, source_sum, comment_ = __salt__['file.get_managed']( name=template_tmp_file, template=None, source=template_file, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) template_manage_result = __salt__['file.manage_file']( name=template_tmp_file, sfn=tsfn, ret=None, source=template_file, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if template_manage_result['result']: with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_: tpl = salt.utils.stringutils.to_unicode(tfp_.read()) salt.utils.files.safe_rm(template_tmp_file) try: template = _parse_template(tpl) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open template: {0} {1}'.format(template_file, comment_) else: ret['result'] = False ret['comment'] = 'Can not open template' if ret['result'] is False: return ret kwargs = {} kwargs['template'] = template try: h_client.stacks.validate(**kwargs) except Exception as ex: # pylint: disable=W0703 log.exception('Template not valid') ret['result'] = False ret['comment'] = 'Template not valid {0}'.format(ex) return ret env = {} if environment: environment_tmp_file = salt.utils.files.mkstemp() esfn, source_sum, comment_ = __salt__['file.get_managed']( name=environment_tmp_file, template=None, source=environment, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) environment_manage_result = __salt__['file.manage_file']( name=environment_tmp_file, sfn=esfn, ret=None, source=environment, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if environment_manage_result['result']: with salt.utils.files.fopen(environment_tmp_file, 'r') as efp_: env_str = salt.utils.stringutils.to_unicode(efp_.read()) salt.utils.files.safe_rm(environment_tmp_file) try: env = _parse_environment(env_str) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open environment: {0}, {1}'.format(environment, comment_) if ret['result'] is False: return ret fields = { 'disable_rollback': not rollback, 'parameters': parameters, 'template': template, 'environment': env, 'timeout_mins': timeout } try: h_client.stacks.update(name, **fields) except Exception as ex: # pylint: disable=W0703 log.exception('Update failed') ret['result'] = False ret['comment'] = 'Update failed {0}'.format(ex) return ret if poll > 0: stack_status, msg = _poll_for_events(h_client, name, action='UPDATE', poll_period=poll, timeout=timeout) if stack_status == 'UPDATE_FAILED': ret['result'] = False ret['comment'] = 'Updated stack FAILED\'{0}\'{1}.'.format(name, msg) if ret['result'] is True: ret['comment'] = 'Updated stack \'{0}\'.'.format(name), return ret def template_stack(name=None, profile=None): ''' Return template a specific stack (heat stack-template) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.template_stack name=mystack profile=openstack1 ''' h_client = _auth(profile) if not name: return { 'result': False, 'comment': 'Parameter name missing or None' } try: get_template = h_client.stacks.template(name) except heatclient.exc.HTTPNotFound: return { 'result': False, 'comment': 'No stack with {0}'.format(name) } except heatclient.exc.BadRequest: return { 'result': False, 'comment': 'Bad request fot stack {0}'.format(name) } if 'heat_template_version' in get_template: template = salt.utils.yaml.safe_dump(get_template) else: template = jsonutils.dumps(get_template, indent=2, ensure_ascii=False) checksum = __salt__['hashutil.digest'](template) ret = { 'template': template, 'result': True, 'checksum': checksum } return ret
saltstack/salt
salt/modules/heat.py
create_stack
python
def create_stack(name=None, template_file=None, environment=None, parameters=None, poll=0, rollback=False, timeout=60, profile=None, enviroment=None): ''' Create a stack (heat stack-create) name Name of the new stack template_file File of template environment File of environment parameters Parameter dict used to create the stack poll Poll and report events until stack complete rollback Enable rollback on create failure timeout Stack creation timeout in minutes profile Profile to build on CLI Example: .. code-block:: bash salt '*' heat.create_stack name=mystack \\ template_file=salt://template.yaml \\ environment=salt://environment.yaml \\ parameters="{"image": "Debian 8", "flavor": "m1.small"}" \\ poll=5 rollback=False timeout=60 profile=openstack1 .. versionadded:: 2017.7.5,2018.3.1 The spelling mistake in parameter `enviroment` was corrected to `environment`. The misspelled version is still supported for backward compatibility, but will be removed in Salt Neon. ''' if environment is None and enviroment is not None: salt.utils.versions.warn_until('Neon', ( "Please use the 'environment' parameter instead of the misspelled 'enviroment' " "parameter which will be removed in Salt Neon." )) environment = enviroment h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not parameters: parameters = {} if template_file: template_tmp_file = salt.utils.files.mkstemp() tsfn, source_sum, comment_ = __salt__['file.get_managed']( name=template_tmp_file, template=None, source=template_file, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) template_manage_result = __salt__['file.manage_file']( name=template_tmp_file, sfn=tsfn, ret=None, source=template_file, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if template_manage_result['result']: with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_: tpl = salt.utils.stringutils.to_unicode(tfp_.read()) salt.utils.files.safe_rm(template_tmp_file) try: template = _parse_template(tpl) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open template: {0} {1}'.format(template_file, comment_) else: ret['result'] = False ret['comment'] = 'Can not open template' if ret['result'] is False: return ret kwargs = {} kwargs['template'] = template try: h_client.stacks.validate(**kwargs) except Exception as ex: log.exception('Template not valid') ret['result'] = False ret['comment'] = 'Template not valid: {0}'.format(ex) return ret env = {} if environment: environment_tmp_file = salt.utils.files.mkstemp() esfn, source_sum, comment_ = __salt__['file.get_managed']( name=environment_tmp_file, template=None, source=environment, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) environment_manage_result = __salt__['file.manage_file']( name=environment_tmp_file, sfn=esfn, ret=None, source=environment, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if environment_manage_result['result']: with salt.utils.files.fopen(environment_tmp_file, 'r') as efp_: env_str = salt.utils.stringutils.to_unicode(efp_.read()) salt.utils.files.safe_rm(environment_tmp_file) try: env = _parse_environment(env_str) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open environment: {0}, {1}'.format(environment, comment_) if ret['result'] is False: return ret fields = { 'stack_name': name, 'disable_rollback': not rollback, 'parameters': parameters, 'template': template, 'environment': env, 'timeout_mins': timeout } # If one or more environments is found, pass the listing to the server try: h_client.stacks.create(**fields) except Exception as ex: # pylint: disable=W0703 log.exception('Create failed') ret['result'] = False ret['comment'] = six.text_type(ex) return ret if poll > 0: stack_status, msg = _poll_for_events(h_client, name, action='CREATE', poll_period=poll, timeout=timeout) if stack_status == 'CREATE_FAILED': ret['result'] = False ret['comment'] = 'Created stack FAILED\'{0}\'{1}.'.format(name, msg) if ret['result'] is True: ret['comment'] = 'Created stack \'{0}\'.'.format(name) return ret
Create a stack (heat stack-create) name Name of the new stack template_file File of template environment File of environment parameters Parameter dict used to create the stack poll Poll and report events until stack complete rollback Enable rollback on create failure timeout Stack creation timeout in minutes profile Profile to build on CLI Example: .. code-block:: bash salt '*' heat.create_stack name=mystack \\ template_file=salt://template.yaml \\ environment=salt://environment.yaml \\ parameters="{"image": "Debian 8", "flavor": "m1.small"}" \\ poll=5 rollback=False timeout=60 profile=openstack1 .. versionadded:: 2017.7.5,2018.3.1 The spelling mistake in parameter `enviroment` was corrected to `environment`. The misspelled version is still supported for backward compatibility, but will be removed in Salt Neon.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/heat.py#L431-L623
[ "def mkstemp(*args, **kwargs):\n '''\n Helper function which does exactly what ``tempfile.mkstemp()`` does but\n accepts another argument, ``close_fd``, which, by default, is true and closes\n the fd before returning the file path. Something commonly done throughout\n Salt's code.\n '''\n if 'prefix' not in kwargs:\n kwargs['prefix'] = '__salt.tmp.'\n close_fd = kwargs.pop('close_fd', True)\n fd_, f_path = tempfile.mkstemp(*args, **kwargs)\n if close_fd is False:\n return fd_, f_path\n os.close(fd_)\n del fd_\n return f_path\n", "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n", "def warn_until(version,\n message,\n category=DeprecationWarning,\n stacklevel=None,\n _version_info_=None,\n _dont_call_warnings=False):\n '''\n Helper function to raise a warning, by default, a ``DeprecationWarning``,\n until the provided ``version``, after which, a ``RuntimeError`` will\n be raised to remind the developers to remove the warning because the\n target version has been reached.\n\n :param version: The version info or name after which the warning becomes a\n ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen``\n or an instance of :class:`salt.version.SaltStackVersion`.\n :param message: The warning message to be displayed.\n :param category: The warning class to be thrown, by default\n ``DeprecationWarning``\n :param stacklevel: There should be no need to set the value of\n ``stacklevel``. Salt should be able to do the right thing.\n :param _version_info_: In order to reuse this function for other SaltStack\n projects, they need to be able to provide the\n version info to compare to.\n :param _dont_call_warnings: This parameter is used just to get the\n functionality until the actual error is to be\n issued. When we're only after the salt version\n checks to raise a ``RuntimeError``.\n '''\n if not isinstance(version, (tuple,\n six.string_types,\n salt.version.SaltStackVersion)):\n raise RuntimeError(\n 'The \\'version\\' argument should be passed as a tuple, string or '\n 'an instance of \\'salt.version.SaltStackVersion\\'.'\n )\n elif isinstance(version, tuple):\n version = salt.version.SaltStackVersion(*version)\n elif isinstance(version, six.string_types):\n version = salt.version.SaltStackVersion.from_name(version)\n\n if stacklevel is None:\n # Attribute the warning to the calling function, not to warn_until()\n stacklevel = 2\n\n if _version_info_ is None:\n _version_info_ = salt.version.__version_info__\n\n _version_ = salt.version.SaltStackVersion(*_version_info_)\n\n if _version_ >= version:\n import inspect\n caller = inspect.getframeinfo(sys._getframe(stacklevel - 1))\n raise RuntimeError(\n 'The warning triggered on filename \\'{filename}\\', line number '\n '{lineno}, is supposed to be shown until version '\n '{until_version} is released. Current version is now '\n '{salt_version}. Please remove the warning.'.format(\n filename=caller.filename,\n lineno=caller.lineno,\n until_version=version.formatted_version,\n salt_version=_version_.formatted_version\n ),\n )\n\n if _dont_call_warnings is False:\n def _formatwarning(message,\n category,\n filename,\n lineno,\n line=None): # pylint: disable=W0613\n '''\n Replacement for warnings.formatwarning that disables the echoing of\n the 'line' parameter.\n '''\n return '{0}:{1}: {2}: {3}\\n'.format(\n filename, lineno, category.__name__, message\n )\n saved = warnings.formatwarning\n warnings.formatwarning = _formatwarning\n warnings.warn(\n message.format(version=version.formatted_version),\n category,\n stacklevel=stacklevel\n )\n warnings.formatwarning = saved\n", "def safe_rm(tgt):\n '''\n Safely remove a file\n '''\n try:\n os.remove(tgt)\n except (IOError, OSError):\n pass\n", "def _auth(profile=None, api_version=1, **connection_args):\n '''\n Set up heat credentials, returns\n `heatclient.client.Client`. Optional parameter\n \"api_version\" defaults to 1.\n\n Only intended to be used within heat-enabled modules\n '''\n\n if profile:\n prefix = profile + ':keystone.'\n else:\n prefix = 'keystone.'\n\n def get(key, default=None):\n '''\n Checks connection_args, then salt-minion config,\n falls back to specified default value.\n '''\n return connection_args.get('connection_' + key,\n __salt__['config.get'](prefix + key, default))\n\n user = get('user', 'admin')\n password = get('password', None)\n tenant = get('tenant', 'admin')\n tenant_id = get('tenant_id')\n auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0')\n insecure = get('insecure', False)\n admin_token = get('token')\n region_name = get('region_name', None)\n\n if admin_token and api_version != 1 and not password:\n # If we had a password we could just\n # ignore the admin-token and move on...\n raise SaltInvocationError('Only can use keystone admin token ' +\n 'with Heat API v1')\n elif password:\n # Can't use the admin-token anyway\n kwargs = {'username': user,\n 'password': password,\n 'tenant_id': tenant_id,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'tenant_name': tenant}\n # 'insecure' keyword not supported by all v2.0 keystone clients\n # this ensures it's only passed in when defined\n if insecure:\n kwargs['insecure'] = True\n elif api_version == 1 and admin_token:\n kwargs = {'token': admin_token,\n 'auth_url': auth_url}\n else:\n raise SaltInvocationError('No credentials to authenticate with.')\n\n token = __salt__['keystone.token_get'](profile)\n kwargs['token'] = token['id']\n # This doesn't realy prevent the password to show up\n # in the minion log as keystoneclient.session is\n # logging it anyway when in debug-mode\n kwargs.pop('password')\n try:\n heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['url']\n except KeyError:\n heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['publicurl']\n heat_endpoint = heat_endpoint % token\n log.debug('Calling heatclient.client.Client(%s, %s, **%s)',\n api_version, heat_endpoint, kwargs)\n # may raise exc.HTTPUnauthorized, exc.HTTPNotFound\n # but we deal with those elsewhere\n return heatclient.client.Client(api_version, endpoint=heat_endpoint, **kwargs)\n", "def _parse_template(tmpl_str):\n '''\n Parsing template\n '''\n tmpl_str = tmpl_str.strip()\n if tmpl_str.startswith('{'):\n tpl = salt.utils.json.loads(tmpl_str)\n else:\n try:\n tpl = salt.utils.yaml.safe_load(tmpl_str)\n except salt.utils.yaml.YAMLError as exc:\n raise ValueError(six.text_type(exc))\n else:\n if tpl is None:\n tpl = {}\n if not ('HeatTemplateFormatVersion' in tpl\n or 'heat_template_version' in tpl\n or 'AWSTemplateFormatVersion' in tpl):\n raise ValueError(('Template format version not found.'))\n return tpl\n", "def _parse_environment(env_str):\n '''\n Parsing template\n '''\n try:\n env = salt.utils.yaml.safe_load(env_str)\n except salt.utils.yaml.YAMLError as exc:\n raise ValueError(six.text_type(exc))\n else:\n if env is None:\n env = {}\n elif not isinstance(env, dict):\n raise ValueError(\n 'The environment is not a valid YAML mapping data type.'\n )\n\n for param in env:\n if param not in SECTIONS:\n raise ValueError('environment has wrong section \"{0}\"'.format(param))\n\n return env\n", "def _poll_for_events(h_client, stack_name, action=None, poll_period=5,\n timeout=60, marker=None):\n '''\n Polling stack events\n '''\n if action:\n stop_status = ('{0}_FAILED'.format(action), '{0}_COMPLETE'.format(action))\n stop_check = lambda a: a in stop_status\n else:\n stop_check = lambda a: a.endswith('_COMPLETE') or a.endswith('_FAILED')\n timeout_sec = timeout * 60\n no_event_polls = 0\n msg_template = ('\\n Stack %(name)s %(status)s \\n')\n while True:\n events = _get_stack_events(h_client, stack_id=stack_name,\n event_args={'sort_dir': 'asc', 'marker': marker})\n\n if not events:\n no_event_polls += 1\n else:\n no_event_polls = 0\n # set marker to last event that was received.\n marker = getattr(events[-1], 'id', None)\n for event in events:\n # check if stack event was also received\n if getattr(event, 'resource_name', '') == stack_name:\n stack_status = getattr(event, 'resource_status', '')\n msg = msg_template % dict(\n name=stack_name, status=stack_status)\n if stop_check(stack_status):\n return stack_status, msg\n\n if no_event_polls >= 2:\n # after 2 polls with no events, fall back to a stack get\n stack = h_client.stacks.get(stack_name)\n stack_status = stack.stack_status\n msg = msg_template % dict(\n name=stack_name, status=stack_status)\n if stop_check(stack_status):\n return stack_status, msg\n # go back to event polling again\n no_event_polls = 0\n\n time.sleep(poll_period)\n timeout_sec -= poll_period\n if timeout_sec <= 0:\n stack_status = '{0}_FAILED'.format(action)\n msg = 'Timeout expired'\n return stack_status, msg\n" ]
# -*- coding: utf-8 -*- ''' Module for handling OpenStack Heat calls .. versionadded:: 2017.7.0 :depends: - heatclient Python module :configuration: This module is not usable until the user, password, tenant, and auth URL are specified either in a pillar or in the minion's config file. For example:: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.insecure: False #(optional) keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' # Optional keystone.region_name: 'RegionOne' If configuration for multiple OpenStack accounts is required, they can be set up as different configuration profiles: For example:: openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the heat functions can make use of a configuration profile by declaring it explicitly. For example:: salt '*' heat.flavor_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time import logging # Import Salt libs from salt.exceptions import SaltInvocationError from salt.ext import six import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml # pylint: disable=import-error HAS_HEAT = False try: import heatclient HAS_HEAT = True except ImportError: pass HAS_OSLO = False try: from oslo_serialization import jsonutils HAS_OSLO = True except ImportError: pass SECTIONS = ( PARAMETER_DEFAULTS, PARAMETERS, RESOURCE_REGISTRY, EVENT_SINKS) = ( 'parameter_defaults', 'parameters', 'resource_registry', 'event_sinks') logging.basicConfig(level=logging.DEBUG) log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if heat is installed on this minion. ''' if HAS_HEAT and HAS_OSLO: return 'heat' return (False, 'The heat execution module cannot be loaded: ' 'the heatclient and oslo_serialization' # 'the heatclient and keystoneclient and oslo_serialization' ' python library is not available.') __opts__ = {} def _auth(profile=None, api_version=1, **connection_args): ''' Set up heat credentials, returns `heatclient.client.Client`. Optional parameter "api_version" defaults to 1. Only intended to be used within heat-enabled modules ''' if profile: prefix = profile + ':keystone.' else: prefix = 'keystone.' def get(key, default=None): ''' Checks connection_args, then salt-minion config, falls back to specified default value. ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', None) tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0') insecure = get('insecure', False) admin_token = get('token') region_name = get('region_name', None) if admin_token and api_version != 1 and not password: # If we had a password we could just # ignore the admin-token and move on... raise SaltInvocationError('Only can use keystone admin token ' + 'with Heat API v1') elif password: # Can't use the admin-token anyway kwargs = {'username': user, 'password': password, 'tenant_id': tenant_id, 'auth_url': auth_url, 'region_name': region_name, 'tenant_name': tenant} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True elif api_version == 1 and admin_token: kwargs = {'token': admin_token, 'auth_url': auth_url} else: raise SaltInvocationError('No credentials to authenticate with.') token = __salt__['keystone.token_get'](profile) kwargs['token'] = token['id'] # This doesn't realy prevent the password to show up # in the minion log as keystoneclient.session is # logging it anyway when in debug-mode kwargs.pop('password') try: heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['url'] except KeyError: heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['publicurl'] heat_endpoint = heat_endpoint % token log.debug('Calling heatclient.client.Client(%s, %s, **%s)', api_version, heat_endpoint, kwargs) # may raise exc.HTTPUnauthorized, exc.HTTPNotFound # but we deal with those elsewhere return heatclient.client.Client(api_version, endpoint=heat_endpoint, **kwargs) def _parse_template(tmpl_str): ''' Parsing template ''' tmpl_str = tmpl_str.strip() if tmpl_str.startswith('{'): tpl = salt.utils.json.loads(tmpl_str) else: try: tpl = salt.utils.yaml.safe_load(tmpl_str) except salt.utils.yaml.YAMLError as exc: raise ValueError(six.text_type(exc)) else: if tpl is None: tpl = {} if not ('HeatTemplateFormatVersion' in tpl or 'heat_template_version' in tpl or 'AWSTemplateFormatVersion' in tpl): raise ValueError(('Template format version not found.')) return tpl def _parse_environment(env_str): ''' Parsing template ''' try: env = salt.utils.yaml.safe_load(env_str) except salt.utils.yaml.YAMLError as exc: raise ValueError(six.text_type(exc)) else: if env is None: env = {} elif not isinstance(env, dict): raise ValueError( 'The environment is not a valid YAML mapping data type.' ) for param in env: if param not in SECTIONS: raise ValueError('environment has wrong section "{0}"'.format(param)) return env def _get_stack_events(h_client, stack_id, event_args): ''' Get event for stack ''' event_args['stack_id'] = stack_id event_args['resource_name'] = None try: events = h_client.events.list(**event_args) except heatclient.exc.HTTPNotFound as exc: raise heatclient.exc.CommandError(six.text_type(exc)) else: for event in events: event.stack_name = stack_id.split('/')[0] return events def _poll_for_events(h_client, stack_name, action=None, poll_period=5, timeout=60, marker=None): ''' Polling stack events ''' if action: stop_status = ('{0}_FAILED'.format(action), '{0}_COMPLETE'.format(action)) stop_check = lambda a: a in stop_status else: stop_check = lambda a: a.endswith('_COMPLETE') or a.endswith('_FAILED') timeout_sec = timeout * 60 no_event_polls = 0 msg_template = ('\n Stack %(name)s %(status)s \n') while True: events = _get_stack_events(h_client, stack_id=stack_name, event_args={'sort_dir': 'asc', 'marker': marker}) if not events: no_event_polls += 1 else: no_event_polls = 0 # set marker to last event that was received. marker = getattr(events[-1], 'id', None) for event in events: # check if stack event was also received if getattr(event, 'resource_name', '') == stack_name: stack_status = getattr(event, 'resource_status', '') msg = msg_template % dict( name=stack_name, status=stack_status) if stop_check(stack_status): return stack_status, msg if no_event_polls >= 2: # after 2 polls with no events, fall back to a stack get stack = h_client.stacks.get(stack_name) stack_status = stack.stack_status msg = msg_template % dict( name=stack_name, status=stack_status) if stop_check(stack_status): return stack_status, msg # go back to event polling again no_event_polls = 0 time.sleep(poll_period) timeout_sec -= poll_period if timeout_sec <= 0: stack_status = '{0}_FAILED'.format(action) msg = 'Timeout expired' return stack_status, msg def list_stack(profile=None): ''' Return a list of available stack (heat stack-list) profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.list_stack profile=openstack1 ''' ret = {} h_client = _auth(profile) for stack in h_client.stacks.list(): links = {} for link in stack.links: links[link['rel']] = link['href'] ret[stack.stack_name] = { 'status': stack.stack_status, 'id': stack.id, 'name': stack.stack_name, 'creation': stack.creation_time, 'owner': stack.stack_owner, 'reason': stack.stack_status_reason, 'links': links, } return ret def show_stack(name=None, profile=None): ''' Return details about a specific stack (heat stack-show) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.show_stack name=mystack profile=openstack1 ''' h_client = _auth(profile) if not name: return { 'result': False, 'comment': 'Parameter name missing or None' } try: ret = {} stack = h_client.stacks.get(name) links = {} for link in stack.links: links[link['rel']] = link['href'] ret[stack.stack_name] = { 'status': stack.stack_status, 'id': stack.id, 'name': stack.stack_name, 'creation': stack.creation_time, 'owner': stack.stack_owner, 'reason': stack.stack_status_reason, 'parameters': stack.parameters, 'links': links, } ret['result'] = True except heatclient.exc.HTTPNotFound: return { 'result': False, 'comment': 'No stack {0}'.format(name) } return ret def delete_stack(name=None, poll=0, timeout=60, profile=None): ''' Delete a stack (heat stack-delete) name Name of the stack poll Poll and report events until stack complete timeout Stack creation timeout in minute profile Profile to use CLI Examples: .. code-block:: bash salt '*' heat.delete_stack name=mystack poll=5 \\ profile=openstack1 ''' h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not name: ret['result'] = False ret['comment'] = 'Parameter name missing or None' return ret try: h_client.stacks.delete(name) except heatclient.exc.HTTPNotFound: ret['result'] = False ret['comment'] = 'No stack {0}'.format(name) except heatclient.exc.HTTPForbidden as forbidden: log.exception(forbidden) ret['result'] = False ret['comment'] = six.text_type(forbidden) if ret['result'] is False: return ret if poll > 0: try: stack_status, msg = _poll_for_events(h_client, name, action='DELETE', poll_period=poll, timeout=timeout) except heatclient.exc.CommandError: ret['comment'] = 'Deleted stack {0}.'.format(name) return ret except Exception as ex: # pylint: disable=W0703 log.exception('Delete failed %s', ex) ret['result'] = False ret['comment'] = '{0}'.format(ex) return ret if stack_status == 'DELETE_FAILED': ret['result'] = False ret['comment'] = 'Deleted stack FAILED\'{0}\'{1}.'.format(name, msg) else: ret['comment'] = 'Deleted stack {0}.'.format(name) return ret def update_stack(name=None, template_file=None, environment=None, parameters=None, poll=0, rollback=False, timeout=60, profile=None, enviroment=None): ''' Update a stack (heat stack-template) name Name of the stack template_file File of template environment File of environment parameters Parameter dict used to update the stack poll Poll and report events until stack complete rollback Enable rollback on update failure timeout Stack creation timeout in minutes profile Profile to build on CLI Example: .. code-block:: bash salt '*' heat.update_stack name=mystack \\ template_file=salt://template.yaml \\ environment=salt://environment.yaml \\ parameters="{"image": "Debian 8", "flavor": "m1.small"}" \\ poll=5 rollback=False timeout=60 profile=openstack1 .. versionadded:: 2017.7.5,2018.3.1 The spelling mistake in parameter `enviroment` was corrected to `environment`. The misspelled version is still supported for backward compatibility, but will be removed in Salt Neon. ''' if environment is None and enviroment is not None: salt.utils.versions.warn_until('Neon', ( "Please use the 'environment' parameter instead of the misspelled 'enviroment' " "parameter which will be removed in Salt Neon." )) environment = enviroment h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not name: ret['result'] = False ret['comment'] = 'Parameter name missing or None' return ret if not parameters: parameters = {} if template_file: template_tmp_file = salt.utils.files.mkstemp() tsfn, source_sum, comment_ = __salt__['file.get_managed']( name=template_tmp_file, template=None, source=template_file, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) template_manage_result = __salt__['file.manage_file']( name=template_tmp_file, sfn=tsfn, ret=None, source=template_file, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if template_manage_result['result']: with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_: tpl = salt.utils.stringutils.to_unicode(tfp_.read()) salt.utils.files.safe_rm(template_tmp_file) try: template = _parse_template(tpl) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open template: {0} {1}'.format(template_file, comment_) else: ret['result'] = False ret['comment'] = 'Can not open template' if ret['result'] is False: return ret kwargs = {} kwargs['template'] = template try: h_client.stacks.validate(**kwargs) except Exception as ex: # pylint: disable=W0703 log.exception('Template not valid') ret['result'] = False ret['comment'] = 'Template not valid {0}'.format(ex) return ret env = {} if environment: environment_tmp_file = salt.utils.files.mkstemp() esfn, source_sum, comment_ = __salt__['file.get_managed']( name=environment_tmp_file, template=None, source=environment, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) environment_manage_result = __salt__['file.manage_file']( name=environment_tmp_file, sfn=esfn, ret=None, source=environment, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if environment_manage_result['result']: with salt.utils.files.fopen(environment_tmp_file, 'r') as efp_: env_str = salt.utils.stringutils.to_unicode(efp_.read()) salt.utils.files.safe_rm(environment_tmp_file) try: env = _parse_environment(env_str) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open environment: {0}, {1}'.format(environment, comment_) if ret['result'] is False: return ret fields = { 'disable_rollback': not rollback, 'parameters': parameters, 'template': template, 'environment': env, 'timeout_mins': timeout } try: h_client.stacks.update(name, **fields) except Exception as ex: # pylint: disable=W0703 log.exception('Update failed') ret['result'] = False ret['comment'] = 'Update failed {0}'.format(ex) return ret if poll > 0: stack_status, msg = _poll_for_events(h_client, name, action='UPDATE', poll_period=poll, timeout=timeout) if stack_status == 'UPDATE_FAILED': ret['result'] = False ret['comment'] = 'Updated stack FAILED\'{0}\'{1}.'.format(name, msg) if ret['result'] is True: ret['comment'] = 'Updated stack \'{0}\'.'.format(name), return ret def template_stack(name=None, profile=None): ''' Return template a specific stack (heat stack-template) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.template_stack name=mystack profile=openstack1 ''' h_client = _auth(profile) if not name: return { 'result': False, 'comment': 'Parameter name missing or None' } try: get_template = h_client.stacks.template(name) except heatclient.exc.HTTPNotFound: return { 'result': False, 'comment': 'No stack with {0}'.format(name) } except heatclient.exc.BadRequest: return { 'result': False, 'comment': 'Bad request fot stack {0}'.format(name) } if 'heat_template_version' in get_template: template = salt.utils.yaml.safe_dump(get_template) else: template = jsonutils.dumps(get_template, indent=2, ensure_ascii=False) checksum = __salt__['hashutil.digest'](template) ret = { 'template': template, 'result': True, 'checksum': checksum } return ret
saltstack/salt
salt/modules/heat.py
template_stack
python
def template_stack(name=None, profile=None): ''' Return template a specific stack (heat stack-template) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.template_stack name=mystack profile=openstack1 ''' h_client = _auth(profile) if not name: return { 'result': False, 'comment': 'Parameter name missing or None' } try: get_template = h_client.stacks.template(name) except heatclient.exc.HTTPNotFound: return { 'result': False, 'comment': 'No stack with {0}'.format(name) } except heatclient.exc.BadRequest: return { 'result': False, 'comment': 'Bad request fot stack {0}'.format(name) } if 'heat_template_version' in get_template: template = salt.utils.yaml.safe_dump(get_template) else: template = jsonutils.dumps(get_template, indent=2, ensure_ascii=False) checksum = __salt__['hashutil.digest'](template) ret = { 'template': template, 'result': True, 'checksum': checksum } return ret
Return template a specific stack (heat stack-template) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.template_stack name=mystack profile=openstack1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/heat.py#L824-L871
[ "def safe_dump(data, stream=None, **kwargs):\n '''\n Use a custom dumper to ensure that defaultdict and OrderedDict are\n represented properly. Ensure that unicode strings are encoded unless\n explicitly told not to.\n '''\n if 'allow_unicode' not in kwargs:\n kwargs['allow_unicode'] = True\n return yaml.dump(data, stream, Dumper=SafeOrderedDumper, **kwargs)\n", "def _auth(profile=None, api_version=1, **connection_args):\n '''\n Set up heat credentials, returns\n `heatclient.client.Client`. Optional parameter\n \"api_version\" defaults to 1.\n\n Only intended to be used within heat-enabled modules\n '''\n\n if profile:\n prefix = profile + ':keystone.'\n else:\n prefix = 'keystone.'\n\n def get(key, default=None):\n '''\n Checks connection_args, then salt-minion config,\n falls back to specified default value.\n '''\n return connection_args.get('connection_' + key,\n __salt__['config.get'](prefix + key, default))\n\n user = get('user', 'admin')\n password = get('password', None)\n tenant = get('tenant', 'admin')\n tenant_id = get('tenant_id')\n auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0')\n insecure = get('insecure', False)\n admin_token = get('token')\n region_name = get('region_name', None)\n\n if admin_token and api_version != 1 and not password:\n # If we had a password we could just\n # ignore the admin-token and move on...\n raise SaltInvocationError('Only can use keystone admin token ' +\n 'with Heat API v1')\n elif password:\n # Can't use the admin-token anyway\n kwargs = {'username': user,\n 'password': password,\n 'tenant_id': tenant_id,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'tenant_name': tenant}\n # 'insecure' keyword not supported by all v2.0 keystone clients\n # this ensures it's only passed in when defined\n if insecure:\n kwargs['insecure'] = True\n elif api_version == 1 and admin_token:\n kwargs = {'token': admin_token,\n 'auth_url': auth_url}\n else:\n raise SaltInvocationError('No credentials to authenticate with.')\n\n token = __salt__['keystone.token_get'](profile)\n kwargs['token'] = token['id']\n # This doesn't realy prevent the password to show up\n # in the minion log as keystoneclient.session is\n # logging it anyway when in debug-mode\n kwargs.pop('password')\n try:\n heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['url']\n except KeyError:\n heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['publicurl']\n heat_endpoint = heat_endpoint % token\n log.debug('Calling heatclient.client.Client(%s, %s, **%s)',\n api_version, heat_endpoint, kwargs)\n # may raise exc.HTTPUnauthorized, exc.HTTPNotFound\n # but we deal with those elsewhere\n return heatclient.client.Client(api_version, endpoint=heat_endpoint, **kwargs)\n" ]
# -*- coding: utf-8 -*- ''' Module for handling OpenStack Heat calls .. versionadded:: 2017.7.0 :depends: - heatclient Python module :configuration: This module is not usable until the user, password, tenant, and auth URL are specified either in a pillar or in the minion's config file. For example:: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.insecure: False #(optional) keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' # Optional keystone.region_name: 'RegionOne' If configuration for multiple OpenStack accounts is required, they can be set up as different configuration profiles: For example:: openstack1: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' openstack2: keystone.user: admin keystone.password: verybadpass keystone.tenant: admin keystone.auth_url: 'http://127.0.0.2:5000/v2.0/' With this configuration in place, any of the heat functions can make use of a configuration profile by declaring it explicitly. For example:: salt '*' heat.flavor_list profile=openstack1 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import time import logging # Import Salt libs from salt.exceptions import SaltInvocationError from salt.ext import six import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml # pylint: disable=import-error HAS_HEAT = False try: import heatclient HAS_HEAT = True except ImportError: pass HAS_OSLO = False try: from oslo_serialization import jsonutils HAS_OSLO = True except ImportError: pass SECTIONS = ( PARAMETER_DEFAULTS, PARAMETERS, RESOURCE_REGISTRY, EVENT_SINKS) = ( 'parameter_defaults', 'parameters', 'resource_registry', 'event_sinks') logging.basicConfig(level=logging.DEBUG) log = logging.getLogger(__name__) def __virtual__(): ''' Only load this module if heat is installed on this minion. ''' if HAS_HEAT and HAS_OSLO: return 'heat' return (False, 'The heat execution module cannot be loaded: ' 'the heatclient and oslo_serialization' # 'the heatclient and keystoneclient and oslo_serialization' ' python library is not available.') __opts__ = {} def _auth(profile=None, api_version=1, **connection_args): ''' Set up heat credentials, returns `heatclient.client.Client`. Optional parameter "api_version" defaults to 1. Only intended to be used within heat-enabled modules ''' if profile: prefix = profile + ':keystone.' else: prefix = 'keystone.' def get(key, default=None): ''' Checks connection_args, then salt-minion config, falls back to specified default value. ''' return connection_args.get('connection_' + key, __salt__['config.get'](prefix + key, default)) user = get('user', 'admin') password = get('password', None) tenant = get('tenant', 'admin') tenant_id = get('tenant_id') auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0') insecure = get('insecure', False) admin_token = get('token') region_name = get('region_name', None) if admin_token and api_version != 1 and not password: # If we had a password we could just # ignore the admin-token and move on... raise SaltInvocationError('Only can use keystone admin token ' + 'with Heat API v1') elif password: # Can't use the admin-token anyway kwargs = {'username': user, 'password': password, 'tenant_id': tenant_id, 'auth_url': auth_url, 'region_name': region_name, 'tenant_name': tenant} # 'insecure' keyword not supported by all v2.0 keystone clients # this ensures it's only passed in when defined if insecure: kwargs['insecure'] = True elif api_version == 1 and admin_token: kwargs = {'token': admin_token, 'auth_url': auth_url} else: raise SaltInvocationError('No credentials to authenticate with.') token = __salt__['keystone.token_get'](profile) kwargs['token'] = token['id'] # This doesn't realy prevent the password to show up # in the minion log as keystoneclient.session is # logging it anyway when in debug-mode kwargs.pop('password') try: heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['url'] except KeyError: heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['publicurl'] heat_endpoint = heat_endpoint % token log.debug('Calling heatclient.client.Client(%s, %s, **%s)', api_version, heat_endpoint, kwargs) # may raise exc.HTTPUnauthorized, exc.HTTPNotFound # but we deal with those elsewhere return heatclient.client.Client(api_version, endpoint=heat_endpoint, **kwargs) def _parse_template(tmpl_str): ''' Parsing template ''' tmpl_str = tmpl_str.strip() if tmpl_str.startswith('{'): tpl = salt.utils.json.loads(tmpl_str) else: try: tpl = salt.utils.yaml.safe_load(tmpl_str) except salt.utils.yaml.YAMLError as exc: raise ValueError(six.text_type(exc)) else: if tpl is None: tpl = {} if not ('HeatTemplateFormatVersion' in tpl or 'heat_template_version' in tpl or 'AWSTemplateFormatVersion' in tpl): raise ValueError(('Template format version not found.')) return tpl def _parse_environment(env_str): ''' Parsing template ''' try: env = salt.utils.yaml.safe_load(env_str) except salt.utils.yaml.YAMLError as exc: raise ValueError(six.text_type(exc)) else: if env is None: env = {} elif not isinstance(env, dict): raise ValueError( 'The environment is not a valid YAML mapping data type.' ) for param in env: if param not in SECTIONS: raise ValueError('environment has wrong section "{0}"'.format(param)) return env def _get_stack_events(h_client, stack_id, event_args): ''' Get event for stack ''' event_args['stack_id'] = stack_id event_args['resource_name'] = None try: events = h_client.events.list(**event_args) except heatclient.exc.HTTPNotFound as exc: raise heatclient.exc.CommandError(six.text_type(exc)) else: for event in events: event.stack_name = stack_id.split('/')[0] return events def _poll_for_events(h_client, stack_name, action=None, poll_period=5, timeout=60, marker=None): ''' Polling stack events ''' if action: stop_status = ('{0}_FAILED'.format(action), '{0}_COMPLETE'.format(action)) stop_check = lambda a: a in stop_status else: stop_check = lambda a: a.endswith('_COMPLETE') or a.endswith('_FAILED') timeout_sec = timeout * 60 no_event_polls = 0 msg_template = ('\n Stack %(name)s %(status)s \n') while True: events = _get_stack_events(h_client, stack_id=stack_name, event_args={'sort_dir': 'asc', 'marker': marker}) if not events: no_event_polls += 1 else: no_event_polls = 0 # set marker to last event that was received. marker = getattr(events[-1], 'id', None) for event in events: # check if stack event was also received if getattr(event, 'resource_name', '') == stack_name: stack_status = getattr(event, 'resource_status', '') msg = msg_template % dict( name=stack_name, status=stack_status) if stop_check(stack_status): return stack_status, msg if no_event_polls >= 2: # after 2 polls with no events, fall back to a stack get stack = h_client.stacks.get(stack_name) stack_status = stack.stack_status msg = msg_template % dict( name=stack_name, status=stack_status) if stop_check(stack_status): return stack_status, msg # go back to event polling again no_event_polls = 0 time.sleep(poll_period) timeout_sec -= poll_period if timeout_sec <= 0: stack_status = '{0}_FAILED'.format(action) msg = 'Timeout expired' return stack_status, msg def list_stack(profile=None): ''' Return a list of available stack (heat stack-list) profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.list_stack profile=openstack1 ''' ret = {} h_client = _auth(profile) for stack in h_client.stacks.list(): links = {} for link in stack.links: links[link['rel']] = link['href'] ret[stack.stack_name] = { 'status': stack.stack_status, 'id': stack.id, 'name': stack.stack_name, 'creation': stack.creation_time, 'owner': stack.stack_owner, 'reason': stack.stack_status_reason, 'links': links, } return ret def show_stack(name=None, profile=None): ''' Return details about a specific stack (heat stack-show) name Name of the stack profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.show_stack name=mystack profile=openstack1 ''' h_client = _auth(profile) if not name: return { 'result': False, 'comment': 'Parameter name missing or None' } try: ret = {} stack = h_client.stacks.get(name) links = {} for link in stack.links: links[link['rel']] = link['href'] ret[stack.stack_name] = { 'status': stack.stack_status, 'id': stack.id, 'name': stack.stack_name, 'creation': stack.creation_time, 'owner': stack.stack_owner, 'reason': stack.stack_status_reason, 'parameters': stack.parameters, 'links': links, } ret['result'] = True except heatclient.exc.HTTPNotFound: return { 'result': False, 'comment': 'No stack {0}'.format(name) } return ret def delete_stack(name=None, poll=0, timeout=60, profile=None): ''' Delete a stack (heat stack-delete) name Name of the stack poll Poll and report events until stack complete timeout Stack creation timeout in minute profile Profile to use CLI Examples: .. code-block:: bash salt '*' heat.delete_stack name=mystack poll=5 \\ profile=openstack1 ''' h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not name: ret['result'] = False ret['comment'] = 'Parameter name missing or None' return ret try: h_client.stacks.delete(name) except heatclient.exc.HTTPNotFound: ret['result'] = False ret['comment'] = 'No stack {0}'.format(name) except heatclient.exc.HTTPForbidden as forbidden: log.exception(forbidden) ret['result'] = False ret['comment'] = six.text_type(forbidden) if ret['result'] is False: return ret if poll > 0: try: stack_status, msg = _poll_for_events(h_client, name, action='DELETE', poll_period=poll, timeout=timeout) except heatclient.exc.CommandError: ret['comment'] = 'Deleted stack {0}.'.format(name) return ret except Exception as ex: # pylint: disable=W0703 log.exception('Delete failed %s', ex) ret['result'] = False ret['comment'] = '{0}'.format(ex) return ret if stack_status == 'DELETE_FAILED': ret['result'] = False ret['comment'] = 'Deleted stack FAILED\'{0}\'{1}.'.format(name, msg) else: ret['comment'] = 'Deleted stack {0}.'.format(name) return ret def create_stack(name=None, template_file=None, environment=None, parameters=None, poll=0, rollback=False, timeout=60, profile=None, enviroment=None): ''' Create a stack (heat stack-create) name Name of the new stack template_file File of template environment File of environment parameters Parameter dict used to create the stack poll Poll and report events until stack complete rollback Enable rollback on create failure timeout Stack creation timeout in minutes profile Profile to build on CLI Example: .. code-block:: bash salt '*' heat.create_stack name=mystack \\ template_file=salt://template.yaml \\ environment=salt://environment.yaml \\ parameters="{"image": "Debian 8", "flavor": "m1.small"}" \\ poll=5 rollback=False timeout=60 profile=openstack1 .. versionadded:: 2017.7.5,2018.3.1 The spelling mistake in parameter `enviroment` was corrected to `environment`. The misspelled version is still supported for backward compatibility, but will be removed in Salt Neon. ''' if environment is None and enviroment is not None: salt.utils.versions.warn_until('Neon', ( "Please use the 'environment' parameter instead of the misspelled 'enviroment' " "parameter which will be removed in Salt Neon." )) environment = enviroment h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not parameters: parameters = {} if template_file: template_tmp_file = salt.utils.files.mkstemp() tsfn, source_sum, comment_ = __salt__['file.get_managed']( name=template_tmp_file, template=None, source=template_file, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) template_manage_result = __salt__['file.manage_file']( name=template_tmp_file, sfn=tsfn, ret=None, source=template_file, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if template_manage_result['result']: with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_: tpl = salt.utils.stringutils.to_unicode(tfp_.read()) salt.utils.files.safe_rm(template_tmp_file) try: template = _parse_template(tpl) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open template: {0} {1}'.format(template_file, comment_) else: ret['result'] = False ret['comment'] = 'Can not open template' if ret['result'] is False: return ret kwargs = {} kwargs['template'] = template try: h_client.stacks.validate(**kwargs) except Exception as ex: log.exception('Template not valid') ret['result'] = False ret['comment'] = 'Template not valid: {0}'.format(ex) return ret env = {} if environment: environment_tmp_file = salt.utils.files.mkstemp() esfn, source_sum, comment_ = __salt__['file.get_managed']( name=environment_tmp_file, template=None, source=environment, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) environment_manage_result = __salt__['file.manage_file']( name=environment_tmp_file, sfn=esfn, ret=None, source=environment, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if environment_manage_result['result']: with salt.utils.files.fopen(environment_tmp_file, 'r') as efp_: env_str = salt.utils.stringutils.to_unicode(efp_.read()) salt.utils.files.safe_rm(environment_tmp_file) try: env = _parse_environment(env_str) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open environment: {0}, {1}'.format(environment, comment_) if ret['result'] is False: return ret fields = { 'stack_name': name, 'disable_rollback': not rollback, 'parameters': parameters, 'template': template, 'environment': env, 'timeout_mins': timeout } # If one or more environments is found, pass the listing to the server try: h_client.stacks.create(**fields) except Exception as ex: # pylint: disable=W0703 log.exception('Create failed') ret['result'] = False ret['comment'] = six.text_type(ex) return ret if poll > 0: stack_status, msg = _poll_for_events(h_client, name, action='CREATE', poll_period=poll, timeout=timeout) if stack_status == 'CREATE_FAILED': ret['result'] = False ret['comment'] = 'Created stack FAILED\'{0}\'{1}.'.format(name, msg) if ret['result'] is True: ret['comment'] = 'Created stack \'{0}\'.'.format(name) return ret def update_stack(name=None, template_file=None, environment=None, parameters=None, poll=0, rollback=False, timeout=60, profile=None, enviroment=None): ''' Update a stack (heat stack-template) name Name of the stack template_file File of template environment File of environment parameters Parameter dict used to update the stack poll Poll and report events until stack complete rollback Enable rollback on update failure timeout Stack creation timeout in minutes profile Profile to build on CLI Example: .. code-block:: bash salt '*' heat.update_stack name=mystack \\ template_file=salt://template.yaml \\ environment=salt://environment.yaml \\ parameters="{"image": "Debian 8", "flavor": "m1.small"}" \\ poll=5 rollback=False timeout=60 profile=openstack1 .. versionadded:: 2017.7.5,2018.3.1 The spelling mistake in parameter `enviroment` was corrected to `environment`. The misspelled version is still supported for backward compatibility, but will be removed in Salt Neon. ''' if environment is None and enviroment is not None: salt.utils.versions.warn_until('Neon', ( "Please use the 'environment' parameter instead of the misspelled 'enviroment' " "parameter which will be removed in Salt Neon." )) environment = enviroment h_client = _auth(profile) ret = { 'result': True, 'comment': '' } if not name: ret['result'] = False ret['comment'] = 'Parameter name missing or None' return ret if not parameters: parameters = {} if template_file: template_tmp_file = salt.utils.files.mkstemp() tsfn, source_sum, comment_ = __salt__['file.get_managed']( name=template_tmp_file, template=None, source=template_file, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) template_manage_result = __salt__['file.manage_file']( name=template_tmp_file, sfn=tsfn, ret=None, source=template_file, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if template_manage_result['result']: with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_: tpl = salt.utils.stringutils.to_unicode(tfp_.read()) salt.utils.files.safe_rm(template_tmp_file) try: template = _parse_template(tpl) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open template: {0} {1}'.format(template_file, comment_) else: ret['result'] = False ret['comment'] = 'Can not open template' if ret['result'] is False: return ret kwargs = {} kwargs['template'] = template try: h_client.stacks.validate(**kwargs) except Exception as ex: # pylint: disable=W0703 log.exception('Template not valid') ret['result'] = False ret['comment'] = 'Template not valid {0}'.format(ex) return ret env = {} if environment: environment_tmp_file = salt.utils.files.mkstemp() esfn, source_sum, comment_ = __salt__['file.get_managed']( name=environment_tmp_file, template=None, source=environment, source_hash=None, user=None, group=None, mode=None, saltenv='base', context=None, defaults=None, skip_verify=False, kwargs=None) environment_manage_result = __salt__['file.manage_file']( name=environment_tmp_file, sfn=esfn, ret=None, source=environment, source_sum=source_sum, user=None, group=None, mode=None, saltenv='base', backup=None, makedirs=True, template=None, show_changes=False, contents=None, dir_mode=None) if environment_manage_result['result']: with salt.utils.files.fopen(environment_tmp_file, 'r') as efp_: env_str = salt.utils.stringutils.to_unicode(efp_.read()) salt.utils.files.safe_rm(environment_tmp_file) try: env = _parse_environment(env_str) except ValueError as ex: ret['result'] = False ret['comment'] = 'Error parsing template {0}'.format(ex) else: ret['result'] = False ret['comment'] = 'Can not open environment: {0}, {1}'.format(environment, comment_) if ret['result'] is False: return ret fields = { 'disable_rollback': not rollback, 'parameters': parameters, 'template': template, 'environment': env, 'timeout_mins': timeout } try: h_client.stacks.update(name, **fields) except Exception as ex: # pylint: disable=W0703 log.exception('Update failed') ret['result'] = False ret['comment'] = 'Update failed {0}'.format(ex) return ret if poll > 0: stack_status, msg = _poll_for_events(h_client, name, action='UPDATE', poll_period=poll, timeout=timeout) if stack_status == 'UPDATE_FAILED': ret['result'] = False ret['comment'] = 'Updated stack FAILED\'{0}\'{1}.'.format(name, msg) if ret['result'] is True: ret['comment'] = 'Updated stack \'{0}\'.'.format(name), return ret
saltstack/salt
salt/states/uptime.py
monitored
python
def monitored(name, **params): ''' Makes sure an URL is monitored by uptime. Checks if URL is already monitored, and if not, adds it. ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if __salt__['uptime.check_exists'](name=name): ret['result'] = True ret['comment'] = 'URL {0} is already monitored'.format(name) ret['changes'] = {} return ret if not __opts__['test']: url_monitored = __salt__['uptime.create'](name, **params) if url_monitored: ret['result'] = True msg = 'Successfully added the URL {0} to uptime' ret['comment'] = msg.format(name) ret['changes'] = {'url_monitored': url_monitored} else: ret['result'] = False ret['comment'] = 'Failed to add {0} to uptime'.format(name) ret['changes'] = {} else: msg = 'URL {0} is going to be added to uptime' ret.update(result=None, comment=msg.format(name)) return ret
Makes sure an URL is monitored by uptime. Checks if URL is already monitored, and if not, adds it.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/uptime.py#L47-L75
null
# -*- coding: utf-8 -*- ''' Monitor Web Server with Uptime ============================== `Uptime <https://github.com/fzaninotto/uptime>`_ is an open source remote monitoring application using Node.js, MongoDB, and Twitter Bootstrap. .. warning:: This state module is beta. It might be changed later to include more or less automation. .. note:: This state module requires a pillar to specify the location of your uptime install .. code-block:: yaml uptime: application_url: "http://uptime-url.example.org" Example: .. code-block:: yaml url: uptime.monitored url/sitemap.xml: uptime.monitored: - polling: 600 # every hour ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): ''' Only load if the uptime module is present ''' return 'uptime.checks_list' in __salt__
saltstack/salt
salt/modules/zk_concurrency.py
lock_holders
python
def lock_holders(path, zk_hosts=None, identifier=None, max_concurrency=1, timeout=None, ephemeral_lease=False, profile=None, scheme=None, username=None, password=None, default_acl=None): ''' Return an un-ordered list of lock holders path The path in zookeeper where the lock is zk_hosts zookeeper connect string identifier Name to identify this minion, if unspecified defaults to hostname max_concurrency Maximum number of lock holders timeout timeout to wait for the lock. A None timeout will block forever ephemeral_lease Whether the locks in zookeper should be ephemeral Example: .. code-block: bash salt minion zk_concurrency.lock_holders /lock/path host1:1234,host2:1234 ''' zk = _get_zk_conn(profile=profile, hosts=zk_hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if path not in __context__['semaphore_map']: __context__['semaphore_map'][path] = _Semaphore(zk, path, identifier, max_leases=max_concurrency, ephemeral_lease=ephemeral_lease) return __context__['semaphore_map'][path].lease_holders()
Return an un-ordered list of lock holders path The path in zookeeper where the lock is zk_hosts zookeeper connect string identifier Name to identify this minion, if unspecified defaults to hostname max_concurrency Maximum number of lock holders timeout timeout to wait for the lock. A None timeout will block forever ephemeral_lease Whether the locks in zookeper should be ephemeral Example: .. code-block: bash salt minion zk_concurrency.lock_holders /lock/path host1:1234,host2:1234
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zk_concurrency.py#L154-L198
[ "def _get_zk_conn(profile=None, **connection_args):\n if profile:\n prefix = 'zookeeper:' + profile\n else:\n prefix = 'zookeeper'\n\n def get(key, default=None):\n '''\n look in connection_args first, then default to config file\n '''\n return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default)\n\n hosts = get('hosts', '127.0.0.1:2181')\n scheme = get('scheme', None)\n username = get('username', None)\n password = get('password', None)\n default_acl = get('default_acl', None)\n\n if isinstance(hosts, list):\n hosts = ','.join(hosts)\n\n if username is not None and password is not None and scheme is None:\n scheme = 'digest'\n\n auth_data = None\n if scheme and username and password:\n auth_data = [(scheme, ':'.join([username, password]))]\n\n if default_acl is not None:\n if isinstance(default_acl, list):\n default_acl = [__salt__['zookeeper.make_digest_acl'](**acl) for acl in default_acl]\n else:\n default_acl = [__salt__['zookeeper.make_digest_acl'](**default_acl)]\n\n __context__.setdefault('zkconnection', {}).setdefault(profile or hosts,\n kazoo.client.KazooClient(hosts=hosts,\n default_acl=default_acl,\n auth_data=auth_data))\n\n if not __context__['zkconnection'][profile or hosts].connected:\n __context__['zkconnection'][profile or hosts].start()\n\n return __context__['zkconnection'][profile or hosts]\n" ]
# -*- coding: utf-8 -*- ''' Concurrency controls in zookeeper ========================================================================= :depends: kazoo :configuration: See :py:mod:`salt.modules.zookeeper` for setup instructions. This module allows you to acquire and release a slot. This is primarily useful for ensureing that no more than N hosts take a specific action at once. This can also be used to coordinate between masters. ''' from __future__ import absolute_import, print_function, unicode_literals import logging import sys try: import kazoo.client from kazoo.retry import ( ForceRetryError ) import kazoo.recipe.lock import kazoo.recipe.barrier import kazoo.recipe.party from kazoo.exceptions import CancelledError from kazoo.exceptions import NoNodeError from socket import gethostname # TODO: use the kazoo one, waiting for pull req: # https://github.com/python-zk/kazoo/pull/206 class _Semaphore(kazoo.recipe.lock.Semaphore): def __init__(self, client, path, identifier=None, max_leases=1, ephemeral_lease=True, ): identifier = (identifier or gethostname()) kazoo.recipe.lock.Semaphore.__init__(self, client, path, identifier=identifier, max_leases=max_leases) self.ephemeral_lease = ephemeral_lease # if its not ephemeral, make sure we didn't already grab it if not self.ephemeral_lease: try: for child in self.client.get_children(self.path): try: data, stat = self.client.get(self.path + "/" + child) if identifier == data.decode('utf-8'): self.create_path = self.path + "/" + child self.is_acquired = True break except NoNodeError: # pragma: nocover pass except NoNodeError: # pragma: nocover pass def _get_lease(self, data=None): # Make sure the session is still valid if self._session_expired: raise ForceRetryError("Retry on session loss at top") # Make sure that the request hasn't been canceled if self.cancelled: raise CancelledError("Semaphore cancelled") # Get a list of the current potential lock holders. If they change, # notify our wake_event object. This is used to unblock a blocking # self._inner_acquire call. children = self.client.get_children(self.path, self._watch_lease_change) # If there are leases available, acquire one if len(children) < self.max_leases: self.client.create(self.create_path, self.data, ephemeral=self.ephemeral_lease) # Check if our acquisition was successful or not. Update our state. if self.client.exists(self.create_path): self.is_acquired = True else: self.is_acquired = False # Return current state return self.is_acquired HAS_DEPS = True except ImportError: HAS_DEPS = False __virtualname__ = 'zk_concurrency' def __virtual__(): if not HAS_DEPS: return (False, "Module zk_concurrency: dependencies failed") __context__['semaphore_map'] = {} return __virtualname__ def _get_zk_conn(profile=None, **connection_args): if profile: prefix = 'zookeeper:' + profile else: prefix = 'zookeeper' def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default) hosts = get('hosts', '127.0.0.1:2181') scheme = get('scheme', None) username = get('username', None) password = get('password', None) default_acl = get('default_acl', None) if isinstance(hosts, list): hosts = ','.join(hosts) if username is not None and password is not None and scheme is None: scheme = 'digest' auth_data = None if scheme and username and password: auth_data = [(scheme, ':'.join([username, password]))] if default_acl is not None: if isinstance(default_acl, list): default_acl = [__salt__['zookeeper.make_digest_acl'](**acl) for acl in default_acl] else: default_acl = [__salt__['zookeeper.make_digest_acl'](**default_acl)] __context__.setdefault('zkconnection', {}).setdefault(profile or hosts, kazoo.client.KazooClient(hosts=hosts, default_acl=default_acl, auth_data=auth_data)) if not __context__['zkconnection'][profile or hosts].connected: __context__['zkconnection'][profile or hosts].start() return __context__['zkconnection'][profile or hosts] def lock(path, zk_hosts=None, identifier=None, max_concurrency=1, timeout=None, ephemeral_lease=False, force=False, # foricble get the lock regardless of open slots profile=None, scheme=None, username=None, password=None, default_acl=None, ): ''' Get lock (with optional timeout) path The path in zookeeper where the lock is zk_hosts zookeeper connect string identifier Name to identify this minion, if unspecified defaults to the hostname max_concurrency Maximum number of lock holders timeout timeout to wait for the lock. A None timeout will block forever ephemeral_lease Whether the locks in zookeper should be ephemeral force Forcibly acquire the lock regardless of available slots Example: .. code-block: bash salt minion zk_concurrency.lock /lock/path host1:1234,host2:1234 ''' zk = _get_zk_conn(profile=profile, hosts=zk_hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if path not in __context__['semaphore_map']: __context__['semaphore_map'][path] = _Semaphore(zk, path, identifier, max_leases=max_concurrency, ephemeral_lease=ephemeral_lease) # forcibly get the lock regardless of max_concurrency if force: __context__['semaphore_map'][path].assured_path = True __context__['semaphore_map'][path].max_leases = sys.maxint # block waiting for lock acquisition if timeout: logging.info('Acquiring lock %s with timeout=%s', path, timeout) __context__['semaphore_map'][path].acquire(timeout=timeout) else: logging.info('Acquiring lock %s with no timeout', path) __context__['semaphore_map'][path].acquire() return __context__['semaphore_map'][path].is_acquired def unlock(path, zk_hosts=None, # in case you need to unlock without having run lock (failed execution for example) identifier=None, max_concurrency=1, ephemeral_lease=False, scheme=None, profile=None, username=None, password=None, default_acl=None ): ''' Remove lease from semaphore path The path in zookeeper where the lock is zk_hosts zookeeper connect string identifier Name to identify this minion, if unspecified defaults to hostname max_concurrency Maximum number of lock holders timeout timeout to wait for the lock. A None timeout will block forever ephemeral_lease Whether the locks in zookeper should be ephemeral Example: .. code-block: bash salt minion zk_concurrency.unlock /lock/path host1:1234,host2:1234 ''' # if someone passed in zk_hosts, and the path isn't in __context__['semaphore_map'], lets # see if we can find it zk = _get_zk_conn(profile=profile, hosts=zk_hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if path not in __context__['semaphore_map']: __context__['semaphore_map'][path] = _Semaphore(zk, path, identifier, max_leases=max_concurrency, ephemeral_lease=ephemeral_lease) if path in __context__['semaphore_map']: __context__['semaphore_map'][path].release() del __context__['semaphore_map'][path] return True else: logging.error('Unable to find lease for path %s', path) return False def party_members(path, zk_hosts=None, min_nodes=1, blocking=False, profile=None, scheme=None, username=None, password=None, default_acl=None, ): ''' Get the List of identifiers in a particular party, optionally waiting for the specified minimum number of nodes (min_nodes) to appear path The path in zookeeper where the lock is zk_hosts zookeeper connect string min_nodes The minimum number of nodes expected to be present in the party blocking The boolean indicating if we need to block until min_nodes are available Example: .. code-block: bash salt minion zk_concurrency.party_members /lock/path host1:1234,host2:1234 salt minion zk_concurrency.party_members /lock/path host1:1234,host2:1234 min_nodes=3 blocking=True ''' zk = _get_zk_conn(profile=profile, hosts=zk_hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) party = kazoo.recipe.party.ShallowParty(zk, path) if blocking: barrier = kazoo.recipe.barrier.DoubleBarrier(zk, path, min_nodes) barrier.enter() party = kazoo.recipe.party.ShallowParty(zk, path) barrier.leave() return list(party)
saltstack/salt
salt/modules/zk_concurrency.py
lock
python
def lock(path, zk_hosts=None, identifier=None, max_concurrency=1, timeout=None, ephemeral_lease=False, force=False, # foricble get the lock regardless of open slots profile=None, scheme=None, username=None, password=None, default_acl=None, ): ''' Get lock (with optional timeout) path The path in zookeeper where the lock is zk_hosts zookeeper connect string identifier Name to identify this minion, if unspecified defaults to the hostname max_concurrency Maximum number of lock holders timeout timeout to wait for the lock. A None timeout will block forever ephemeral_lease Whether the locks in zookeper should be ephemeral force Forcibly acquire the lock regardless of available slots Example: .. code-block: bash salt minion zk_concurrency.lock /lock/path host1:1234,host2:1234 ''' zk = _get_zk_conn(profile=profile, hosts=zk_hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if path not in __context__['semaphore_map']: __context__['semaphore_map'][path] = _Semaphore(zk, path, identifier, max_leases=max_concurrency, ephemeral_lease=ephemeral_lease) # forcibly get the lock regardless of max_concurrency if force: __context__['semaphore_map'][path].assured_path = True __context__['semaphore_map'][path].max_leases = sys.maxint # block waiting for lock acquisition if timeout: logging.info('Acquiring lock %s with timeout=%s', path, timeout) __context__['semaphore_map'][path].acquire(timeout=timeout) else: logging.info('Acquiring lock %s with no timeout', path) __context__['semaphore_map'][path].acquire() return __context__['semaphore_map'][path].is_acquired
Get lock (with optional timeout) path The path in zookeeper where the lock is zk_hosts zookeeper connect string identifier Name to identify this minion, if unspecified defaults to the hostname max_concurrency Maximum number of lock holders timeout timeout to wait for the lock. A None timeout will block forever ephemeral_lease Whether the locks in zookeper should be ephemeral force Forcibly acquire the lock regardless of available slots Example: .. code-block: bash salt minion zk_concurrency.lock /lock/path host1:1234,host2:1234
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zk_concurrency.py#L201-L264
[ "def _get_zk_conn(profile=None, **connection_args):\n if profile:\n prefix = 'zookeeper:' + profile\n else:\n prefix = 'zookeeper'\n\n def get(key, default=None):\n '''\n look in connection_args first, then default to config file\n '''\n return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default)\n\n hosts = get('hosts', '127.0.0.1:2181')\n scheme = get('scheme', None)\n username = get('username', None)\n password = get('password', None)\n default_acl = get('default_acl', None)\n\n if isinstance(hosts, list):\n hosts = ','.join(hosts)\n\n if username is not None and password is not None and scheme is None:\n scheme = 'digest'\n\n auth_data = None\n if scheme and username and password:\n auth_data = [(scheme, ':'.join([username, password]))]\n\n if default_acl is not None:\n if isinstance(default_acl, list):\n default_acl = [__salt__['zookeeper.make_digest_acl'](**acl) for acl in default_acl]\n else:\n default_acl = [__salt__['zookeeper.make_digest_acl'](**default_acl)]\n\n __context__.setdefault('zkconnection', {}).setdefault(profile or hosts,\n kazoo.client.KazooClient(hosts=hosts,\n default_acl=default_acl,\n auth_data=auth_data))\n\n if not __context__['zkconnection'][profile or hosts].connected:\n __context__['zkconnection'][profile or hosts].start()\n\n return __context__['zkconnection'][profile or hosts]\n" ]
# -*- coding: utf-8 -*- ''' Concurrency controls in zookeeper ========================================================================= :depends: kazoo :configuration: See :py:mod:`salt.modules.zookeeper` for setup instructions. This module allows you to acquire and release a slot. This is primarily useful for ensureing that no more than N hosts take a specific action at once. This can also be used to coordinate between masters. ''' from __future__ import absolute_import, print_function, unicode_literals import logging import sys try: import kazoo.client from kazoo.retry import ( ForceRetryError ) import kazoo.recipe.lock import kazoo.recipe.barrier import kazoo.recipe.party from kazoo.exceptions import CancelledError from kazoo.exceptions import NoNodeError from socket import gethostname # TODO: use the kazoo one, waiting for pull req: # https://github.com/python-zk/kazoo/pull/206 class _Semaphore(kazoo.recipe.lock.Semaphore): def __init__(self, client, path, identifier=None, max_leases=1, ephemeral_lease=True, ): identifier = (identifier or gethostname()) kazoo.recipe.lock.Semaphore.__init__(self, client, path, identifier=identifier, max_leases=max_leases) self.ephemeral_lease = ephemeral_lease # if its not ephemeral, make sure we didn't already grab it if not self.ephemeral_lease: try: for child in self.client.get_children(self.path): try: data, stat = self.client.get(self.path + "/" + child) if identifier == data.decode('utf-8'): self.create_path = self.path + "/" + child self.is_acquired = True break except NoNodeError: # pragma: nocover pass except NoNodeError: # pragma: nocover pass def _get_lease(self, data=None): # Make sure the session is still valid if self._session_expired: raise ForceRetryError("Retry on session loss at top") # Make sure that the request hasn't been canceled if self.cancelled: raise CancelledError("Semaphore cancelled") # Get a list of the current potential lock holders. If they change, # notify our wake_event object. This is used to unblock a blocking # self._inner_acquire call. children = self.client.get_children(self.path, self._watch_lease_change) # If there are leases available, acquire one if len(children) < self.max_leases: self.client.create(self.create_path, self.data, ephemeral=self.ephemeral_lease) # Check if our acquisition was successful or not. Update our state. if self.client.exists(self.create_path): self.is_acquired = True else: self.is_acquired = False # Return current state return self.is_acquired HAS_DEPS = True except ImportError: HAS_DEPS = False __virtualname__ = 'zk_concurrency' def __virtual__(): if not HAS_DEPS: return (False, "Module zk_concurrency: dependencies failed") __context__['semaphore_map'] = {} return __virtualname__ def _get_zk_conn(profile=None, **connection_args): if profile: prefix = 'zookeeper:' + profile else: prefix = 'zookeeper' def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default) hosts = get('hosts', '127.0.0.1:2181') scheme = get('scheme', None) username = get('username', None) password = get('password', None) default_acl = get('default_acl', None) if isinstance(hosts, list): hosts = ','.join(hosts) if username is not None and password is not None and scheme is None: scheme = 'digest' auth_data = None if scheme and username and password: auth_data = [(scheme, ':'.join([username, password]))] if default_acl is not None: if isinstance(default_acl, list): default_acl = [__salt__['zookeeper.make_digest_acl'](**acl) for acl in default_acl] else: default_acl = [__salt__['zookeeper.make_digest_acl'](**default_acl)] __context__.setdefault('zkconnection', {}).setdefault(profile or hosts, kazoo.client.KazooClient(hosts=hosts, default_acl=default_acl, auth_data=auth_data)) if not __context__['zkconnection'][profile or hosts].connected: __context__['zkconnection'][profile or hosts].start() return __context__['zkconnection'][profile or hosts] def lock_holders(path, zk_hosts=None, identifier=None, max_concurrency=1, timeout=None, ephemeral_lease=False, profile=None, scheme=None, username=None, password=None, default_acl=None): ''' Return an un-ordered list of lock holders path The path in zookeeper where the lock is zk_hosts zookeeper connect string identifier Name to identify this minion, if unspecified defaults to hostname max_concurrency Maximum number of lock holders timeout timeout to wait for the lock. A None timeout will block forever ephemeral_lease Whether the locks in zookeper should be ephemeral Example: .. code-block: bash salt minion zk_concurrency.lock_holders /lock/path host1:1234,host2:1234 ''' zk = _get_zk_conn(profile=profile, hosts=zk_hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if path not in __context__['semaphore_map']: __context__['semaphore_map'][path] = _Semaphore(zk, path, identifier, max_leases=max_concurrency, ephemeral_lease=ephemeral_lease) return __context__['semaphore_map'][path].lease_holders() def unlock(path, zk_hosts=None, # in case you need to unlock without having run lock (failed execution for example) identifier=None, max_concurrency=1, ephemeral_lease=False, scheme=None, profile=None, username=None, password=None, default_acl=None ): ''' Remove lease from semaphore path The path in zookeeper where the lock is zk_hosts zookeeper connect string identifier Name to identify this minion, if unspecified defaults to hostname max_concurrency Maximum number of lock holders timeout timeout to wait for the lock. A None timeout will block forever ephemeral_lease Whether the locks in zookeper should be ephemeral Example: .. code-block: bash salt minion zk_concurrency.unlock /lock/path host1:1234,host2:1234 ''' # if someone passed in zk_hosts, and the path isn't in __context__['semaphore_map'], lets # see if we can find it zk = _get_zk_conn(profile=profile, hosts=zk_hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if path not in __context__['semaphore_map']: __context__['semaphore_map'][path] = _Semaphore(zk, path, identifier, max_leases=max_concurrency, ephemeral_lease=ephemeral_lease) if path in __context__['semaphore_map']: __context__['semaphore_map'][path].release() del __context__['semaphore_map'][path] return True else: logging.error('Unable to find lease for path %s', path) return False def party_members(path, zk_hosts=None, min_nodes=1, blocking=False, profile=None, scheme=None, username=None, password=None, default_acl=None, ): ''' Get the List of identifiers in a particular party, optionally waiting for the specified minimum number of nodes (min_nodes) to appear path The path in zookeeper where the lock is zk_hosts zookeeper connect string min_nodes The minimum number of nodes expected to be present in the party blocking The boolean indicating if we need to block until min_nodes are available Example: .. code-block: bash salt minion zk_concurrency.party_members /lock/path host1:1234,host2:1234 salt minion zk_concurrency.party_members /lock/path host1:1234,host2:1234 min_nodes=3 blocking=True ''' zk = _get_zk_conn(profile=profile, hosts=zk_hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) party = kazoo.recipe.party.ShallowParty(zk, path) if blocking: barrier = kazoo.recipe.barrier.DoubleBarrier(zk, path, min_nodes) barrier.enter() party = kazoo.recipe.party.ShallowParty(zk, path) barrier.leave() return list(party)
saltstack/salt
salt/modules/zk_concurrency.py
unlock
python
def unlock(path, zk_hosts=None, # in case you need to unlock without having run lock (failed execution for example) identifier=None, max_concurrency=1, ephemeral_lease=False, scheme=None, profile=None, username=None, password=None, default_acl=None ): ''' Remove lease from semaphore path The path in zookeeper where the lock is zk_hosts zookeeper connect string identifier Name to identify this minion, if unspecified defaults to hostname max_concurrency Maximum number of lock holders timeout timeout to wait for the lock. A None timeout will block forever ephemeral_lease Whether the locks in zookeper should be ephemeral Example: .. code-block: bash salt minion zk_concurrency.unlock /lock/path host1:1234,host2:1234 ''' # if someone passed in zk_hosts, and the path isn't in __context__['semaphore_map'], lets # see if we can find it zk = _get_zk_conn(profile=profile, hosts=zk_hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if path not in __context__['semaphore_map']: __context__['semaphore_map'][path] = _Semaphore(zk, path, identifier, max_leases=max_concurrency, ephemeral_lease=ephemeral_lease) if path in __context__['semaphore_map']: __context__['semaphore_map'][path].release() del __context__['semaphore_map'][path] return True else: logging.error('Unable to find lease for path %s', path) return False
Remove lease from semaphore path The path in zookeeper where the lock is zk_hosts zookeeper connect string identifier Name to identify this minion, if unspecified defaults to hostname max_concurrency Maximum number of lock holders timeout timeout to wait for the lock. A None timeout will block forever ephemeral_lease Whether the locks in zookeper should be ephemeral Example: .. code-block: bash salt minion zk_concurrency.unlock /lock/path host1:1234,host2:1234
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zk_concurrency.py#L267-L320
[ "def _get_zk_conn(profile=None, **connection_args):\n if profile:\n prefix = 'zookeeper:' + profile\n else:\n prefix = 'zookeeper'\n\n def get(key, default=None):\n '''\n look in connection_args first, then default to config file\n '''\n return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default)\n\n hosts = get('hosts', '127.0.0.1:2181')\n scheme = get('scheme', None)\n username = get('username', None)\n password = get('password', None)\n default_acl = get('default_acl', None)\n\n if isinstance(hosts, list):\n hosts = ','.join(hosts)\n\n if username is not None and password is not None and scheme is None:\n scheme = 'digest'\n\n auth_data = None\n if scheme and username and password:\n auth_data = [(scheme, ':'.join([username, password]))]\n\n if default_acl is not None:\n if isinstance(default_acl, list):\n default_acl = [__salt__['zookeeper.make_digest_acl'](**acl) for acl in default_acl]\n else:\n default_acl = [__salt__['zookeeper.make_digest_acl'](**default_acl)]\n\n __context__.setdefault('zkconnection', {}).setdefault(profile or hosts,\n kazoo.client.KazooClient(hosts=hosts,\n default_acl=default_acl,\n auth_data=auth_data))\n\n if not __context__['zkconnection'][profile or hosts].connected:\n __context__['zkconnection'][profile or hosts].start()\n\n return __context__['zkconnection'][profile or hosts]\n" ]
# -*- coding: utf-8 -*- ''' Concurrency controls in zookeeper ========================================================================= :depends: kazoo :configuration: See :py:mod:`salt.modules.zookeeper` for setup instructions. This module allows you to acquire and release a slot. This is primarily useful for ensureing that no more than N hosts take a specific action at once. This can also be used to coordinate between masters. ''' from __future__ import absolute_import, print_function, unicode_literals import logging import sys try: import kazoo.client from kazoo.retry import ( ForceRetryError ) import kazoo.recipe.lock import kazoo.recipe.barrier import kazoo.recipe.party from kazoo.exceptions import CancelledError from kazoo.exceptions import NoNodeError from socket import gethostname # TODO: use the kazoo one, waiting for pull req: # https://github.com/python-zk/kazoo/pull/206 class _Semaphore(kazoo.recipe.lock.Semaphore): def __init__(self, client, path, identifier=None, max_leases=1, ephemeral_lease=True, ): identifier = (identifier or gethostname()) kazoo.recipe.lock.Semaphore.__init__(self, client, path, identifier=identifier, max_leases=max_leases) self.ephemeral_lease = ephemeral_lease # if its not ephemeral, make sure we didn't already grab it if not self.ephemeral_lease: try: for child in self.client.get_children(self.path): try: data, stat = self.client.get(self.path + "/" + child) if identifier == data.decode('utf-8'): self.create_path = self.path + "/" + child self.is_acquired = True break except NoNodeError: # pragma: nocover pass except NoNodeError: # pragma: nocover pass def _get_lease(self, data=None): # Make sure the session is still valid if self._session_expired: raise ForceRetryError("Retry on session loss at top") # Make sure that the request hasn't been canceled if self.cancelled: raise CancelledError("Semaphore cancelled") # Get a list of the current potential lock holders. If they change, # notify our wake_event object. This is used to unblock a blocking # self._inner_acquire call. children = self.client.get_children(self.path, self._watch_lease_change) # If there are leases available, acquire one if len(children) < self.max_leases: self.client.create(self.create_path, self.data, ephemeral=self.ephemeral_lease) # Check if our acquisition was successful or not. Update our state. if self.client.exists(self.create_path): self.is_acquired = True else: self.is_acquired = False # Return current state return self.is_acquired HAS_DEPS = True except ImportError: HAS_DEPS = False __virtualname__ = 'zk_concurrency' def __virtual__(): if not HAS_DEPS: return (False, "Module zk_concurrency: dependencies failed") __context__['semaphore_map'] = {} return __virtualname__ def _get_zk_conn(profile=None, **connection_args): if profile: prefix = 'zookeeper:' + profile else: prefix = 'zookeeper' def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default) hosts = get('hosts', '127.0.0.1:2181') scheme = get('scheme', None) username = get('username', None) password = get('password', None) default_acl = get('default_acl', None) if isinstance(hosts, list): hosts = ','.join(hosts) if username is not None and password is not None and scheme is None: scheme = 'digest' auth_data = None if scheme and username and password: auth_data = [(scheme, ':'.join([username, password]))] if default_acl is not None: if isinstance(default_acl, list): default_acl = [__salt__['zookeeper.make_digest_acl'](**acl) for acl in default_acl] else: default_acl = [__salt__['zookeeper.make_digest_acl'](**default_acl)] __context__.setdefault('zkconnection', {}).setdefault(profile or hosts, kazoo.client.KazooClient(hosts=hosts, default_acl=default_acl, auth_data=auth_data)) if not __context__['zkconnection'][profile or hosts].connected: __context__['zkconnection'][profile or hosts].start() return __context__['zkconnection'][profile or hosts] def lock_holders(path, zk_hosts=None, identifier=None, max_concurrency=1, timeout=None, ephemeral_lease=False, profile=None, scheme=None, username=None, password=None, default_acl=None): ''' Return an un-ordered list of lock holders path The path in zookeeper where the lock is zk_hosts zookeeper connect string identifier Name to identify this minion, if unspecified defaults to hostname max_concurrency Maximum number of lock holders timeout timeout to wait for the lock. A None timeout will block forever ephemeral_lease Whether the locks in zookeper should be ephemeral Example: .. code-block: bash salt minion zk_concurrency.lock_holders /lock/path host1:1234,host2:1234 ''' zk = _get_zk_conn(profile=profile, hosts=zk_hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if path not in __context__['semaphore_map']: __context__['semaphore_map'][path] = _Semaphore(zk, path, identifier, max_leases=max_concurrency, ephemeral_lease=ephemeral_lease) return __context__['semaphore_map'][path].lease_holders() def lock(path, zk_hosts=None, identifier=None, max_concurrency=1, timeout=None, ephemeral_lease=False, force=False, # foricble get the lock regardless of open slots profile=None, scheme=None, username=None, password=None, default_acl=None, ): ''' Get lock (with optional timeout) path The path in zookeeper where the lock is zk_hosts zookeeper connect string identifier Name to identify this minion, if unspecified defaults to the hostname max_concurrency Maximum number of lock holders timeout timeout to wait for the lock. A None timeout will block forever ephemeral_lease Whether the locks in zookeper should be ephemeral force Forcibly acquire the lock regardless of available slots Example: .. code-block: bash salt minion zk_concurrency.lock /lock/path host1:1234,host2:1234 ''' zk = _get_zk_conn(profile=profile, hosts=zk_hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if path not in __context__['semaphore_map']: __context__['semaphore_map'][path] = _Semaphore(zk, path, identifier, max_leases=max_concurrency, ephemeral_lease=ephemeral_lease) # forcibly get the lock regardless of max_concurrency if force: __context__['semaphore_map'][path].assured_path = True __context__['semaphore_map'][path].max_leases = sys.maxint # block waiting for lock acquisition if timeout: logging.info('Acquiring lock %s with timeout=%s', path, timeout) __context__['semaphore_map'][path].acquire(timeout=timeout) else: logging.info('Acquiring lock %s with no timeout', path) __context__['semaphore_map'][path].acquire() return __context__['semaphore_map'][path].is_acquired def party_members(path, zk_hosts=None, min_nodes=1, blocking=False, profile=None, scheme=None, username=None, password=None, default_acl=None, ): ''' Get the List of identifiers in a particular party, optionally waiting for the specified minimum number of nodes (min_nodes) to appear path The path in zookeeper where the lock is zk_hosts zookeeper connect string min_nodes The minimum number of nodes expected to be present in the party blocking The boolean indicating if we need to block until min_nodes are available Example: .. code-block: bash salt minion zk_concurrency.party_members /lock/path host1:1234,host2:1234 salt minion zk_concurrency.party_members /lock/path host1:1234,host2:1234 min_nodes=3 blocking=True ''' zk = _get_zk_conn(profile=profile, hosts=zk_hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) party = kazoo.recipe.party.ShallowParty(zk, path) if blocking: barrier = kazoo.recipe.barrier.DoubleBarrier(zk, path, min_nodes) barrier.enter() party = kazoo.recipe.party.ShallowParty(zk, path) barrier.leave() return list(party)
saltstack/salt
salt/modules/zk_concurrency.py
party_members
python
def party_members(path, zk_hosts=None, min_nodes=1, blocking=False, profile=None, scheme=None, username=None, password=None, default_acl=None, ): ''' Get the List of identifiers in a particular party, optionally waiting for the specified minimum number of nodes (min_nodes) to appear path The path in zookeeper where the lock is zk_hosts zookeeper connect string min_nodes The minimum number of nodes expected to be present in the party blocking The boolean indicating if we need to block until min_nodes are available Example: .. code-block: bash salt minion zk_concurrency.party_members /lock/path host1:1234,host2:1234 salt minion zk_concurrency.party_members /lock/path host1:1234,host2:1234 min_nodes=3 blocking=True ''' zk = _get_zk_conn(profile=profile, hosts=zk_hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) party = kazoo.recipe.party.ShallowParty(zk, path) if blocking: barrier = kazoo.recipe.barrier.DoubleBarrier(zk, path, min_nodes) barrier.enter() party = kazoo.recipe.party.ShallowParty(zk, path) barrier.leave() return list(party)
Get the List of identifiers in a particular party, optionally waiting for the specified minimum number of nodes (min_nodes) to appear path The path in zookeeper where the lock is zk_hosts zookeeper connect string min_nodes The minimum number of nodes expected to be present in the party blocking The boolean indicating if we need to block until min_nodes are available Example: .. code-block: bash salt minion zk_concurrency.party_members /lock/path host1:1234,host2:1234 salt minion zk_concurrency.party_members /lock/path host1:1234,host2:1234 min_nodes=3 blocking=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zk_concurrency.py#L323-L364
[ "def _get_zk_conn(profile=None, **connection_args):\n if profile:\n prefix = 'zookeeper:' + profile\n else:\n prefix = 'zookeeper'\n\n def get(key, default=None):\n '''\n look in connection_args first, then default to config file\n '''\n return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default)\n\n hosts = get('hosts', '127.0.0.1:2181')\n scheme = get('scheme', None)\n username = get('username', None)\n password = get('password', None)\n default_acl = get('default_acl', None)\n\n if isinstance(hosts, list):\n hosts = ','.join(hosts)\n\n if username is not None and password is not None and scheme is None:\n scheme = 'digest'\n\n auth_data = None\n if scheme and username and password:\n auth_data = [(scheme, ':'.join([username, password]))]\n\n if default_acl is not None:\n if isinstance(default_acl, list):\n default_acl = [__salt__['zookeeper.make_digest_acl'](**acl) for acl in default_acl]\n else:\n default_acl = [__salt__['zookeeper.make_digest_acl'](**default_acl)]\n\n __context__.setdefault('zkconnection', {}).setdefault(profile or hosts,\n kazoo.client.KazooClient(hosts=hosts,\n default_acl=default_acl,\n auth_data=auth_data))\n\n if not __context__['zkconnection'][profile or hosts].connected:\n __context__['zkconnection'][profile or hosts].start()\n\n return __context__['zkconnection'][profile or hosts]\n" ]
# -*- coding: utf-8 -*- ''' Concurrency controls in zookeeper ========================================================================= :depends: kazoo :configuration: See :py:mod:`salt.modules.zookeeper` for setup instructions. This module allows you to acquire and release a slot. This is primarily useful for ensureing that no more than N hosts take a specific action at once. This can also be used to coordinate between masters. ''' from __future__ import absolute_import, print_function, unicode_literals import logging import sys try: import kazoo.client from kazoo.retry import ( ForceRetryError ) import kazoo.recipe.lock import kazoo.recipe.barrier import kazoo.recipe.party from kazoo.exceptions import CancelledError from kazoo.exceptions import NoNodeError from socket import gethostname # TODO: use the kazoo one, waiting for pull req: # https://github.com/python-zk/kazoo/pull/206 class _Semaphore(kazoo.recipe.lock.Semaphore): def __init__(self, client, path, identifier=None, max_leases=1, ephemeral_lease=True, ): identifier = (identifier or gethostname()) kazoo.recipe.lock.Semaphore.__init__(self, client, path, identifier=identifier, max_leases=max_leases) self.ephemeral_lease = ephemeral_lease # if its not ephemeral, make sure we didn't already grab it if not self.ephemeral_lease: try: for child in self.client.get_children(self.path): try: data, stat = self.client.get(self.path + "/" + child) if identifier == data.decode('utf-8'): self.create_path = self.path + "/" + child self.is_acquired = True break except NoNodeError: # pragma: nocover pass except NoNodeError: # pragma: nocover pass def _get_lease(self, data=None): # Make sure the session is still valid if self._session_expired: raise ForceRetryError("Retry on session loss at top") # Make sure that the request hasn't been canceled if self.cancelled: raise CancelledError("Semaphore cancelled") # Get a list of the current potential lock holders. If they change, # notify our wake_event object. This is used to unblock a blocking # self._inner_acquire call. children = self.client.get_children(self.path, self._watch_lease_change) # If there are leases available, acquire one if len(children) < self.max_leases: self.client.create(self.create_path, self.data, ephemeral=self.ephemeral_lease) # Check if our acquisition was successful or not. Update our state. if self.client.exists(self.create_path): self.is_acquired = True else: self.is_acquired = False # Return current state return self.is_acquired HAS_DEPS = True except ImportError: HAS_DEPS = False __virtualname__ = 'zk_concurrency' def __virtual__(): if not HAS_DEPS: return (False, "Module zk_concurrency: dependencies failed") __context__['semaphore_map'] = {} return __virtualname__ def _get_zk_conn(profile=None, **connection_args): if profile: prefix = 'zookeeper:' + profile else: prefix = 'zookeeper' def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default) hosts = get('hosts', '127.0.0.1:2181') scheme = get('scheme', None) username = get('username', None) password = get('password', None) default_acl = get('default_acl', None) if isinstance(hosts, list): hosts = ','.join(hosts) if username is not None and password is not None and scheme is None: scheme = 'digest' auth_data = None if scheme and username and password: auth_data = [(scheme, ':'.join([username, password]))] if default_acl is not None: if isinstance(default_acl, list): default_acl = [__salt__['zookeeper.make_digest_acl'](**acl) for acl in default_acl] else: default_acl = [__salt__['zookeeper.make_digest_acl'](**default_acl)] __context__.setdefault('zkconnection', {}).setdefault(profile or hosts, kazoo.client.KazooClient(hosts=hosts, default_acl=default_acl, auth_data=auth_data)) if not __context__['zkconnection'][profile or hosts].connected: __context__['zkconnection'][profile or hosts].start() return __context__['zkconnection'][profile or hosts] def lock_holders(path, zk_hosts=None, identifier=None, max_concurrency=1, timeout=None, ephemeral_lease=False, profile=None, scheme=None, username=None, password=None, default_acl=None): ''' Return an un-ordered list of lock holders path The path in zookeeper where the lock is zk_hosts zookeeper connect string identifier Name to identify this minion, if unspecified defaults to hostname max_concurrency Maximum number of lock holders timeout timeout to wait for the lock. A None timeout will block forever ephemeral_lease Whether the locks in zookeper should be ephemeral Example: .. code-block: bash salt minion zk_concurrency.lock_holders /lock/path host1:1234,host2:1234 ''' zk = _get_zk_conn(profile=profile, hosts=zk_hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if path not in __context__['semaphore_map']: __context__['semaphore_map'][path] = _Semaphore(zk, path, identifier, max_leases=max_concurrency, ephemeral_lease=ephemeral_lease) return __context__['semaphore_map'][path].lease_holders() def lock(path, zk_hosts=None, identifier=None, max_concurrency=1, timeout=None, ephemeral_lease=False, force=False, # foricble get the lock regardless of open slots profile=None, scheme=None, username=None, password=None, default_acl=None, ): ''' Get lock (with optional timeout) path The path in zookeeper where the lock is zk_hosts zookeeper connect string identifier Name to identify this minion, if unspecified defaults to the hostname max_concurrency Maximum number of lock holders timeout timeout to wait for the lock. A None timeout will block forever ephemeral_lease Whether the locks in zookeper should be ephemeral force Forcibly acquire the lock regardless of available slots Example: .. code-block: bash salt minion zk_concurrency.lock /lock/path host1:1234,host2:1234 ''' zk = _get_zk_conn(profile=profile, hosts=zk_hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if path not in __context__['semaphore_map']: __context__['semaphore_map'][path] = _Semaphore(zk, path, identifier, max_leases=max_concurrency, ephemeral_lease=ephemeral_lease) # forcibly get the lock regardless of max_concurrency if force: __context__['semaphore_map'][path].assured_path = True __context__['semaphore_map'][path].max_leases = sys.maxint # block waiting for lock acquisition if timeout: logging.info('Acquiring lock %s with timeout=%s', path, timeout) __context__['semaphore_map'][path].acquire(timeout=timeout) else: logging.info('Acquiring lock %s with no timeout', path) __context__['semaphore_map'][path].acquire() return __context__['semaphore_map'][path].is_acquired def unlock(path, zk_hosts=None, # in case you need to unlock without having run lock (failed execution for example) identifier=None, max_concurrency=1, ephemeral_lease=False, scheme=None, profile=None, username=None, password=None, default_acl=None ): ''' Remove lease from semaphore path The path in zookeeper where the lock is zk_hosts zookeeper connect string identifier Name to identify this minion, if unspecified defaults to hostname max_concurrency Maximum number of lock holders timeout timeout to wait for the lock. A None timeout will block forever ephemeral_lease Whether the locks in zookeper should be ephemeral Example: .. code-block: bash salt minion zk_concurrency.unlock /lock/path host1:1234,host2:1234 ''' # if someone passed in zk_hosts, and the path isn't in __context__['semaphore_map'], lets # see if we can find it zk = _get_zk_conn(profile=profile, hosts=zk_hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if path not in __context__['semaphore_map']: __context__['semaphore_map'][path] = _Semaphore(zk, path, identifier, max_leases=max_concurrency, ephemeral_lease=ephemeral_lease) if path in __context__['semaphore_map']: __context__['semaphore_map'][path].release() del __context__['semaphore_map'][path] return True else: logging.error('Unable to find lease for path %s', path) return False
saltstack/salt
salt/modules/chef.py
_default_logfile
python
def _default_logfile(exe_name): ''' Retrieve the logfile name ''' if salt.utils.platform.is_windows(): tmp_dir = os.path.join(__opts__['cachedir'], 'tmp') if not os.path.isdir(tmp_dir): os.mkdir(tmp_dir) logfile_tmp = tempfile.NamedTemporaryFile(dir=tmp_dir, prefix=exe_name, suffix='.log', delete=False) logfile = logfile_tmp.name logfile_tmp.close() else: logfile = salt.utils.path.join( '/var/log', '{0}.log'.format(exe_name) ) return logfile
Retrieve the logfile name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chef.py#L32-L52
null
# -*- coding: utf-8 -*- ''' Execute chef in server or solo mode ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import tempfile # Import Salt libs import salt.utils.path import salt.utils.platform import salt.utils.decorators.path # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Only load if chef is installed ''' if not salt.utils.path.which('chef-client'): return (False, 'Cannot load chef module: chef-client not found') return True @salt.utils.decorators.path.which('chef-client') def client(whyrun=False, localmode=False, logfile=None, **kwargs): ''' Execute a chef client run and return a dict with the stderr, stdout, return code, and pid. CLI Example: .. code-block:: bash salt '*' chef.client server=https://localhost server The chef server URL client_key Set the client key file location config The configuration file to use config-file-jail Directory under which config files are allowed to be loaded (no client.rb or knife.rb outside this path will be loaded). environment Set the Chef Environment on the node group Group to set privilege to json-attributes Load attributes from a JSON file or URL localmode Point chef-client at local repository if True log_level Set the log level (debug, info, warn, error, fatal) logfile Set the log file location node-name The node name for this client override-runlist Replace current run list with specified items for a single run pid Set the PID file location, defaults to /tmp/chef-client.pid run-lock-timeout Set maximum duration to wait for another client run to finish, default is indefinitely. runlist Permanently replace current run list with specified items user User to set privilege to validation_key Set the validation key file location, used for registering new clients whyrun Enable whyrun mode when set to True ''' if logfile is None: logfile = _default_logfile('chef-client') args = ['chef-client', '--no-color', '--once', '--logfile "{0}"'.format(logfile), '--format doc'] if whyrun: args.append('--why-run') if localmode: args.append('--local-mode') return _exec_cmd(*args, **kwargs) @salt.utils.decorators.path.which('chef-solo') def solo(whyrun=False, logfile=None, **kwargs): ''' Execute a chef solo run and return a dict with the stderr, stdout, return code, and pid. CLI Example: .. code-block:: bash salt '*' chef.solo override-runlist=test config The configuration file to use environment Set the Chef Environment on the node group Group to set privilege to json-attributes Load attributes from a JSON file or URL log_level Set the log level (debug, info, warn, error, fatal) logfile Set the log file location node-name The node name for this client override-runlist Replace current run list with specified items for a single run recipe-url Pull down a remote gzipped tarball of recipes and untar it to the cookbook cache run-lock-timeout Set maximum duration to wait for another client run to finish, default is indefinitely. user User to set privilege to whyrun Enable whyrun mode when set to True ''' if logfile is None: logfile = _default_logfile('chef-solo') args = ['chef-solo', '--no-color', '--logfile "{0}"'.format(logfile), '--format doc'] if whyrun: args.append('--why-run') return _exec_cmd(*args, **kwargs) def _exec_cmd(*args, **kwargs): # Compile the command arguments cmd_args = ' '.join(args) cmd_kwargs = ''.join([ ' --{0} {1}'.format(k, v) for k, v in six.iteritems(kwargs) if not k.startswith('__') ]) cmd_exec = '{0}{1}'.format(cmd_args, cmd_kwargs) log.debug('Chef command: %s', cmd_exec) return __salt__['cmd.run_all'](cmd_exec, python_shell=False)
saltstack/salt
salt/modules/chef.py
client
python
def client(whyrun=False, localmode=False, logfile=None, **kwargs): ''' Execute a chef client run and return a dict with the stderr, stdout, return code, and pid. CLI Example: .. code-block:: bash salt '*' chef.client server=https://localhost server The chef server URL client_key Set the client key file location config The configuration file to use config-file-jail Directory under which config files are allowed to be loaded (no client.rb or knife.rb outside this path will be loaded). environment Set the Chef Environment on the node group Group to set privilege to json-attributes Load attributes from a JSON file or URL localmode Point chef-client at local repository if True log_level Set the log level (debug, info, warn, error, fatal) logfile Set the log file location node-name The node name for this client override-runlist Replace current run list with specified items for a single run pid Set the PID file location, defaults to /tmp/chef-client.pid run-lock-timeout Set maximum duration to wait for another client run to finish, default is indefinitely. runlist Permanently replace current run list with specified items user User to set privilege to validation_key Set the validation key file location, used for registering new clients whyrun Enable whyrun mode when set to True ''' if logfile is None: logfile = _default_logfile('chef-client') args = ['chef-client', '--no-color', '--once', '--logfile "{0}"'.format(logfile), '--format doc'] if whyrun: args.append('--why-run') if localmode: args.append('--local-mode') return _exec_cmd(*args, **kwargs)
Execute a chef client run and return a dict with the stderr, stdout, return code, and pid. CLI Example: .. code-block:: bash salt '*' chef.client server=https://localhost server The chef server URL client_key Set the client key file location config The configuration file to use config-file-jail Directory under which config files are allowed to be loaded (no client.rb or knife.rb outside this path will be loaded). environment Set the Chef Environment on the node group Group to set privilege to json-attributes Load attributes from a JSON file or URL localmode Point chef-client at local repository if True log_level Set the log level (debug, info, warn, error, fatal) logfile Set the log file location node-name The node name for this client override-runlist Replace current run list with specified items for a single run pid Set the PID file location, defaults to /tmp/chef-client.pid run-lock-timeout Set maximum duration to wait for another client run to finish, default is indefinitely. runlist Permanently replace current run list with specified items user User to set privilege to validation_key Set the validation key file location, used for registering new clients whyrun Enable whyrun mode when set to True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chef.py#L56-L141
[ "def _default_logfile(exe_name):\n '''\n Retrieve the logfile name\n '''\n if salt.utils.platform.is_windows():\n tmp_dir = os.path.join(__opts__['cachedir'], 'tmp')\n if not os.path.isdir(tmp_dir):\n os.mkdir(tmp_dir)\n logfile_tmp = tempfile.NamedTemporaryFile(dir=tmp_dir,\n prefix=exe_name,\n suffix='.log',\n delete=False)\n logfile = logfile_tmp.name\n logfile_tmp.close()\n else:\n logfile = salt.utils.path.join(\n '/var/log',\n '{0}.log'.format(exe_name)\n )\n\n return logfile\n", "def _exec_cmd(*args, **kwargs):\n\n # Compile the command arguments\n cmd_args = ' '.join(args)\n cmd_kwargs = ''.join([\n ' --{0} {1}'.format(k, v)\n for k, v in six.iteritems(kwargs) if not k.startswith('__')\n ])\n cmd_exec = '{0}{1}'.format(cmd_args, cmd_kwargs)\n log.debug('Chef command: %s', cmd_exec)\n\n return __salt__['cmd.run_all'](cmd_exec, python_shell=False)\n" ]
# -*- coding: utf-8 -*- ''' Execute chef in server or solo mode ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import tempfile # Import Salt libs import salt.utils.path import salt.utils.platform import salt.utils.decorators.path # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Only load if chef is installed ''' if not salt.utils.path.which('chef-client'): return (False, 'Cannot load chef module: chef-client not found') return True def _default_logfile(exe_name): ''' Retrieve the logfile name ''' if salt.utils.platform.is_windows(): tmp_dir = os.path.join(__opts__['cachedir'], 'tmp') if not os.path.isdir(tmp_dir): os.mkdir(tmp_dir) logfile_tmp = tempfile.NamedTemporaryFile(dir=tmp_dir, prefix=exe_name, suffix='.log', delete=False) logfile = logfile_tmp.name logfile_tmp.close() else: logfile = salt.utils.path.join( '/var/log', '{0}.log'.format(exe_name) ) return logfile @salt.utils.decorators.path.which('chef-client') @salt.utils.decorators.path.which('chef-solo') def solo(whyrun=False, logfile=None, **kwargs): ''' Execute a chef solo run and return a dict with the stderr, stdout, return code, and pid. CLI Example: .. code-block:: bash salt '*' chef.solo override-runlist=test config The configuration file to use environment Set the Chef Environment on the node group Group to set privilege to json-attributes Load attributes from a JSON file or URL log_level Set the log level (debug, info, warn, error, fatal) logfile Set the log file location node-name The node name for this client override-runlist Replace current run list with specified items for a single run recipe-url Pull down a remote gzipped tarball of recipes and untar it to the cookbook cache run-lock-timeout Set maximum duration to wait for another client run to finish, default is indefinitely. user User to set privilege to whyrun Enable whyrun mode when set to True ''' if logfile is None: logfile = _default_logfile('chef-solo') args = ['chef-solo', '--no-color', '--logfile "{0}"'.format(logfile), '--format doc'] if whyrun: args.append('--why-run') return _exec_cmd(*args, **kwargs) def _exec_cmd(*args, **kwargs): # Compile the command arguments cmd_args = ' '.join(args) cmd_kwargs = ''.join([ ' --{0} {1}'.format(k, v) for k, v in six.iteritems(kwargs) if not k.startswith('__') ]) cmd_exec = '{0}{1}'.format(cmd_args, cmd_kwargs) log.debug('Chef command: %s', cmd_exec) return __salt__['cmd.run_all'](cmd_exec, python_shell=False)
saltstack/salt
salt/modules/chef.py
solo
python
def solo(whyrun=False, logfile=None, **kwargs): ''' Execute a chef solo run and return a dict with the stderr, stdout, return code, and pid. CLI Example: .. code-block:: bash salt '*' chef.solo override-runlist=test config The configuration file to use environment Set the Chef Environment on the node group Group to set privilege to json-attributes Load attributes from a JSON file or URL log_level Set the log level (debug, info, warn, error, fatal) logfile Set the log file location node-name The node name for this client override-runlist Replace current run list with specified items for a single run recipe-url Pull down a remote gzipped tarball of recipes and untar it to the cookbook cache run-lock-timeout Set maximum duration to wait for another client run to finish, default is indefinitely. user User to set privilege to whyrun Enable whyrun mode when set to True ''' if logfile is None: logfile = _default_logfile('chef-solo') args = ['chef-solo', '--no-color', '--logfile "{0}"'.format(logfile), '--format doc'] if whyrun: args.append('--why-run') return _exec_cmd(*args, **kwargs)
Execute a chef solo run and return a dict with the stderr, stdout, return code, and pid. CLI Example: .. code-block:: bash salt '*' chef.solo override-runlist=test config The configuration file to use environment Set the Chef Environment on the node group Group to set privilege to json-attributes Load attributes from a JSON file or URL log_level Set the log level (debug, info, warn, error, fatal) logfile Set the log file location node-name The node name for this client override-runlist Replace current run list with specified items for a single run recipe-url Pull down a remote gzipped tarball of recipes and untar it to the cookbook cache run-lock-timeout Set maximum duration to wait for another client run to finish, default is indefinitely. user User to set privilege to whyrun Enable whyrun mode when set to True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chef.py#L145-L206
[ "def _default_logfile(exe_name):\n '''\n Retrieve the logfile name\n '''\n if salt.utils.platform.is_windows():\n tmp_dir = os.path.join(__opts__['cachedir'], 'tmp')\n if not os.path.isdir(tmp_dir):\n os.mkdir(tmp_dir)\n logfile_tmp = tempfile.NamedTemporaryFile(dir=tmp_dir,\n prefix=exe_name,\n suffix='.log',\n delete=False)\n logfile = logfile_tmp.name\n logfile_tmp.close()\n else:\n logfile = salt.utils.path.join(\n '/var/log',\n '{0}.log'.format(exe_name)\n )\n\n return logfile\n", "def _exec_cmd(*args, **kwargs):\n\n # Compile the command arguments\n cmd_args = ' '.join(args)\n cmd_kwargs = ''.join([\n ' --{0} {1}'.format(k, v)\n for k, v in six.iteritems(kwargs) if not k.startswith('__')\n ])\n cmd_exec = '{0}{1}'.format(cmd_args, cmd_kwargs)\n log.debug('Chef command: %s', cmd_exec)\n\n return __salt__['cmd.run_all'](cmd_exec, python_shell=False)\n" ]
# -*- coding: utf-8 -*- ''' Execute chef in server or solo mode ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import tempfile # Import Salt libs import salt.utils.path import salt.utils.platform import salt.utils.decorators.path # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Only load if chef is installed ''' if not salt.utils.path.which('chef-client'): return (False, 'Cannot load chef module: chef-client not found') return True def _default_logfile(exe_name): ''' Retrieve the logfile name ''' if salt.utils.platform.is_windows(): tmp_dir = os.path.join(__opts__['cachedir'], 'tmp') if not os.path.isdir(tmp_dir): os.mkdir(tmp_dir) logfile_tmp = tempfile.NamedTemporaryFile(dir=tmp_dir, prefix=exe_name, suffix='.log', delete=False) logfile = logfile_tmp.name logfile_tmp.close() else: logfile = salt.utils.path.join( '/var/log', '{0}.log'.format(exe_name) ) return logfile @salt.utils.decorators.path.which('chef-client') def client(whyrun=False, localmode=False, logfile=None, **kwargs): ''' Execute a chef client run and return a dict with the stderr, stdout, return code, and pid. CLI Example: .. code-block:: bash salt '*' chef.client server=https://localhost server The chef server URL client_key Set the client key file location config The configuration file to use config-file-jail Directory under which config files are allowed to be loaded (no client.rb or knife.rb outside this path will be loaded). environment Set the Chef Environment on the node group Group to set privilege to json-attributes Load attributes from a JSON file or URL localmode Point chef-client at local repository if True log_level Set the log level (debug, info, warn, error, fatal) logfile Set the log file location node-name The node name for this client override-runlist Replace current run list with specified items for a single run pid Set the PID file location, defaults to /tmp/chef-client.pid run-lock-timeout Set maximum duration to wait for another client run to finish, default is indefinitely. runlist Permanently replace current run list with specified items user User to set privilege to validation_key Set the validation key file location, used for registering new clients whyrun Enable whyrun mode when set to True ''' if logfile is None: logfile = _default_logfile('chef-client') args = ['chef-client', '--no-color', '--once', '--logfile "{0}"'.format(logfile), '--format doc'] if whyrun: args.append('--why-run') if localmode: args.append('--local-mode') return _exec_cmd(*args, **kwargs) @salt.utils.decorators.path.which('chef-solo') def _exec_cmd(*args, **kwargs): # Compile the command arguments cmd_args = ' '.join(args) cmd_kwargs = ''.join([ ' --{0} {1}'.format(k, v) for k, v in six.iteritems(kwargs) if not k.startswith('__') ]) cmd_exec = '{0}{1}'.format(cmd_args, cmd_kwargs) log.debug('Chef command: %s', cmd_exec) return __salt__['cmd.run_all'](cmd_exec, python_shell=False)
saltstack/salt
salt/transport/frame.py
frame_msg
python
def frame_msg(body, header=None, raw_body=False): # pylint: disable=unused-argument ''' Frame the given message with our wire protocol ''' framed_msg = {} if header is None: header = {} framed_msg['head'] = header framed_msg['body'] = body return salt.utils.msgpack.dumps(framed_msg)
Frame the given message with our wire protocol
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/frame.py#L11-L21
[ "def packb(o, **kwargs):\n '''\n .. versionadded:: 2018.3.4\n\n Wraps msgpack.packb and ensures that the passed object is unwrapped if it\n is a proxy.\n\n By default, this function uses the msgpack module and falls back to\n msgpack_pure, if the msgpack is not available. You can pass an alternate\n msgpack module using the _msgpack_module argument.\n '''\n msgpack_module = kwargs.pop('_msgpack_module', msgpack)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n return msgpack_module.packb(o, default=_enc_func, **kwargs)\n" ]
# -*- coding: utf-8 -*- ''' Helper functions for transport components to handle message framing ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.utils.msgpack from salt.ext import six def frame_msg_ipc(body, header=None, raw_body=False): # pylint: disable=unused-argument ''' Frame the given message with our wire protocol for IPC For IPC, we don't need to be backwards compatible, so use the more efficient "use_bin_type=True" on Python 3. ''' framed_msg = {} if header is None: header = {} framed_msg['head'] = header framed_msg['body'] = body if six.PY2: return salt.utils.msgpack.dumps(framed_msg) else: return salt.utils.msgpack.dumps(framed_msg, use_bin_type=True) def _decode_embedded_list(src): ''' Convert enbedded bytes to strings if possible. List helper. ''' output = [] for elem in src: if isinstance(elem, dict): elem = _decode_embedded_dict(elem) elif isinstance(elem, list): elem = _decode_embedded_list(elem) # pylint: disable=redefined-variable-type elif isinstance(elem, bytes): try: elem = elem.decode() except UnicodeError: pass output.append(elem) return output def _decode_embedded_dict(src): ''' Convert enbedded bytes to strings if possible. Dict helper. ''' output = {} for key, val in six.iteritems(src): if isinstance(val, dict): val = _decode_embedded_dict(val) elif isinstance(val, list): val = _decode_embedded_list(val) # pylint: disable=redefined-variable-type elif isinstance(val, bytes): try: val = val.decode() except UnicodeError: pass if isinstance(key, bytes): try: key = key.decode() except UnicodeError: pass output[key] = val return output def decode_embedded_strs(src): ''' Convert enbedded bytes to strings if possible. This is necessary because Python 3 makes a distinction between these types. This wouldn't be needed if we used "use_bin_type=True" when encoding and "encoding='utf-8'" when decoding. Unfortunately, this would break backwards compatibility due to a change in wire protocol, so this less than ideal solution is used instead. ''' if not six.PY3: return src if isinstance(src, dict): return _decode_embedded_dict(src) elif isinstance(src, list): return _decode_embedded_list(src) elif isinstance(src, bytes): try: return src.decode() # pylint: disable=redefined-variable-type except UnicodeError: return src else: return src
saltstack/salt
salt/transport/frame.py
frame_msg_ipc
python
def frame_msg_ipc(body, header=None, raw_body=False): # pylint: disable=unused-argument ''' Frame the given message with our wire protocol for IPC For IPC, we don't need to be backwards compatible, so use the more efficient "use_bin_type=True" on Python 3. ''' framed_msg = {} if header is None: header = {} framed_msg['head'] = header framed_msg['body'] = body if six.PY2: return salt.utils.msgpack.dumps(framed_msg) else: return salt.utils.msgpack.dumps(framed_msg, use_bin_type=True)
Frame the given message with our wire protocol for IPC For IPC, we don't need to be backwards compatible, so use the more efficient "use_bin_type=True" on Python 3.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/frame.py#L24-L40
[ "def packb(o, **kwargs):\n '''\n .. versionadded:: 2018.3.4\n\n Wraps msgpack.packb and ensures that the passed object is unwrapped if it\n is a proxy.\n\n By default, this function uses the msgpack module and falls back to\n msgpack_pure, if the msgpack is not available. You can pass an alternate\n msgpack module using the _msgpack_module argument.\n '''\n msgpack_module = kwargs.pop('_msgpack_module', msgpack)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n return msgpack_module.packb(o, default=_enc_func, **kwargs)\n" ]
# -*- coding: utf-8 -*- ''' Helper functions for transport components to handle message framing ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.utils.msgpack from salt.ext import six def frame_msg(body, header=None, raw_body=False): # pylint: disable=unused-argument ''' Frame the given message with our wire protocol ''' framed_msg = {} if header is None: header = {} framed_msg['head'] = header framed_msg['body'] = body return salt.utils.msgpack.dumps(framed_msg) def _decode_embedded_list(src): ''' Convert enbedded bytes to strings if possible. List helper. ''' output = [] for elem in src: if isinstance(elem, dict): elem = _decode_embedded_dict(elem) elif isinstance(elem, list): elem = _decode_embedded_list(elem) # pylint: disable=redefined-variable-type elif isinstance(elem, bytes): try: elem = elem.decode() except UnicodeError: pass output.append(elem) return output def _decode_embedded_dict(src): ''' Convert enbedded bytes to strings if possible. Dict helper. ''' output = {} for key, val in six.iteritems(src): if isinstance(val, dict): val = _decode_embedded_dict(val) elif isinstance(val, list): val = _decode_embedded_list(val) # pylint: disable=redefined-variable-type elif isinstance(val, bytes): try: val = val.decode() except UnicodeError: pass if isinstance(key, bytes): try: key = key.decode() except UnicodeError: pass output[key] = val return output def decode_embedded_strs(src): ''' Convert enbedded bytes to strings if possible. This is necessary because Python 3 makes a distinction between these types. This wouldn't be needed if we used "use_bin_type=True" when encoding and "encoding='utf-8'" when decoding. Unfortunately, this would break backwards compatibility due to a change in wire protocol, so this less than ideal solution is used instead. ''' if not six.PY3: return src if isinstance(src, dict): return _decode_embedded_dict(src) elif isinstance(src, list): return _decode_embedded_list(src) elif isinstance(src, bytes): try: return src.decode() # pylint: disable=redefined-variable-type except UnicodeError: return src else: return src
saltstack/salt
salt/transport/frame.py
_decode_embedded_list
python
def _decode_embedded_list(src): ''' Convert enbedded bytes to strings if possible. List helper. ''' output = [] for elem in src: if isinstance(elem, dict): elem = _decode_embedded_dict(elem) elif isinstance(elem, list): elem = _decode_embedded_list(elem) # pylint: disable=redefined-variable-type elif isinstance(elem, bytes): try: elem = elem.decode() except UnicodeError: pass output.append(elem) return output
Convert enbedded bytes to strings if possible. List helper.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/frame.py#L43-L60
null
# -*- coding: utf-8 -*- ''' Helper functions for transport components to handle message framing ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.utils.msgpack from salt.ext import six def frame_msg(body, header=None, raw_body=False): # pylint: disable=unused-argument ''' Frame the given message with our wire protocol ''' framed_msg = {} if header is None: header = {} framed_msg['head'] = header framed_msg['body'] = body return salt.utils.msgpack.dumps(framed_msg) def frame_msg_ipc(body, header=None, raw_body=False): # pylint: disable=unused-argument ''' Frame the given message with our wire protocol for IPC For IPC, we don't need to be backwards compatible, so use the more efficient "use_bin_type=True" on Python 3. ''' framed_msg = {} if header is None: header = {} framed_msg['head'] = header framed_msg['body'] = body if six.PY2: return salt.utils.msgpack.dumps(framed_msg) else: return salt.utils.msgpack.dumps(framed_msg, use_bin_type=True) def _decode_embedded_dict(src): ''' Convert enbedded bytes to strings if possible. Dict helper. ''' output = {} for key, val in six.iteritems(src): if isinstance(val, dict): val = _decode_embedded_dict(val) elif isinstance(val, list): val = _decode_embedded_list(val) # pylint: disable=redefined-variable-type elif isinstance(val, bytes): try: val = val.decode() except UnicodeError: pass if isinstance(key, bytes): try: key = key.decode() except UnicodeError: pass output[key] = val return output def decode_embedded_strs(src): ''' Convert enbedded bytes to strings if possible. This is necessary because Python 3 makes a distinction between these types. This wouldn't be needed if we used "use_bin_type=True" when encoding and "encoding='utf-8'" when decoding. Unfortunately, this would break backwards compatibility due to a change in wire protocol, so this less than ideal solution is used instead. ''' if not six.PY3: return src if isinstance(src, dict): return _decode_embedded_dict(src) elif isinstance(src, list): return _decode_embedded_list(src) elif isinstance(src, bytes): try: return src.decode() # pylint: disable=redefined-variable-type except UnicodeError: return src else: return src
saltstack/salt
salt/transport/frame.py
_decode_embedded_dict
python
def _decode_embedded_dict(src): ''' Convert enbedded bytes to strings if possible. Dict helper. ''' output = {} for key, val in six.iteritems(src): if isinstance(val, dict): val = _decode_embedded_dict(val) elif isinstance(val, list): val = _decode_embedded_list(val) # pylint: disable=redefined-variable-type elif isinstance(val, bytes): try: val = val.decode() except UnicodeError: pass if isinstance(key, bytes): try: key = key.decode() except UnicodeError: pass output[key] = val return output
Convert enbedded bytes to strings if possible. Dict helper.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/frame.py#L63-L85
null
# -*- coding: utf-8 -*- ''' Helper functions for transport components to handle message framing ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.utils.msgpack from salt.ext import six def frame_msg(body, header=None, raw_body=False): # pylint: disable=unused-argument ''' Frame the given message with our wire protocol ''' framed_msg = {} if header is None: header = {} framed_msg['head'] = header framed_msg['body'] = body return salt.utils.msgpack.dumps(framed_msg) def frame_msg_ipc(body, header=None, raw_body=False): # pylint: disable=unused-argument ''' Frame the given message with our wire protocol for IPC For IPC, we don't need to be backwards compatible, so use the more efficient "use_bin_type=True" on Python 3. ''' framed_msg = {} if header is None: header = {} framed_msg['head'] = header framed_msg['body'] = body if six.PY2: return salt.utils.msgpack.dumps(framed_msg) else: return salt.utils.msgpack.dumps(framed_msg, use_bin_type=True) def _decode_embedded_list(src): ''' Convert enbedded bytes to strings if possible. List helper. ''' output = [] for elem in src: if isinstance(elem, dict): elem = _decode_embedded_dict(elem) elif isinstance(elem, list): elem = _decode_embedded_list(elem) # pylint: disable=redefined-variable-type elif isinstance(elem, bytes): try: elem = elem.decode() except UnicodeError: pass output.append(elem) return output def decode_embedded_strs(src): ''' Convert enbedded bytes to strings if possible. This is necessary because Python 3 makes a distinction between these types. This wouldn't be needed if we used "use_bin_type=True" when encoding and "encoding='utf-8'" when decoding. Unfortunately, this would break backwards compatibility due to a change in wire protocol, so this less than ideal solution is used instead. ''' if not six.PY3: return src if isinstance(src, dict): return _decode_embedded_dict(src) elif isinstance(src, list): return _decode_embedded_list(src) elif isinstance(src, bytes): try: return src.decode() # pylint: disable=redefined-variable-type except UnicodeError: return src else: return src
saltstack/salt
salt/transport/frame.py
decode_embedded_strs
python
def decode_embedded_strs(src): ''' Convert enbedded bytes to strings if possible. This is necessary because Python 3 makes a distinction between these types. This wouldn't be needed if we used "use_bin_type=True" when encoding and "encoding='utf-8'" when decoding. Unfortunately, this would break backwards compatibility due to a change in wire protocol, so this less than ideal solution is used instead. ''' if not six.PY3: return src if isinstance(src, dict): return _decode_embedded_dict(src) elif isinstance(src, list): return _decode_embedded_list(src) elif isinstance(src, bytes): try: return src.decode() # pylint: disable=redefined-variable-type except UnicodeError: return src else: return src
Convert enbedded bytes to strings if possible. This is necessary because Python 3 makes a distinction between these types. This wouldn't be needed if we used "use_bin_type=True" when encoding and "encoding='utf-8'" when decoding. Unfortunately, this would break backwards compatibility due to a change in wire protocol, so this less than ideal solution is used instead.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/frame.py#L88-L112
null
# -*- coding: utf-8 -*- ''' Helper functions for transport components to handle message framing ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.utils.msgpack from salt.ext import six def frame_msg(body, header=None, raw_body=False): # pylint: disable=unused-argument ''' Frame the given message with our wire protocol ''' framed_msg = {} if header is None: header = {} framed_msg['head'] = header framed_msg['body'] = body return salt.utils.msgpack.dumps(framed_msg) def frame_msg_ipc(body, header=None, raw_body=False): # pylint: disable=unused-argument ''' Frame the given message with our wire protocol for IPC For IPC, we don't need to be backwards compatible, so use the more efficient "use_bin_type=True" on Python 3. ''' framed_msg = {} if header is None: header = {} framed_msg['head'] = header framed_msg['body'] = body if six.PY2: return salt.utils.msgpack.dumps(framed_msg) else: return salt.utils.msgpack.dumps(framed_msg, use_bin_type=True) def _decode_embedded_list(src): ''' Convert enbedded bytes to strings if possible. List helper. ''' output = [] for elem in src: if isinstance(elem, dict): elem = _decode_embedded_dict(elem) elif isinstance(elem, list): elem = _decode_embedded_list(elem) # pylint: disable=redefined-variable-type elif isinstance(elem, bytes): try: elem = elem.decode() except UnicodeError: pass output.append(elem) return output def _decode_embedded_dict(src): ''' Convert enbedded bytes to strings if possible. Dict helper. ''' output = {} for key, val in six.iteritems(src): if isinstance(val, dict): val = _decode_embedded_dict(val) elif isinstance(val, list): val = _decode_embedded_list(val) # pylint: disable=redefined-variable-type elif isinstance(val, bytes): try: val = val.decode() except UnicodeError: pass if isinstance(key, bytes): try: key = key.decode() except UnicodeError: pass output[key] = val return output
saltstack/salt
salt/states/disk.py
_validate_int
python
def _validate_int(name, value, limits=(), strip='%'): ''' Validate the named integer within the supplied limits inclusive and strip supplied unit characters ''' comment = '' # Must be integral try: if isinstance(value, string_types): value = value.strip(' ' + strip) value = int(value) except (TypeError, ValueError): comment += '{0} must be an integer '.format(name) # Must be in range else: if len(limits) == 2: if value < limits[0] or value > limits[1]: comment += '{0} must be in the range [{1[0]}, {1[1]}] '.format(name, limits) return value, comment
Validate the named integer within the supplied limits inclusive and strip supplied unit characters
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/disk.py#L57-L75
null
# -*- coding: utf-8 -*- ''' Disk monitoring state Monitor the state of disk resources. The ``disk.status`` function can be used to report that the used space of a filesystem is within the specified limits. .. code-block:: sls used_space: disk.status: - name: /dev/xda1 - maximum: 79% - minimum: 11% It can be used with an ``onfail`` requisite, for example, to take additional action in response to or in preparation for other states. .. code-block:: sls storage_threshold: disk.status: - name: /dev/xda1 - maximum: 97% clear_cache: cmd.run: - name: rm -r /var/cache/app - onfail: - disk: storage_threshold To use kilobytes (KB) for ``minimum`` and ``maximum`` rather than percents, specify the ``absolute`` flag: .. code-block:: sls used_space: disk.status: - name: /dev/xda1 - minimum: 1024 KB - maximum: 1048576 KB - absolute: True ''' from __future__ import absolute_import, print_function, unicode_literals # Import salt libs from salt.ext.six import string_types from os import path __monitor__ = [ 'status', ] def _status_mount(name, ret, minimum, maximum, absolute, free, data): # Get used space if absolute: used = int(data[name]['used']) available = int(data[name]['available']) else: # POSIX-compliant df output reports percent used as 'capacity' used = int(data[name]['capacity'].strip('%')) available = 100 - used # Collect return information ret['data'] = data[name] return _check_min_max(absolute, free, available, used, maximum, minimum, ret) def _status_path(directory, ret, minimum, maximum, absolute, free): if path.isdir(directory) is False: ret['result'] = False ret['comment'] += ('Directory {0} does not exist or is not a directory'.format(directory)) return ret data = __salt__['status.diskusage'](directory) if absolute: used = int(data[directory]['total']) - int(data[directory]['available']) available = int(data[directory]['available']) else: if int(data[directory]['total']) == 0: used = 0 available = 0 else: used = round(float(int(data[directory]['total']) - int(data[directory]['available'])) / int(data[directory]['total']) * 100, 1) available = round(float(data[directory]['available']) / int(data[directory]['total']) * 100, 1) ret['data'] = data return _check_min_max(absolute, free, available, used, maximum, minimum, ret) def _check_min_max(absolute, free, available, used, maximum, minimum, ret): unit = 'KB' if absolute else '%' if minimum is not None: if free: if available < minimum: ret['comment'] = ('Disk available space is below minimum' ' of {0} {2} at {1} {2}' ''.format(minimum, available, unit) ) return ret else: if used < minimum: ret['comment'] = ('Disk used space is below minimum' ' of {0} {2} at {1} {2}' ''.format(minimum, used, unit) ) return ret if maximum is not None: if free: if available > maximum: ret['comment'] = ('Disk available space is above maximum' ' of {0} {2} at {1} {2}' ''.format(maximum, available, unit) ) return ret else: if used > maximum: ret['comment'] = ('Disk used space is above maximum' ' of {0} {2} at {1} {2}' ''.format(maximum, used, unit) ) return ret ret['comment'] = 'Disk used space in acceptable range' ret['result'] = True return ret def status(name, maximum=None, minimum=None, absolute=False, free=False): ''' Return the current disk usage stats for the named mount point name Disk mount or directory for which to check used space maximum The maximum disk utilization minimum The minimum disk utilization absolute By default, the utilization is measured in percentage. Set the `absolute` flag to use kilobytes. .. versionadded:: 2016.11.0 free By default, `minimum` & `maximum` refer to the amount of used space. Set to `True` to evaluate the free space instead. ''' # Monitoring state, no changes will be made so no test interface needed ret = {'name': name, 'result': False, 'comment': '', 'changes': {}, 'data': {}} # Data field for monitoring state # Validate extrema if maximum is not None: if not absolute: maximum, comment = _validate_int('maximum', maximum, [0, 100]) else: maximum, comment = _validate_int('maximum', maximum, strip='KB') ret['comment'] += comment if minimum is not None: if not absolute: minimum, comment = _validate_int('minimum', minimum, [0, 100]) else: minimum, comment = _validate_int('minimum', minimum, strip='KB') ret['comment'] += comment if minimum is not None and maximum is not None: if minimum >= maximum: ret['comment'] += 'minimum must be less than maximum ' if ret['comment']: return ret data = __salt__['disk.usage']() # Validate name if name not in data: ret['comment'] += ('Disk mount {0} not present. '.format(name)) return _status_path(name, ret, minimum, maximum, absolute, free) else: return _status_mount(name, ret, minimum, maximum, absolute, free, data)
saltstack/salt
salt/states/disk.py
status
python
def status(name, maximum=None, minimum=None, absolute=False, free=False): ''' Return the current disk usage stats for the named mount point name Disk mount or directory for which to check used space maximum The maximum disk utilization minimum The minimum disk utilization absolute By default, the utilization is measured in percentage. Set the `absolute` flag to use kilobytes. .. versionadded:: 2016.11.0 free By default, `minimum` & `maximum` refer to the amount of used space. Set to `True` to evaluate the free space instead. ''' # Monitoring state, no changes will be made so no test interface needed ret = {'name': name, 'result': False, 'comment': '', 'changes': {}, 'data': {}} # Data field for monitoring state # Validate extrema if maximum is not None: if not absolute: maximum, comment = _validate_int('maximum', maximum, [0, 100]) else: maximum, comment = _validate_int('maximum', maximum, strip='KB') ret['comment'] += comment if minimum is not None: if not absolute: minimum, comment = _validate_int('minimum', minimum, [0, 100]) else: minimum, comment = _validate_int('minimum', minimum, strip='KB') ret['comment'] += comment if minimum is not None and maximum is not None: if minimum >= maximum: ret['comment'] += 'minimum must be less than maximum ' if ret['comment']: return ret data = __salt__['disk.usage']() # Validate name if name not in data: ret['comment'] += ('Disk mount {0} not present. '.format(name)) return _status_path(name, ret, minimum, maximum, absolute, free) else: return _status_mount(name, ret, minimum, maximum, absolute, free, data)
Return the current disk usage stats for the named mount point name Disk mount or directory for which to check used space maximum The maximum disk utilization minimum The minimum disk utilization absolute By default, the utilization is measured in percentage. Set the `absolute` flag to use kilobytes. .. versionadded:: 2016.11.0 free By default, `minimum` & `maximum` refer to the amount of used space. Set to `True` to evaluate the free space instead.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/disk.py#L154-L210
[ "def _validate_int(name, value, limits=(), strip='%'):\n '''\n Validate the named integer within the supplied limits inclusive and\n strip supplied unit characters\n '''\n comment = ''\n # Must be integral\n try:\n if isinstance(value, string_types):\n value = value.strip(' ' + strip)\n value = int(value)\n except (TypeError, ValueError):\n comment += '{0} must be an integer '.format(name)\n # Must be in range\n else:\n if len(limits) == 2:\n if value < limits[0] or value > limits[1]:\n comment += '{0} must be in the range [{1[0]}, {1[1]}] '.format(name, limits)\n return value, comment\n", "def _status_mount(name, ret, minimum, maximum, absolute, free, data):\n # Get used space\n if absolute:\n used = int(data[name]['used'])\n available = int(data[name]['available'])\n else:\n # POSIX-compliant df output reports percent used as 'capacity'\n used = int(data[name]['capacity'].strip('%'))\n available = 100 - used\n\n # Collect return information\n ret['data'] = data[name]\n return _check_min_max(absolute, free, available, used, maximum, minimum, ret)\n", "def _status_path(directory, ret, minimum, maximum, absolute, free):\n if path.isdir(directory) is False:\n ret['result'] = False\n ret['comment'] += ('Directory {0} does not exist or is not a directory'.format(directory))\n return ret\n\n data = __salt__['status.diskusage'](directory)\n\n if absolute:\n used = int(data[directory]['total']) - int(data[directory]['available'])\n available = int(data[directory]['available'])\n else:\n if int(data[directory]['total']) == 0:\n used = 0\n available = 0\n else:\n used = round(float(int(data[directory]['total']) - int(data[directory]['available'])) /\n int(data[directory]['total']) * 100, 1)\n available = round(float(data[directory]['available']) / int(data[directory]['total']) * 100, 1)\n\n ret['data'] = data\n return _check_min_max(absolute, free, available, used, maximum, minimum, ret)\n" ]
# -*- coding: utf-8 -*- ''' Disk monitoring state Monitor the state of disk resources. The ``disk.status`` function can be used to report that the used space of a filesystem is within the specified limits. .. code-block:: sls used_space: disk.status: - name: /dev/xda1 - maximum: 79% - minimum: 11% It can be used with an ``onfail`` requisite, for example, to take additional action in response to or in preparation for other states. .. code-block:: sls storage_threshold: disk.status: - name: /dev/xda1 - maximum: 97% clear_cache: cmd.run: - name: rm -r /var/cache/app - onfail: - disk: storage_threshold To use kilobytes (KB) for ``minimum`` and ``maximum`` rather than percents, specify the ``absolute`` flag: .. code-block:: sls used_space: disk.status: - name: /dev/xda1 - minimum: 1024 KB - maximum: 1048576 KB - absolute: True ''' from __future__ import absolute_import, print_function, unicode_literals # Import salt libs from salt.ext.six import string_types from os import path __monitor__ = [ 'status', ] def _validate_int(name, value, limits=(), strip='%'): ''' Validate the named integer within the supplied limits inclusive and strip supplied unit characters ''' comment = '' # Must be integral try: if isinstance(value, string_types): value = value.strip(' ' + strip) value = int(value) except (TypeError, ValueError): comment += '{0} must be an integer '.format(name) # Must be in range else: if len(limits) == 2: if value < limits[0] or value > limits[1]: comment += '{0} must be in the range [{1[0]}, {1[1]}] '.format(name, limits) return value, comment def _status_mount(name, ret, minimum, maximum, absolute, free, data): # Get used space if absolute: used = int(data[name]['used']) available = int(data[name]['available']) else: # POSIX-compliant df output reports percent used as 'capacity' used = int(data[name]['capacity'].strip('%')) available = 100 - used # Collect return information ret['data'] = data[name] return _check_min_max(absolute, free, available, used, maximum, minimum, ret) def _status_path(directory, ret, minimum, maximum, absolute, free): if path.isdir(directory) is False: ret['result'] = False ret['comment'] += ('Directory {0} does not exist or is not a directory'.format(directory)) return ret data = __salt__['status.diskusage'](directory) if absolute: used = int(data[directory]['total']) - int(data[directory]['available']) available = int(data[directory]['available']) else: if int(data[directory]['total']) == 0: used = 0 available = 0 else: used = round(float(int(data[directory]['total']) - int(data[directory]['available'])) / int(data[directory]['total']) * 100, 1) available = round(float(data[directory]['available']) / int(data[directory]['total']) * 100, 1) ret['data'] = data return _check_min_max(absolute, free, available, used, maximum, minimum, ret) def _check_min_max(absolute, free, available, used, maximum, minimum, ret): unit = 'KB' if absolute else '%' if minimum is not None: if free: if available < minimum: ret['comment'] = ('Disk available space is below minimum' ' of {0} {2} at {1} {2}' ''.format(minimum, available, unit) ) return ret else: if used < minimum: ret['comment'] = ('Disk used space is below minimum' ' of {0} {2} at {1} {2}' ''.format(minimum, used, unit) ) return ret if maximum is not None: if free: if available > maximum: ret['comment'] = ('Disk available space is above maximum' ' of {0} {2} at {1} {2}' ''.format(maximum, available, unit) ) return ret else: if used > maximum: ret['comment'] = ('Disk used space is above maximum' ' of {0} {2} at {1} {2}' ''.format(maximum, used, unit) ) return ret ret['comment'] = 'Disk used space in acceptable range' ret['result'] = True return ret
saltstack/salt
salt/states/ssh_known_hosts.py
present
python
def present( name, user=None, fingerprint=None, key=None, port=None, enc=None, config=None, hash_known_hosts=True, timeout=5, fingerprint_hash_type=None): ''' Verifies that the specified host is known by the specified user On many systems, specifically those running with openssh 4 or older, the ``enc`` option must be set, only openssh 5 and above can detect the key type. name The name of the remote host (e.g. "github.com") Note that only a single hostname is supported, if foo.example.com and bar.example.com have the same host you will need two separate Salt States to represent them. user The user who owns the ssh authorized keys file to modify fingerprint The fingerprint of the key which must be present in the known_hosts file (optional if key specified) key The public key which must be present in the known_hosts file (optional if fingerprint specified) port optional parameter, port which will be used to when requesting the public key from the remote host, defaults to port 22. enc Defines what type of key is being used, can be ed25519, ecdsa ssh-rsa or ssh-dss config The location of the authorized keys file relative to the user's home directory, defaults to ".ssh/known_hosts". If no user is specified, defaults to "/etc/ssh/ssh_known_hosts". If present, must be an absolute path when a user is not specified. hash_known_hosts : True Hash all hostnames and addresses in the known hosts file. timeout : int Set the timeout for connection attempts. If ``timeout`` seconds have elapsed since a connection was initiated to a host or since the last time anything was read from that host, then the connection is closed and the host in question considered unavailable. Default is 5 seconds. .. versionadded:: 2016.3.0 fingerprint_hash_type The public key fingerprint hash type that the public key fingerprint was originally hashed with. This defaults to ``sha256`` if not specified. .. versionadded:: 2016.11.4 .. versionchanged:: 2017.7.0: default changed from ``md5`` to ``sha256`` ''' ret = {'name': name, 'changes': {}, 'result': None if __opts__['test'] else True, 'comment': ''} if not user: config = config or '/etc/ssh/ssh_known_hosts' else: config = config or '.ssh/known_hosts' if not user and not os.path.isabs(config): comment = 'If not specifying a "user", specify an absolute "config".' ret['result'] = False return dict(ret, comment=comment) if __opts__['test']: if key and fingerprint: comment = 'Specify either "key" or "fingerprint", not both.' ret['result'] = False return dict(ret, comment=comment) elif key and not enc: comment = 'Required argument "enc" if using "key" argument.' ret['result'] = False return dict(ret, comment=comment) try: result = __salt__['ssh.check_known_host'](user, name, key=key, fingerprint=fingerprint, config=config, port=port, fingerprint_hash_type=fingerprint_hash_type) except CommandNotFoundError as err: ret['result'] = False ret['comment'] = 'ssh.check_known_host error: {0}'.format(err) return ret if result == 'exists': comment = 'Host {0} is already in {1}'.format(name, config) ret['result'] = True return dict(ret, comment=comment) elif result == 'add': comment = 'Key for {0} is set to be added to {1}'.format(name, config) return dict(ret, comment=comment) else: # 'update' comment = 'Key for {0} is set to be updated in {1}'.format(name, config) return dict(ret, comment=comment) result = __salt__['ssh.set_known_host']( user=user, hostname=name, fingerprint=fingerprint, key=key, port=port, enc=enc, config=config, hash_known_hosts=hash_known_hosts, timeout=timeout, fingerprint_hash_type=fingerprint_hash_type) if result['status'] == 'exists': return dict(ret, comment='{0} already exists in {1}'.format(name, config)) elif result['status'] == 'error': return dict(ret, result=False, comment=result['error']) else: # 'updated' if key: new_key = result['new'][0]['key'] return dict(ret, changes={'old': result['old'], 'new': result['new']}, comment='{0}\'s key saved to {1} (key: {2})'.format( name, config, new_key)) else: fingerprint = result['new'][0]['fingerprint'] return dict(ret, changes={'old': result['old'], 'new': result['new']}, comment='{0}\'s key saved to {1} (fingerprint: {2})'.format( name, config, fingerprint))
Verifies that the specified host is known by the specified user On many systems, specifically those running with openssh 4 or older, the ``enc`` option must be set, only openssh 5 and above can detect the key type. name The name of the remote host (e.g. "github.com") Note that only a single hostname is supported, if foo.example.com and bar.example.com have the same host you will need two separate Salt States to represent them. user The user who owns the ssh authorized keys file to modify fingerprint The fingerprint of the key which must be present in the known_hosts file (optional if key specified) key The public key which must be present in the known_hosts file (optional if fingerprint specified) port optional parameter, port which will be used to when requesting the public key from the remote host, defaults to port 22. enc Defines what type of key is being used, can be ed25519, ecdsa ssh-rsa or ssh-dss config The location of the authorized keys file relative to the user's home directory, defaults to ".ssh/known_hosts". If no user is specified, defaults to "/etc/ssh/ssh_known_hosts". If present, must be an absolute path when a user is not specified. hash_known_hosts : True Hash all hostnames and addresses in the known hosts file. timeout : int Set the timeout for connection attempts. If ``timeout`` seconds have elapsed since a connection was initiated to a host or since the last time anything was read from that host, then the connection is closed and the host in question considered unavailable. Default is 5 seconds. .. versionadded:: 2016.3.0 fingerprint_hash_type The public key fingerprint hash type that the public key fingerprint was originally hashed with. This defaults to ``sha256`` if not specified. .. versionadded:: 2016.11.4 .. versionchanged:: 2017.7.0: default changed from ``md5`` to ``sha256``
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ssh_known_hosts.py#L45-L191
null
# -*- coding: utf-8 -*- ''' Control of SSH known_hosts entries ================================== Manage the information stored in the known_hosts files. .. code-block:: yaml github.com: ssh_known_hosts: - present - user: root - fingerprint: 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48 - fingerprint_hash_type: md5 example.com: ssh_known_hosts: - absent - user: root ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import os # Import Salt libs import salt.utils.platform from salt.exceptions import CommandNotFoundError # Define the state's virtual name __virtualname__ = 'ssh_known_hosts' def __virtual__(): ''' Does not work on Windows, requires ssh module functions ''' if salt.utils.platform.is_windows(): return False, 'ssh_known_hosts: Does not support Windows' return __virtualname__ def absent(name, user=None, config=None): ''' Verifies that the specified host is not known by the given user name The host name Note that only single host names are supported. If foo.example.com and bar.example.com are the same machine and you need to exclude both, you will need one Salt state for each. user The user who owns the ssh authorized keys file to modify config The location of the authorized keys file relative to the user's home directory, defaults to ".ssh/known_hosts". If no user is specified, defaults to "/etc/ssh/ssh_known_hosts". If present, must be an absolute path when a user is not specified. ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} if not user: config = config or '/etc/ssh/ssh_known_hosts' else: config = config or '.ssh/known_hosts' if not user and not os.path.isabs(config): comment = 'If not specifying a "user", specify an absolute "config".' ret['result'] = False return dict(ret, comment=comment) known_host = __salt__['ssh.get_known_host_entries'](user=user, hostname=name, config=config) if not known_host: return dict(ret, comment='Host is already absent') if __opts__['test']: comment = 'Key for {0} is set to be removed from {1}'.format(name, config) ret['result'] = None return dict(ret, comment=comment) rm_result = __salt__['ssh.rm_known_host'](user=user, hostname=name, config=config) if rm_result['status'] == 'error': return dict(ret, result=False, comment=rm_result['error']) else: return dict(ret, changes={'old': known_host, 'new': None}, result=True, comment=rm_result['comment'])
saltstack/salt
salt/states/ssh_known_hosts.py
absent
python
def absent(name, user=None, config=None): ''' Verifies that the specified host is not known by the given user name The host name Note that only single host names are supported. If foo.example.com and bar.example.com are the same machine and you need to exclude both, you will need one Salt state for each. user The user who owns the ssh authorized keys file to modify config The location of the authorized keys file relative to the user's home directory, defaults to ".ssh/known_hosts". If no user is specified, defaults to "/etc/ssh/ssh_known_hosts". If present, must be an absolute path when a user is not specified. ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} if not user: config = config or '/etc/ssh/ssh_known_hosts' else: config = config or '.ssh/known_hosts' if not user and not os.path.isabs(config): comment = 'If not specifying a "user", specify an absolute "config".' ret['result'] = False return dict(ret, comment=comment) known_host = __salt__['ssh.get_known_host_entries'](user=user, hostname=name, config=config) if not known_host: return dict(ret, comment='Host is already absent') if __opts__['test']: comment = 'Key for {0} is set to be removed from {1}'.format(name, config) ret['result'] = None return dict(ret, comment=comment) rm_result = __salt__['ssh.rm_known_host'](user=user, hostname=name, config=config) if rm_result['status'] == 'error': return dict(ret, result=False, comment=rm_result['error']) else: return dict(ret, changes={'old': known_host, 'new': None}, result=True, comment=rm_result['comment'])
Verifies that the specified host is not known by the given user name The host name Note that only single host names are supported. If foo.example.com and bar.example.com are the same machine and you need to exclude both, you will need one Salt state for each. user The user who owns the ssh authorized keys file to modify config The location of the authorized keys file relative to the user's home directory, defaults to ".ssh/known_hosts". If no user is specified, defaults to "/etc/ssh/ssh_known_hosts". If present, must be an absolute path when a user is not specified.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ssh_known_hosts.py#L194-L245
null
# -*- coding: utf-8 -*- ''' Control of SSH known_hosts entries ================================== Manage the information stored in the known_hosts files. .. code-block:: yaml github.com: ssh_known_hosts: - present - user: root - fingerprint: 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48 - fingerprint_hash_type: md5 example.com: ssh_known_hosts: - absent - user: root ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import os # Import Salt libs import salt.utils.platform from salt.exceptions import CommandNotFoundError # Define the state's virtual name __virtualname__ = 'ssh_known_hosts' def __virtual__(): ''' Does not work on Windows, requires ssh module functions ''' if salt.utils.platform.is_windows(): return False, 'ssh_known_hosts: Does not support Windows' return __virtualname__ def present( name, user=None, fingerprint=None, key=None, port=None, enc=None, config=None, hash_known_hosts=True, timeout=5, fingerprint_hash_type=None): ''' Verifies that the specified host is known by the specified user On many systems, specifically those running with openssh 4 or older, the ``enc`` option must be set, only openssh 5 and above can detect the key type. name The name of the remote host (e.g. "github.com") Note that only a single hostname is supported, if foo.example.com and bar.example.com have the same host you will need two separate Salt States to represent them. user The user who owns the ssh authorized keys file to modify fingerprint The fingerprint of the key which must be present in the known_hosts file (optional if key specified) key The public key which must be present in the known_hosts file (optional if fingerprint specified) port optional parameter, port which will be used to when requesting the public key from the remote host, defaults to port 22. enc Defines what type of key is being used, can be ed25519, ecdsa ssh-rsa or ssh-dss config The location of the authorized keys file relative to the user's home directory, defaults to ".ssh/known_hosts". If no user is specified, defaults to "/etc/ssh/ssh_known_hosts". If present, must be an absolute path when a user is not specified. hash_known_hosts : True Hash all hostnames and addresses in the known hosts file. timeout : int Set the timeout for connection attempts. If ``timeout`` seconds have elapsed since a connection was initiated to a host or since the last time anything was read from that host, then the connection is closed and the host in question considered unavailable. Default is 5 seconds. .. versionadded:: 2016.3.0 fingerprint_hash_type The public key fingerprint hash type that the public key fingerprint was originally hashed with. This defaults to ``sha256`` if not specified. .. versionadded:: 2016.11.4 .. versionchanged:: 2017.7.0: default changed from ``md5`` to ``sha256`` ''' ret = {'name': name, 'changes': {}, 'result': None if __opts__['test'] else True, 'comment': ''} if not user: config = config or '/etc/ssh/ssh_known_hosts' else: config = config or '.ssh/known_hosts' if not user and not os.path.isabs(config): comment = 'If not specifying a "user", specify an absolute "config".' ret['result'] = False return dict(ret, comment=comment) if __opts__['test']: if key and fingerprint: comment = 'Specify either "key" or "fingerprint", not both.' ret['result'] = False return dict(ret, comment=comment) elif key and not enc: comment = 'Required argument "enc" if using "key" argument.' ret['result'] = False return dict(ret, comment=comment) try: result = __salt__['ssh.check_known_host'](user, name, key=key, fingerprint=fingerprint, config=config, port=port, fingerprint_hash_type=fingerprint_hash_type) except CommandNotFoundError as err: ret['result'] = False ret['comment'] = 'ssh.check_known_host error: {0}'.format(err) return ret if result == 'exists': comment = 'Host {0} is already in {1}'.format(name, config) ret['result'] = True return dict(ret, comment=comment) elif result == 'add': comment = 'Key for {0} is set to be added to {1}'.format(name, config) return dict(ret, comment=comment) else: # 'update' comment = 'Key for {0} is set to be updated in {1}'.format(name, config) return dict(ret, comment=comment) result = __salt__['ssh.set_known_host']( user=user, hostname=name, fingerprint=fingerprint, key=key, port=port, enc=enc, config=config, hash_known_hosts=hash_known_hosts, timeout=timeout, fingerprint_hash_type=fingerprint_hash_type) if result['status'] == 'exists': return dict(ret, comment='{0} already exists in {1}'.format(name, config)) elif result['status'] == 'error': return dict(ret, result=False, comment=result['error']) else: # 'updated' if key: new_key = result['new'][0]['key'] return dict(ret, changes={'old': result['old'], 'new': result['new']}, comment='{0}\'s key saved to {1} (key: {2})'.format( name, config, new_key)) else: fingerprint = result['new'][0]['fingerprint'] return dict(ret, changes={'old': result['old'], 'new': result['new']}, comment='{0}\'s key saved to {1} (fingerprint: {2})'.format( name, config, fingerprint))
saltstack/salt
salt/engines/__init__.py
start_engines
python
def start_engines(opts, proc_mgr, proxy=None): ''' Fire up the configured engines! ''' utils = salt.loader.utils(opts, proxy=proxy) if opts['__role'] == 'master': runners = salt.loader.runner(opts, utils=utils) else: runners = [] funcs = salt.loader.minion_mods(opts, utils=utils, proxy=proxy) engines = salt.loader.engines(opts, funcs, runners, utils, proxy=proxy) engines_opt = opts.get('engines', []) if isinstance(engines_opt, dict): engines_opt = [{k: v} for k, v in engines_opt.items()] # Function references are not picklable. Windows needs to pickle when # spawning processes. On Windows, these will need to be recalculated # in the spawned child process. if salt.utils.platform.is_windows(): runners = None utils = None funcs = None for engine in engines_opt: if isinstance(engine, dict): engine, engine_opts = next(iter(engine.items())) else: engine_opts = None engine_name = None if engine_opts is not None and 'engine_module' in engine_opts: fun = '{0}.start'.format(engine_opts['engine_module']) engine_name = engine del engine_opts['engine_module'] else: fun = '{0}.start'.format(engine) if fun in engines: start_func = engines[fun] if engine_name: name = '{0}.Engine({1}-{2})'.format(__name__, start_func.__module__, engine_name) else: name = '{0}.Engine({1})'.format(__name__, start_func.__module__) log.info('Starting Engine %s', name) proc_mgr.add_process( Engine, args=( opts, fun, engine_opts, funcs, runners, proxy ), name=name )
Fire up the configured engines!
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/__init__.py#L20-L77
[ "def add_process(self, tgt, args=None, kwargs=None, name=None):\n '''\n Create a processes and args + kwargs\n This will deterimine if it is a Process class, otherwise it assumes\n it is a function\n '''\n if args is None:\n args = []\n\n if kwargs is None:\n kwargs = {}\n\n if salt.utils.platform.is_windows():\n # Need to ensure that 'log_queue' and 'log_queue_level' is\n # correctly transferred to processes that inherit from\n # 'MultiprocessingProcess'.\n if type(MultiprocessingProcess) is type(tgt) and (\n issubclass(tgt, MultiprocessingProcess)):\n need_log_queue = True\n else:\n need_log_queue = False\n\n if need_log_queue:\n if 'log_queue' not in kwargs:\n if hasattr(self, 'log_queue'):\n kwargs['log_queue'] = self.log_queue\n else:\n kwargs['log_queue'] = (\n salt.log.setup.get_multiprocessing_logging_queue()\n )\n if 'log_queue_level' not in kwargs:\n if hasattr(self, 'log_queue_level'):\n kwargs['log_queue_level'] = self.log_queue_level\n else:\n kwargs['log_queue_level'] = (\n salt.log.setup.get_multiprocessing_logging_level()\n )\n\n # create a nicer name for the debug log\n if name is None:\n if isinstance(tgt, types.FunctionType):\n name = '{0}.{1}'.format(\n tgt.__module__,\n tgt.__name__,\n )\n else:\n name = '{0}{1}.{2}'.format(\n tgt.__module__,\n '.{0}'.format(tgt.__class__) if six.text_type(tgt.__class__) != \"<type 'type'>\" else '',\n tgt.__name__,\n )\n\n if type(multiprocessing.Process) is type(tgt) and issubclass(tgt, multiprocessing.Process):\n process = tgt(*args, **kwargs)\n else:\n process = multiprocessing.Process(target=tgt, args=args, kwargs=kwargs, name=name)\n\n if isinstance(process, SignalHandlingMultiprocessingProcess):\n with default_signals(signal.SIGINT, signal.SIGTERM):\n process.start()\n else:\n process.start()\n log.debug(\"Started '%s' with pid %s\", name, process.pid)\n self._process_map[process.pid] = {'tgt': tgt,\n 'args': args,\n 'kwargs': kwargs,\n 'Process': process}\n return process\n" ]
# -*- coding: utf-8 -*- ''' Initialize the engines system. This plugin system allows for complex services to be encapsulated within the salt plugin environment ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import multiprocessing import logging # Import salt libs import salt import salt.loader import salt.utils.platform from salt.utils.process import SignalHandlingMultiprocessingProcess log = logging.getLogger(__name__) class Engine(SignalHandlingMultiprocessingProcess): ''' Execute the given engine in a new process ''' def __init__(self, opts, fun, config, funcs, runners, proxy, **kwargs): ''' Set up the process executor ''' super(Engine, self).__init__(**kwargs) self.opts = opts self.config = config self.fun = fun self.funcs = funcs self.runners = runners self.proxy = proxy # __setstate__ and __getstate__ are only used on Windows. # We do this so that __init__ will be invoked on Windows in the child # process so that a register_after_fork() equivalent will work on Windows. def __setstate__(self, state): self._is_child = True self.__init__( state['opts'], state['fun'], state['config'], state['funcs'], state['runners'], state['proxy'], log_queue=state['log_queue'], log_queue_level=state['log_queue_level'] ) def __getstate__(self): return { 'opts': self.opts, 'fun': self.fun, 'config': self.config, 'funcs': self.funcs, 'runners': self.runners, 'proxy': self.proxy, 'log_queue': self.log_queue, 'log_queue_level': self.log_queue_level } def run(self): ''' Run the master service! ''' self.utils = salt.loader.utils(self.opts, proxy=self.proxy) if salt.utils.platform.is_windows(): # Calculate function references since they can't be pickled. if self.opts['__role'] == 'master': self.runners = salt.loader.runner(self.opts, utils=self.utils) else: self.runners = [] self.funcs = salt.loader.minion_mods(self.opts, utils=self.utils, proxy=self.proxy) self.engine = salt.loader.engines(self.opts, self.funcs, self.runners, self.utils, proxy=self.proxy) kwargs = self.config or {} try: self.engine[self.fun](**kwargs) except Exception as exc: log.critical( 'Engine \'%s\' could not be started!', self.fun.split('.')[0], exc_info=True )
saltstack/salt
salt/engines/__init__.py
Engine.run
python
def run(self): ''' Run the master service! ''' self.utils = salt.loader.utils(self.opts, proxy=self.proxy) if salt.utils.platform.is_windows(): # Calculate function references since they can't be pickled. if self.opts['__role'] == 'master': self.runners = salt.loader.runner(self.opts, utils=self.utils) else: self.runners = [] self.funcs = salt.loader.minion_mods(self.opts, utils=self.utils, proxy=self.proxy) self.engine = salt.loader.engines(self.opts, self.funcs, self.runners, self.utils, proxy=self.proxy) kwargs = self.config or {} try: self.engine[self.fun](**kwargs) except Exception as exc: log.critical( 'Engine \'%s\' could not be started!', self.fun.split('.')[0], exc_info=True )
Run the master service!
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/__init__.py#L124-L149
null
class Engine(SignalHandlingMultiprocessingProcess): ''' Execute the given engine in a new process ''' def __init__(self, opts, fun, config, funcs, runners, proxy, **kwargs): ''' Set up the process executor ''' super(Engine, self).__init__(**kwargs) self.opts = opts self.config = config self.fun = fun self.funcs = funcs self.runners = runners self.proxy = proxy # __setstate__ and __getstate__ are only used on Windows. # We do this so that __init__ will be invoked on Windows in the child # process so that a register_after_fork() equivalent will work on Windows. def __setstate__(self, state): self._is_child = True self.__init__( state['opts'], state['fun'], state['config'], state['funcs'], state['runners'], state['proxy'], log_queue=state['log_queue'], log_queue_level=state['log_queue_level'] ) def __getstate__(self): return { 'opts': self.opts, 'fun': self.fun, 'config': self.config, 'funcs': self.funcs, 'runners': self.runners, 'proxy': self.proxy, 'log_queue': self.log_queue, 'log_queue_level': self.log_queue_level }
saltstack/salt
salt/roster/range.py
targets
python
def targets(tgt, tgt_type='range', **kwargs): ''' Return the targets from a range query ''' r = seco.range.Range(__opts__['range_server']) log.debug('Range connection to \'%s\' established', __opts__['range_server']) hosts = [] try: log.debug('Querying range for \'%s\'', tgt) hosts = r.expand(tgt) except seco.range.RangeException as err: log.error('Range server exception: %s', err) return {} log.debug('Range responded with: \'%s\'', hosts) # Currently we only support giving a raw range entry, no target filtering supported other than what range returns :S tgt_func = { 'range': target_range, 'glob': target_range, # 'glob': target_glob, } log.debug('Filtering using tgt_type: \'%s\'', tgt_type) try: targeted_hosts = tgt_func[tgt_type](tgt, hosts) except KeyError: raise NotImplementedError log.debug('Targeting data for salt-ssh: \'%s\'', targeted_hosts) return targeted_hosts
Return the targets from a range query
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/range.py#L35-L66
null
# -*- coding: utf-8 -*- ''' This roster resolves targets from a range server. :depends: seco.range, https://github.com/ytoolshed/range When you want to use a range query for target matching, use ``--roster range``. For example: .. code-block:: bash salt-ssh --roster range '%%%example.range.cluster' test.ping ''' from __future__ import absolute_import, print_function, unicode_literals import fnmatch import copy import logging log = logging.getLogger(__name__) # Try to import range from https://github.com/ytoolshed/range HAS_RANGE = False try: import seco.range HAS_RANGE = True except ImportError: log.error('Unable to load range library') # pylint: enable=import-error def __virtual__(): return HAS_RANGE def target_range(tgt, hosts): ret = {} for host in hosts: ret[host] = copy.deepcopy(__opts__.get('roster_defaults', {})) ret[host].update({'host': host}) if __opts__.get('ssh_user'): ret[host].update({'user': __opts__['ssh_user']}) return ret def target_glob(tgt, hosts): ret = {} for host in hosts: if fnmatch.fnmatch(tgt, host): ret[host] = copy.deepcopy(__opts__.get('roster_defaults', {})) ret[host].update({'host': host}) if __opts__.get('ssh_user'): ret[host].update({'user': __opts__['ssh_user']}) return ret
saltstack/salt
salt/modules/modjk.py
_auth
python
def _auth(url, user, passwd, realm): ''' returns a authentication handler. ''' basic = _HTTPBasicAuthHandler() basic.add_password(realm=realm, uri=url, user=user, passwd=passwd) digest = _HTTPDigestAuthHandler() digest.add_password(realm=realm, uri=url, user=user, passwd=passwd) return _build_opener(basic, digest)
returns a authentication handler.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L56-L65
null
# -*- coding: utf-8 -*- ''' Control Modjk via the Apache Tomcat "Status" worker (http://tomcat.apache.org/connectors-doc/reference/status.html) Below is an example of the configuration needed for this module. This configuration data can be placed either in :ref:`grains <targeting-grains>` or :ref:`pillar <salt-pillars>`. If using grains, this can be accomplished :ref:`statically <static-custom-grains>` or via a :ref:`grain module <writing-grains>`. If using pillar, the yaml configuration can be placed directly into a pillar SLS file, making this both the easier and more dynamic method of configuring this module. .. code-block:: yaml modjk: default: url: http://localhost/jkstatus user: modjk pass: secret realm: authentication realm for digest passwords timeout: 5 otherVhost: url: http://otherVhost/jkstatus user: modjk pass: secret2 realm: authentication realm2 for digest passwords timeout: 600 ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module from salt.ext import six from salt.ext.six.moves.urllib.parse import urlencode as _urlencode from salt.ext.six.moves.urllib.request import ( HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, urlopen as _urlopen, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=import-error,no-name-in-module def __virtual__(): ''' Always load ''' return True def _do_http(opts, profile='default'): ''' Make the http request and return the data ''' ret = {} url = __salt__['config.get']('modjk:{0}:url'.format(profile), '') user = __salt__['config.get']('modjk:{0}:user'.format(profile), '') passwd = __salt__['config.get']('modjk:{0}:pass'.format(profile), '') realm = __salt__['config.get']('modjk:{0}:realm'.format(profile), '') timeout = __salt__['config.get']('modjk:{0}:timeout'.format(profile), '') if not url: raise Exception('missing url in profile {0}'.format(profile)) if user and passwd: auth = _auth(url=url, realm=realm, user=user, passwd=passwd) _install_opener(auth) url += '?{0}'.format(_urlencode(opts)) for line in _urlopen(url, timeout=timeout).read().splitlines(): splt = line.split('=', 1) if splt[0] in ret: ret[splt[0]] += ',{0}'.format(splt[1]) else: ret[splt[0]] = splt[1] return ret def _worker_ctl(worker, lbn, vwa, profile='default'): ''' enable/disable/stop a worker ''' cmd = { 'cmd': 'update', 'mime': 'prop', 'w': lbn, 'sw': worker, 'vwa': vwa, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def version(profile='default'): ''' Return the modjk version CLI Examples: .. code-block:: bash salt '*' modjk.version salt '*' modjk.version other-profile ''' cmd = { 'cmd': 'version', 'mime': 'prop', } return _do_http(cmd, profile)['worker.jk_version'].split('/')[-1] def get_running(profile='default'): ''' Get the current running config (not from disk) CLI Examples: .. code-block:: bash salt '*' modjk.get_running salt '*' modjk.get_running other-profile ''' cmd = { 'cmd': 'list', 'mime': 'prop', } return _do_http(cmd, profile) def dump_config(profile='default'): ''' Dump the original configuration that was loaded from disk CLI Examples: .. code-block:: bash salt '*' modjk.dump_config salt '*' modjk.dump_config other-profile ''' cmd = { 'cmd': 'dump', 'mime': 'prop', } return _do_http(cmd, profile) def list_configured_members(lbn, profile='default'): ''' Return a list of member workers from the configuration files CLI Examples: .. code-block:: bash salt '*' modjk.list_configured_members loadbalancer1 salt '*' modjk.list_configured_members loadbalancer1 other-profile ''' config = dump_config(profile) try: ret = config['worker.{0}.balance_workers'.format(lbn)] except KeyError: return [] return [_f for _f in ret.strip().split(',') if _f] def workers(profile='default'): ''' Return a list of member workers and their status CLI Examples: .. code-block:: bash salt '*' modjk.workers salt '*' modjk.workers other-profile ''' config = get_running(profile) lbn = config['worker.list'].split(',') worker_list = [] ret = {} for lb in lbn: try: worker_list.extend( config['worker.{0}.balance_workers'.format(lb)].split(',') ) except KeyError: pass worker_list = list(set(worker_list)) for worker in worker_list: ret[worker] = { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } return ret def recover_all(lbn, profile='default'): ''' Set the all the workers in lbn to recover and activate them if they are not CLI Examples: .. code-block:: bash salt '*' modjk.recover_all loadbalancer1 salt '*' modjk.recover_all loadbalancer1 other-profile ''' ret = {} config = get_running(profile) try: workers_ = config['worker.{0}.balance_workers'.format(lbn)].split(',') except KeyError: return ret for worker in workers_: curr_state = worker_status(worker, profile) if curr_state['activation'] != 'ACT': worker_activate(worker, lbn, profile) if not curr_state['state'].startswith('OK'): worker_recover(worker, lbn, profile) ret[worker] = worker_status(worker, profile) return ret def reset_stats(lbn, profile='default'): ''' Reset all runtime statistics for the load balancer CLI Examples: .. code-block:: bash salt '*' modjk.reset_stats loadbalancer1 salt '*' modjk.reset_stats loadbalancer1 other-profile ''' cmd = { 'cmd': 'reset', 'mime': 'prop', 'w': lbn, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def lb_edit(lbn, settings, profile='default'): ''' Edit the loadbalancer settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn return _do_http(settings, profile)['worker.result.type'] == 'OK' def bulk_stop(workers, lbn, profile='default'): ''' Stop all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_stop(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_activate(workers, lbn, profile='default'): ''' Activate all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_activate(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_disable(workers, lbn, profile='default'): ''' Disable all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_disable(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_recover(workers, lbn, profile='default'): ''' Recover all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_recover(worker, lbn, profile) except Exception: ret[worker] = False return ret def worker_status(worker, profile='default'): ''' Return the state of the worker CLI Examples: .. code-block:: bash salt '*' modjk.worker_status node1 salt '*' modjk.worker_status node1 other-profile ''' config = get_running(profile) try: return { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } except KeyError: return False def worker_recover(worker, lbn, profile='default'): ''' Set the worker to recover this module will fail if it is in OK state CLI Examples: .. code-block:: bash salt '*' modjk.worker_recover node1 loadbalancer1 salt '*' modjk.worker_recover node1 loadbalancer1 other-profile ''' cmd = { 'cmd': 'recover', 'mime': 'prop', 'w': lbn, 'sw': worker, } return _do_http(cmd, profile) def worker_disable(worker, lbn, profile='default'): ''' Set the worker to disable state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_disable node1 loadbalancer1 salt '*' modjk.worker_disable node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'd', profile) def worker_activate(worker, lbn, profile='default'): ''' Set the worker to activate state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'a', profile) def worker_stop(worker, lbn, profile='default'): ''' Set the worker to stopped state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 's', profile) def worker_edit(worker, lbn, settings, profile='default'): ''' Edit the worker settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn settings['sw'] = worker return _do_http(settings, profile)['worker.result.type'] == 'OK'
saltstack/salt
salt/modules/modjk.py
_do_http
python
def _do_http(opts, profile='default'): ''' Make the http request and return the data ''' ret = {} url = __salt__['config.get']('modjk:{0}:url'.format(profile), '') user = __salt__['config.get']('modjk:{0}:user'.format(profile), '') passwd = __salt__['config.get']('modjk:{0}:pass'.format(profile), '') realm = __salt__['config.get']('modjk:{0}:realm'.format(profile), '') timeout = __salt__['config.get']('modjk:{0}:timeout'.format(profile), '') if not url: raise Exception('missing url in profile {0}'.format(profile)) if user and passwd: auth = _auth(url=url, realm=realm, user=user, passwd=passwd) _install_opener(auth) url += '?{0}'.format(_urlencode(opts)) for line in _urlopen(url, timeout=timeout).read().splitlines(): splt = line.split('=', 1) if splt[0] in ret: ret[splt[0]] += ',{0}'.format(splt[1]) else: ret[splt[0]] = splt[1] return ret
Make the http request and return the data
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L68-L97
[ "def _auth(url, user, passwd, realm):\n '''\n returns a authentication handler.\n '''\n\n basic = _HTTPBasicAuthHandler()\n basic.add_password(realm=realm, uri=url, user=user, passwd=passwd)\n digest = _HTTPDigestAuthHandler()\n digest.add_password(realm=realm, uri=url, user=user, passwd=passwd)\n return _build_opener(basic, digest)\n" ]
# -*- coding: utf-8 -*- ''' Control Modjk via the Apache Tomcat "Status" worker (http://tomcat.apache.org/connectors-doc/reference/status.html) Below is an example of the configuration needed for this module. This configuration data can be placed either in :ref:`grains <targeting-grains>` or :ref:`pillar <salt-pillars>`. If using grains, this can be accomplished :ref:`statically <static-custom-grains>` or via a :ref:`grain module <writing-grains>`. If using pillar, the yaml configuration can be placed directly into a pillar SLS file, making this both the easier and more dynamic method of configuring this module. .. code-block:: yaml modjk: default: url: http://localhost/jkstatus user: modjk pass: secret realm: authentication realm for digest passwords timeout: 5 otherVhost: url: http://otherVhost/jkstatus user: modjk pass: secret2 realm: authentication realm2 for digest passwords timeout: 600 ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module from salt.ext import six from salt.ext.six.moves.urllib.parse import urlencode as _urlencode from salt.ext.six.moves.urllib.request import ( HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, urlopen as _urlopen, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=import-error,no-name-in-module def __virtual__(): ''' Always load ''' return True def _auth(url, user, passwd, realm): ''' returns a authentication handler. ''' basic = _HTTPBasicAuthHandler() basic.add_password(realm=realm, uri=url, user=user, passwd=passwd) digest = _HTTPDigestAuthHandler() digest.add_password(realm=realm, uri=url, user=user, passwd=passwd) return _build_opener(basic, digest) def _worker_ctl(worker, lbn, vwa, profile='default'): ''' enable/disable/stop a worker ''' cmd = { 'cmd': 'update', 'mime': 'prop', 'w': lbn, 'sw': worker, 'vwa': vwa, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def version(profile='default'): ''' Return the modjk version CLI Examples: .. code-block:: bash salt '*' modjk.version salt '*' modjk.version other-profile ''' cmd = { 'cmd': 'version', 'mime': 'prop', } return _do_http(cmd, profile)['worker.jk_version'].split('/')[-1] def get_running(profile='default'): ''' Get the current running config (not from disk) CLI Examples: .. code-block:: bash salt '*' modjk.get_running salt '*' modjk.get_running other-profile ''' cmd = { 'cmd': 'list', 'mime': 'prop', } return _do_http(cmd, profile) def dump_config(profile='default'): ''' Dump the original configuration that was loaded from disk CLI Examples: .. code-block:: bash salt '*' modjk.dump_config salt '*' modjk.dump_config other-profile ''' cmd = { 'cmd': 'dump', 'mime': 'prop', } return _do_http(cmd, profile) def list_configured_members(lbn, profile='default'): ''' Return a list of member workers from the configuration files CLI Examples: .. code-block:: bash salt '*' modjk.list_configured_members loadbalancer1 salt '*' modjk.list_configured_members loadbalancer1 other-profile ''' config = dump_config(profile) try: ret = config['worker.{0}.balance_workers'.format(lbn)] except KeyError: return [] return [_f for _f in ret.strip().split(',') if _f] def workers(profile='default'): ''' Return a list of member workers and their status CLI Examples: .. code-block:: bash salt '*' modjk.workers salt '*' modjk.workers other-profile ''' config = get_running(profile) lbn = config['worker.list'].split(',') worker_list = [] ret = {} for lb in lbn: try: worker_list.extend( config['worker.{0}.balance_workers'.format(lb)].split(',') ) except KeyError: pass worker_list = list(set(worker_list)) for worker in worker_list: ret[worker] = { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } return ret def recover_all(lbn, profile='default'): ''' Set the all the workers in lbn to recover and activate them if they are not CLI Examples: .. code-block:: bash salt '*' modjk.recover_all loadbalancer1 salt '*' modjk.recover_all loadbalancer1 other-profile ''' ret = {} config = get_running(profile) try: workers_ = config['worker.{0}.balance_workers'.format(lbn)].split(',') except KeyError: return ret for worker in workers_: curr_state = worker_status(worker, profile) if curr_state['activation'] != 'ACT': worker_activate(worker, lbn, profile) if not curr_state['state'].startswith('OK'): worker_recover(worker, lbn, profile) ret[worker] = worker_status(worker, profile) return ret def reset_stats(lbn, profile='default'): ''' Reset all runtime statistics for the load balancer CLI Examples: .. code-block:: bash salt '*' modjk.reset_stats loadbalancer1 salt '*' modjk.reset_stats loadbalancer1 other-profile ''' cmd = { 'cmd': 'reset', 'mime': 'prop', 'w': lbn, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def lb_edit(lbn, settings, profile='default'): ''' Edit the loadbalancer settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn return _do_http(settings, profile)['worker.result.type'] == 'OK' def bulk_stop(workers, lbn, profile='default'): ''' Stop all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_stop(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_activate(workers, lbn, profile='default'): ''' Activate all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_activate(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_disable(workers, lbn, profile='default'): ''' Disable all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_disable(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_recover(workers, lbn, profile='default'): ''' Recover all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_recover(worker, lbn, profile) except Exception: ret[worker] = False return ret def worker_status(worker, profile='default'): ''' Return the state of the worker CLI Examples: .. code-block:: bash salt '*' modjk.worker_status node1 salt '*' modjk.worker_status node1 other-profile ''' config = get_running(profile) try: return { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } except KeyError: return False def worker_recover(worker, lbn, profile='default'): ''' Set the worker to recover this module will fail if it is in OK state CLI Examples: .. code-block:: bash salt '*' modjk.worker_recover node1 loadbalancer1 salt '*' modjk.worker_recover node1 loadbalancer1 other-profile ''' cmd = { 'cmd': 'recover', 'mime': 'prop', 'w': lbn, 'sw': worker, } return _do_http(cmd, profile) def worker_disable(worker, lbn, profile='default'): ''' Set the worker to disable state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_disable node1 loadbalancer1 salt '*' modjk.worker_disable node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'd', profile) def worker_activate(worker, lbn, profile='default'): ''' Set the worker to activate state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'a', profile) def worker_stop(worker, lbn, profile='default'): ''' Set the worker to stopped state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 's', profile) def worker_edit(worker, lbn, settings, profile='default'): ''' Edit the worker settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn settings['sw'] = worker return _do_http(settings, profile)['worker.result.type'] == 'OK'
saltstack/salt
salt/modules/modjk.py
_worker_ctl
python
def _worker_ctl(worker, lbn, vwa, profile='default'): ''' enable/disable/stop a worker ''' cmd = { 'cmd': 'update', 'mime': 'prop', 'w': lbn, 'sw': worker, 'vwa': vwa, } return _do_http(cmd, profile)['worker.result.type'] == 'OK'
enable/disable/stop a worker
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L100-L112
[ "def _do_http(opts, profile='default'):\n '''\n Make the http request and return the data\n '''\n\n ret = {}\n\n url = __salt__['config.get']('modjk:{0}:url'.format(profile), '')\n user = __salt__['config.get']('modjk:{0}:user'.format(profile), '')\n passwd = __salt__['config.get']('modjk:{0}:pass'.format(profile), '')\n realm = __salt__['config.get']('modjk:{0}:realm'.format(profile), '')\n timeout = __salt__['config.get']('modjk:{0}:timeout'.format(profile), '')\n\n if not url:\n raise Exception('missing url in profile {0}'.format(profile))\n\n if user and passwd:\n auth = _auth(url=url, realm=realm, user=user, passwd=passwd)\n _install_opener(auth)\n\n url += '?{0}'.format(_urlencode(opts))\n\n for line in _urlopen(url, timeout=timeout).read().splitlines():\n splt = line.split('=', 1)\n if splt[0] in ret:\n ret[splt[0]] += ',{0}'.format(splt[1])\n else:\n ret[splt[0]] = splt[1]\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Control Modjk via the Apache Tomcat "Status" worker (http://tomcat.apache.org/connectors-doc/reference/status.html) Below is an example of the configuration needed for this module. This configuration data can be placed either in :ref:`grains <targeting-grains>` or :ref:`pillar <salt-pillars>`. If using grains, this can be accomplished :ref:`statically <static-custom-grains>` or via a :ref:`grain module <writing-grains>`. If using pillar, the yaml configuration can be placed directly into a pillar SLS file, making this both the easier and more dynamic method of configuring this module. .. code-block:: yaml modjk: default: url: http://localhost/jkstatus user: modjk pass: secret realm: authentication realm for digest passwords timeout: 5 otherVhost: url: http://otherVhost/jkstatus user: modjk pass: secret2 realm: authentication realm2 for digest passwords timeout: 600 ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module from salt.ext import six from salt.ext.six.moves.urllib.parse import urlencode as _urlencode from salt.ext.six.moves.urllib.request import ( HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, urlopen as _urlopen, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=import-error,no-name-in-module def __virtual__(): ''' Always load ''' return True def _auth(url, user, passwd, realm): ''' returns a authentication handler. ''' basic = _HTTPBasicAuthHandler() basic.add_password(realm=realm, uri=url, user=user, passwd=passwd) digest = _HTTPDigestAuthHandler() digest.add_password(realm=realm, uri=url, user=user, passwd=passwd) return _build_opener(basic, digest) def _do_http(opts, profile='default'): ''' Make the http request and return the data ''' ret = {} url = __salt__['config.get']('modjk:{0}:url'.format(profile), '') user = __salt__['config.get']('modjk:{0}:user'.format(profile), '') passwd = __salt__['config.get']('modjk:{0}:pass'.format(profile), '') realm = __salt__['config.get']('modjk:{0}:realm'.format(profile), '') timeout = __salt__['config.get']('modjk:{0}:timeout'.format(profile), '') if not url: raise Exception('missing url in profile {0}'.format(profile)) if user and passwd: auth = _auth(url=url, realm=realm, user=user, passwd=passwd) _install_opener(auth) url += '?{0}'.format(_urlencode(opts)) for line in _urlopen(url, timeout=timeout).read().splitlines(): splt = line.split('=', 1) if splt[0] in ret: ret[splt[0]] += ',{0}'.format(splt[1]) else: ret[splt[0]] = splt[1] return ret def version(profile='default'): ''' Return the modjk version CLI Examples: .. code-block:: bash salt '*' modjk.version salt '*' modjk.version other-profile ''' cmd = { 'cmd': 'version', 'mime': 'prop', } return _do_http(cmd, profile)['worker.jk_version'].split('/')[-1] def get_running(profile='default'): ''' Get the current running config (not from disk) CLI Examples: .. code-block:: bash salt '*' modjk.get_running salt '*' modjk.get_running other-profile ''' cmd = { 'cmd': 'list', 'mime': 'prop', } return _do_http(cmd, profile) def dump_config(profile='default'): ''' Dump the original configuration that was loaded from disk CLI Examples: .. code-block:: bash salt '*' modjk.dump_config salt '*' modjk.dump_config other-profile ''' cmd = { 'cmd': 'dump', 'mime': 'prop', } return _do_http(cmd, profile) def list_configured_members(lbn, profile='default'): ''' Return a list of member workers from the configuration files CLI Examples: .. code-block:: bash salt '*' modjk.list_configured_members loadbalancer1 salt '*' modjk.list_configured_members loadbalancer1 other-profile ''' config = dump_config(profile) try: ret = config['worker.{0}.balance_workers'.format(lbn)] except KeyError: return [] return [_f for _f in ret.strip().split(',') if _f] def workers(profile='default'): ''' Return a list of member workers and their status CLI Examples: .. code-block:: bash salt '*' modjk.workers salt '*' modjk.workers other-profile ''' config = get_running(profile) lbn = config['worker.list'].split(',') worker_list = [] ret = {} for lb in lbn: try: worker_list.extend( config['worker.{0}.balance_workers'.format(lb)].split(',') ) except KeyError: pass worker_list = list(set(worker_list)) for worker in worker_list: ret[worker] = { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } return ret def recover_all(lbn, profile='default'): ''' Set the all the workers in lbn to recover and activate them if they are not CLI Examples: .. code-block:: bash salt '*' modjk.recover_all loadbalancer1 salt '*' modjk.recover_all loadbalancer1 other-profile ''' ret = {} config = get_running(profile) try: workers_ = config['worker.{0}.balance_workers'.format(lbn)].split(',') except KeyError: return ret for worker in workers_: curr_state = worker_status(worker, profile) if curr_state['activation'] != 'ACT': worker_activate(worker, lbn, profile) if not curr_state['state'].startswith('OK'): worker_recover(worker, lbn, profile) ret[worker] = worker_status(worker, profile) return ret def reset_stats(lbn, profile='default'): ''' Reset all runtime statistics for the load balancer CLI Examples: .. code-block:: bash salt '*' modjk.reset_stats loadbalancer1 salt '*' modjk.reset_stats loadbalancer1 other-profile ''' cmd = { 'cmd': 'reset', 'mime': 'prop', 'w': lbn, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def lb_edit(lbn, settings, profile='default'): ''' Edit the loadbalancer settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn return _do_http(settings, profile)['worker.result.type'] == 'OK' def bulk_stop(workers, lbn, profile='default'): ''' Stop all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_stop(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_activate(workers, lbn, profile='default'): ''' Activate all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_activate(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_disable(workers, lbn, profile='default'): ''' Disable all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_disable(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_recover(workers, lbn, profile='default'): ''' Recover all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_recover(worker, lbn, profile) except Exception: ret[worker] = False return ret def worker_status(worker, profile='default'): ''' Return the state of the worker CLI Examples: .. code-block:: bash salt '*' modjk.worker_status node1 salt '*' modjk.worker_status node1 other-profile ''' config = get_running(profile) try: return { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } except KeyError: return False def worker_recover(worker, lbn, profile='default'): ''' Set the worker to recover this module will fail if it is in OK state CLI Examples: .. code-block:: bash salt '*' modjk.worker_recover node1 loadbalancer1 salt '*' modjk.worker_recover node1 loadbalancer1 other-profile ''' cmd = { 'cmd': 'recover', 'mime': 'prop', 'w': lbn, 'sw': worker, } return _do_http(cmd, profile) def worker_disable(worker, lbn, profile='default'): ''' Set the worker to disable state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_disable node1 loadbalancer1 salt '*' modjk.worker_disable node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'd', profile) def worker_activate(worker, lbn, profile='default'): ''' Set the worker to activate state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'a', profile) def worker_stop(worker, lbn, profile='default'): ''' Set the worker to stopped state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 's', profile) def worker_edit(worker, lbn, settings, profile='default'): ''' Edit the worker settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn settings['sw'] = worker return _do_http(settings, profile)['worker.result.type'] == 'OK'
saltstack/salt
salt/modules/modjk.py
list_configured_members
python
def list_configured_members(lbn, profile='default'): ''' Return a list of member workers from the configuration files CLI Examples: .. code-block:: bash salt '*' modjk.list_configured_members loadbalancer1 salt '*' modjk.list_configured_members loadbalancer1 other-profile ''' config = dump_config(profile) try: ret = config['worker.{0}.balance_workers'.format(lbn)] except KeyError: return [] return [_f for _f in ret.strip().split(',') if _f]
Return a list of member workers from the configuration files CLI Examples: .. code-block:: bash salt '*' modjk.list_configured_members loadbalancer1 salt '*' modjk.list_configured_members loadbalancer1 other-profile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L172-L191
[ "def dump_config(profile='default'):\n '''\n Dump the original configuration that was loaded from disk\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' modjk.dump_config\n salt '*' modjk.dump_config other-profile\n '''\n\n cmd = {\n 'cmd': 'dump',\n 'mime': 'prop',\n }\n return _do_http(cmd, profile)\n" ]
# -*- coding: utf-8 -*- ''' Control Modjk via the Apache Tomcat "Status" worker (http://tomcat.apache.org/connectors-doc/reference/status.html) Below is an example of the configuration needed for this module. This configuration data can be placed either in :ref:`grains <targeting-grains>` or :ref:`pillar <salt-pillars>`. If using grains, this can be accomplished :ref:`statically <static-custom-grains>` or via a :ref:`grain module <writing-grains>`. If using pillar, the yaml configuration can be placed directly into a pillar SLS file, making this both the easier and more dynamic method of configuring this module. .. code-block:: yaml modjk: default: url: http://localhost/jkstatus user: modjk pass: secret realm: authentication realm for digest passwords timeout: 5 otherVhost: url: http://otherVhost/jkstatus user: modjk pass: secret2 realm: authentication realm2 for digest passwords timeout: 600 ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module from salt.ext import six from salt.ext.six.moves.urllib.parse import urlencode as _urlencode from salt.ext.six.moves.urllib.request import ( HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, urlopen as _urlopen, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=import-error,no-name-in-module def __virtual__(): ''' Always load ''' return True def _auth(url, user, passwd, realm): ''' returns a authentication handler. ''' basic = _HTTPBasicAuthHandler() basic.add_password(realm=realm, uri=url, user=user, passwd=passwd) digest = _HTTPDigestAuthHandler() digest.add_password(realm=realm, uri=url, user=user, passwd=passwd) return _build_opener(basic, digest) def _do_http(opts, profile='default'): ''' Make the http request and return the data ''' ret = {} url = __salt__['config.get']('modjk:{0}:url'.format(profile), '') user = __salt__['config.get']('modjk:{0}:user'.format(profile), '') passwd = __salt__['config.get']('modjk:{0}:pass'.format(profile), '') realm = __salt__['config.get']('modjk:{0}:realm'.format(profile), '') timeout = __salt__['config.get']('modjk:{0}:timeout'.format(profile), '') if not url: raise Exception('missing url in profile {0}'.format(profile)) if user and passwd: auth = _auth(url=url, realm=realm, user=user, passwd=passwd) _install_opener(auth) url += '?{0}'.format(_urlencode(opts)) for line in _urlopen(url, timeout=timeout).read().splitlines(): splt = line.split('=', 1) if splt[0] in ret: ret[splt[0]] += ',{0}'.format(splt[1]) else: ret[splt[0]] = splt[1] return ret def _worker_ctl(worker, lbn, vwa, profile='default'): ''' enable/disable/stop a worker ''' cmd = { 'cmd': 'update', 'mime': 'prop', 'w': lbn, 'sw': worker, 'vwa': vwa, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def version(profile='default'): ''' Return the modjk version CLI Examples: .. code-block:: bash salt '*' modjk.version salt '*' modjk.version other-profile ''' cmd = { 'cmd': 'version', 'mime': 'prop', } return _do_http(cmd, profile)['worker.jk_version'].split('/')[-1] def get_running(profile='default'): ''' Get the current running config (not from disk) CLI Examples: .. code-block:: bash salt '*' modjk.get_running salt '*' modjk.get_running other-profile ''' cmd = { 'cmd': 'list', 'mime': 'prop', } return _do_http(cmd, profile) def dump_config(profile='default'): ''' Dump the original configuration that was loaded from disk CLI Examples: .. code-block:: bash salt '*' modjk.dump_config salt '*' modjk.dump_config other-profile ''' cmd = { 'cmd': 'dump', 'mime': 'prop', } return _do_http(cmd, profile) def workers(profile='default'): ''' Return a list of member workers and their status CLI Examples: .. code-block:: bash salt '*' modjk.workers salt '*' modjk.workers other-profile ''' config = get_running(profile) lbn = config['worker.list'].split(',') worker_list = [] ret = {} for lb in lbn: try: worker_list.extend( config['worker.{0}.balance_workers'.format(lb)].split(',') ) except KeyError: pass worker_list = list(set(worker_list)) for worker in worker_list: ret[worker] = { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } return ret def recover_all(lbn, profile='default'): ''' Set the all the workers in lbn to recover and activate them if they are not CLI Examples: .. code-block:: bash salt '*' modjk.recover_all loadbalancer1 salt '*' modjk.recover_all loadbalancer1 other-profile ''' ret = {} config = get_running(profile) try: workers_ = config['worker.{0}.balance_workers'.format(lbn)].split(',') except KeyError: return ret for worker in workers_: curr_state = worker_status(worker, profile) if curr_state['activation'] != 'ACT': worker_activate(worker, lbn, profile) if not curr_state['state'].startswith('OK'): worker_recover(worker, lbn, profile) ret[worker] = worker_status(worker, profile) return ret def reset_stats(lbn, profile='default'): ''' Reset all runtime statistics for the load balancer CLI Examples: .. code-block:: bash salt '*' modjk.reset_stats loadbalancer1 salt '*' modjk.reset_stats loadbalancer1 other-profile ''' cmd = { 'cmd': 'reset', 'mime': 'prop', 'w': lbn, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def lb_edit(lbn, settings, profile='default'): ''' Edit the loadbalancer settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn return _do_http(settings, profile)['worker.result.type'] == 'OK' def bulk_stop(workers, lbn, profile='default'): ''' Stop all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_stop(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_activate(workers, lbn, profile='default'): ''' Activate all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_activate(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_disable(workers, lbn, profile='default'): ''' Disable all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_disable(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_recover(workers, lbn, profile='default'): ''' Recover all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_recover(worker, lbn, profile) except Exception: ret[worker] = False return ret def worker_status(worker, profile='default'): ''' Return the state of the worker CLI Examples: .. code-block:: bash salt '*' modjk.worker_status node1 salt '*' modjk.worker_status node1 other-profile ''' config = get_running(profile) try: return { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } except KeyError: return False def worker_recover(worker, lbn, profile='default'): ''' Set the worker to recover this module will fail if it is in OK state CLI Examples: .. code-block:: bash salt '*' modjk.worker_recover node1 loadbalancer1 salt '*' modjk.worker_recover node1 loadbalancer1 other-profile ''' cmd = { 'cmd': 'recover', 'mime': 'prop', 'w': lbn, 'sw': worker, } return _do_http(cmd, profile) def worker_disable(worker, lbn, profile='default'): ''' Set the worker to disable state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_disable node1 loadbalancer1 salt '*' modjk.worker_disable node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'd', profile) def worker_activate(worker, lbn, profile='default'): ''' Set the worker to activate state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'a', profile) def worker_stop(worker, lbn, profile='default'): ''' Set the worker to stopped state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 's', profile) def worker_edit(worker, lbn, settings, profile='default'): ''' Edit the worker settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn settings['sw'] = worker return _do_http(settings, profile)['worker.result.type'] == 'OK'
saltstack/salt
salt/modules/modjk.py
workers
python
def workers(profile='default'): ''' Return a list of member workers and their status CLI Examples: .. code-block:: bash salt '*' modjk.workers salt '*' modjk.workers other-profile ''' config = get_running(profile) lbn = config['worker.list'].split(',') worker_list = [] ret = {} for lb in lbn: try: worker_list.extend( config['worker.{0}.balance_workers'.format(lb)].split(',') ) except KeyError: pass worker_list = list(set(worker_list)) for worker in worker_list: ret[worker] = { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } return ret
Return a list of member workers and their status CLI Examples: .. code-block:: bash salt '*' modjk.workers salt '*' modjk.workers other-profile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L194-L227
[ "def get_running(profile='default'):\n '''\n Get the current running config (not from disk)\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' modjk.get_running\n salt '*' modjk.get_running other-profile\n '''\n\n cmd = {\n 'cmd': 'list',\n 'mime': 'prop',\n }\n return _do_http(cmd, profile)\n" ]
# -*- coding: utf-8 -*- ''' Control Modjk via the Apache Tomcat "Status" worker (http://tomcat.apache.org/connectors-doc/reference/status.html) Below is an example of the configuration needed for this module. This configuration data can be placed either in :ref:`grains <targeting-grains>` or :ref:`pillar <salt-pillars>`. If using grains, this can be accomplished :ref:`statically <static-custom-grains>` or via a :ref:`grain module <writing-grains>`. If using pillar, the yaml configuration can be placed directly into a pillar SLS file, making this both the easier and more dynamic method of configuring this module. .. code-block:: yaml modjk: default: url: http://localhost/jkstatus user: modjk pass: secret realm: authentication realm for digest passwords timeout: 5 otherVhost: url: http://otherVhost/jkstatus user: modjk pass: secret2 realm: authentication realm2 for digest passwords timeout: 600 ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module from salt.ext import six from salt.ext.six.moves.urllib.parse import urlencode as _urlencode from salt.ext.six.moves.urllib.request import ( HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, urlopen as _urlopen, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=import-error,no-name-in-module def __virtual__(): ''' Always load ''' return True def _auth(url, user, passwd, realm): ''' returns a authentication handler. ''' basic = _HTTPBasicAuthHandler() basic.add_password(realm=realm, uri=url, user=user, passwd=passwd) digest = _HTTPDigestAuthHandler() digest.add_password(realm=realm, uri=url, user=user, passwd=passwd) return _build_opener(basic, digest) def _do_http(opts, profile='default'): ''' Make the http request and return the data ''' ret = {} url = __salt__['config.get']('modjk:{0}:url'.format(profile), '') user = __salt__['config.get']('modjk:{0}:user'.format(profile), '') passwd = __salt__['config.get']('modjk:{0}:pass'.format(profile), '') realm = __salt__['config.get']('modjk:{0}:realm'.format(profile), '') timeout = __salt__['config.get']('modjk:{0}:timeout'.format(profile), '') if not url: raise Exception('missing url in profile {0}'.format(profile)) if user and passwd: auth = _auth(url=url, realm=realm, user=user, passwd=passwd) _install_opener(auth) url += '?{0}'.format(_urlencode(opts)) for line in _urlopen(url, timeout=timeout).read().splitlines(): splt = line.split('=', 1) if splt[0] in ret: ret[splt[0]] += ',{0}'.format(splt[1]) else: ret[splt[0]] = splt[1] return ret def _worker_ctl(worker, lbn, vwa, profile='default'): ''' enable/disable/stop a worker ''' cmd = { 'cmd': 'update', 'mime': 'prop', 'w': lbn, 'sw': worker, 'vwa': vwa, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def version(profile='default'): ''' Return the modjk version CLI Examples: .. code-block:: bash salt '*' modjk.version salt '*' modjk.version other-profile ''' cmd = { 'cmd': 'version', 'mime': 'prop', } return _do_http(cmd, profile)['worker.jk_version'].split('/')[-1] def get_running(profile='default'): ''' Get the current running config (not from disk) CLI Examples: .. code-block:: bash salt '*' modjk.get_running salt '*' modjk.get_running other-profile ''' cmd = { 'cmd': 'list', 'mime': 'prop', } return _do_http(cmd, profile) def dump_config(profile='default'): ''' Dump the original configuration that was loaded from disk CLI Examples: .. code-block:: bash salt '*' modjk.dump_config salt '*' modjk.dump_config other-profile ''' cmd = { 'cmd': 'dump', 'mime': 'prop', } return _do_http(cmd, profile) def list_configured_members(lbn, profile='default'): ''' Return a list of member workers from the configuration files CLI Examples: .. code-block:: bash salt '*' modjk.list_configured_members loadbalancer1 salt '*' modjk.list_configured_members loadbalancer1 other-profile ''' config = dump_config(profile) try: ret = config['worker.{0}.balance_workers'.format(lbn)] except KeyError: return [] return [_f for _f in ret.strip().split(',') if _f] def recover_all(lbn, profile='default'): ''' Set the all the workers in lbn to recover and activate them if they are not CLI Examples: .. code-block:: bash salt '*' modjk.recover_all loadbalancer1 salt '*' modjk.recover_all loadbalancer1 other-profile ''' ret = {} config = get_running(profile) try: workers_ = config['worker.{0}.balance_workers'.format(lbn)].split(',') except KeyError: return ret for worker in workers_: curr_state = worker_status(worker, profile) if curr_state['activation'] != 'ACT': worker_activate(worker, lbn, profile) if not curr_state['state'].startswith('OK'): worker_recover(worker, lbn, profile) ret[worker] = worker_status(worker, profile) return ret def reset_stats(lbn, profile='default'): ''' Reset all runtime statistics for the load balancer CLI Examples: .. code-block:: bash salt '*' modjk.reset_stats loadbalancer1 salt '*' modjk.reset_stats loadbalancer1 other-profile ''' cmd = { 'cmd': 'reset', 'mime': 'prop', 'w': lbn, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def lb_edit(lbn, settings, profile='default'): ''' Edit the loadbalancer settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn return _do_http(settings, profile)['worker.result.type'] == 'OK' def bulk_stop(workers, lbn, profile='default'): ''' Stop all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_stop(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_activate(workers, lbn, profile='default'): ''' Activate all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_activate(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_disable(workers, lbn, profile='default'): ''' Disable all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_disable(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_recover(workers, lbn, profile='default'): ''' Recover all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_recover(worker, lbn, profile) except Exception: ret[worker] = False return ret def worker_status(worker, profile='default'): ''' Return the state of the worker CLI Examples: .. code-block:: bash salt '*' modjk.worker_status node1 salt '*' modjk.worker_status node1 other-profile ''' config = get_running(profile) try: return { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } except KeyError: return False def worker_recover(worker, lbn, profile='default'): ''' Set the worker to recover this module will fail if it is in OK state CLI Examples: .. code-block:: bash salt '*' modjk.worker_recover node1 loadbalancer1 salt '*' modjk.worker_recover node1 loadbalancer1 other-profile ''' cmd = { 'cmd': 'recover', 'mime': 'prop', 'w': lbn, 'sw': worker, } return _do_http(cmd, profile) def worker_disable(worker, lbn, profile='default'): ''' Set the worker to disable state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_disable node1 loadbalancer1 salt '*' modjk.worker_disable node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'd', profile) def worker_activate(worker, lbn, profile='default'): ''' Set the worker to activate state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'a', profile) def worker_stop(worker, lbn, profile='default'): ''' Set the worker to stopped state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 's', profile) def worker_edit(worker, lbn, settings, profile='default'): ''' Edit the worker settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn settings['sw'] = worker return _do_http(settings, profile)['worker.result.type'] == 'OK'
saltstack/salt
salt/modules/modjk.py
recover_all
python
def recover_all(lbn, profile='default'): ''' Set the all the workers in lbn to recover and activate them if they are not CLI Examples: .. code-block:: bash salt '*' modjk.recover_all loadbalancer1 salt '*' modjk.recover_all loadbalancer1 other-profile ''' ret = {} config = get_running(profile) try: workers_ = config['worker.{0}.balance_workers'.format(lbn)].split(',') except KeyError: return ret for worker in workers_: curr_state = worker_status(worker, profile) if curr_state['activation'] != 'ACT': worker_activate(worker, lbn, profile) if not curr_state['state'].startswith('OK'): worker_recover(worker, lbn, profile) ret[worker] = worker_status(worker, profile) return ret
Set the all the workers in lbn to recover and activate them if they are not CLI Examples: .. code-block:: bash salt '*' modjk.recover_all loadbalancer1 salt '*' modjk.recover_all loadbalancer1 other-profile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L230-L257
[ "def get_running(profile='default'):\n '''\n Get the current running config (not from disk)\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' modjk.get_running\n salt '*' modjk.get_running other-profile\n '''\n\n cmd = {\n 'cmd': 'list',\n 'mime': 'prop',\n }\n return _do_http(cmd, profile)\n", "def worker_status(worker, profile='default'):\n '''\n Return the state of the worker\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' modjk.worker_status node1\n salt '*' modjk.worker_status node1 other-profile\n '''\n\n config = get_running(profile)\n try:\n return {\n 'activation': config['worker.{0}.activation'.format(worker)],\n 'state': config['worker.{0}.state'.format(worker)],\n }\n except KeyError:\n return False\n", "def worker_activate(worker, lbn, profile='default'):\n '''\n Set the worker to activate state in the lbn load balancer\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' modjk.worker_activate node1 loadbalancer1\n salt '*' modjk.worker_activate node1 loadbalancer1 other-profile\n '''\n\n return _worker_ctl(worker, lbn, 'a', profile)\n", "def worker_recover(worker, lbn, profile='default'):\n '''\n Set the worker to recover\n this module will fail if it is in OK state\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' modjk.worker_recover node1 loadbalancer1\n salt '*' modjk.worker_recover node1 loadbalancer1 other-profile\n '''\n\n cmd = {\n 'cmd': 'recover',\n 'mime': 'prop',\n 'w': lbn,\n 'sw': worker,\n }\n return _do_http(cmd, profile)\n" ]
# -*- coding: utf-8 -*- ''' Control Modjk via the Apache Tomcat "Status" worker (http://tomcat.apache.org/connectors-doc/reference/status.html) Below is an example of the configuration needed for this module. This configuration data can be placed either in :ref:`grains <targeting-grains>` or :ref:`pillar <salt-pillars>`. If using grains, this can be accomplished :ref:`statically <static-custom-grains>` or via a :ref:`grain module <writing-grains>`. If using pillar, the yaml configuration can be placed directly into a pillar SLS file, making this both the easier and more dynamic method of configuring this module. .. code-block:: yaml modjk: default: url: http://localhost/jkstatus user: modjk pass: secret realm: authentication realm for digest passwords timeout: 5 otherVhost: url: http://otherVhost/jkstatus user: modjk pass: secret2 realm: authentication realm2 for digest passwords timeout: 600 ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module from salt.ext import six from salt.ext.six.moves.urllib.parse import urlencode as _urlencode from salt.ext.six.moves.urllib.request import ( HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, urlopen as _urlopen, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=import-error,no-name-in-module def __virtual__(): ''' Always load ''' return True def _auth(url, user, passwd, realm): ''' returns a authentication handler. ''' basic = _HTTPBasicAuthHandler() basic.add_password(realm=realm, uri=url, user=user, passwd=passwd) digest = _HTTPDigestAuthHandler() digest.add_password(realm=realm, uri=url, user=user, passwd=passwd) return _build_opener(basic, digest) def _do_http(opts, profile='default'): ''' Make the http request and return the data ''' ret = {} url = __salt__['config.get']('modjk:{0}:url'.format(profile), '') user = __salt__['config.get']('modjk:{0}:user'.format(profile), '') passwd = __salt__['config.get']('modjk:{0}:pass'.format(profile), '') realm = __salt__['config.get']('modjk:{0}:realm'.format(profile), '') timeout = __salt__['config.get']('modjk:{0}:timeout'.format(profile), '') if not url: raise Exception('missing url in profile {0}'.format(profile)) if user and passwd: auth = _auth(url=url, realm=realm, user=user, passwd=passwd) _install_opener(auth) url += '?{0}'.format(_urlencode(opts)) for line in _urlopen(url, timeout=timeout).read().splitlines(): splt = line.split('=', 1) if splt[0] in ret: ret[splt[0]] += ',{0}'.format(splt[1]) else: ret[splt[0]] = splt[1] return ret def _worker_ctl(worker, lbn, vwa, profile='default'): ''' enable/disable/stop a worker ''' cmd = { 'cmd': 'update', 'mime': 'prop', 'w': lbn, 'sw': worker, 'vwa': vwa, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def version(profile='default'): ''' Return the modjk version CLI Examples: .. code-block:: bash salt '*' modjk.version salt '*' modjk.version other-profile ''' cmd = { 'cmd': 'version', 'mime': 'prop', } return _do_http(cmd, profile)['worker.jk_version'].split('/')[-1] def get_running(profile='default'): ''' Get the current running config (not from disk) CLI Examples: .. code-block:: bash salt '*' modjk.get_running salt '*' modjk.get_running other-profile ''' cmd = { 'cmd': 'list', 'mime': 'prop', } return _do_http(cmd, profile) def dump_config(profile='default'): ''' Dump the original configuration that was loaded from disk CLI Examples: .. code-block:: bash salt '*' modjk.dump_config salt '*' modjk.dump_config other-profile ''' cmd = { 'cmd': 'dump', 'mime': 'prop', } return _do_http(cmd, profile) def list_configured_members(lbn, profile='default'): ''' Return a list of member workers from the configuration files CLI Examples: .. code-block:: bash salt '*' modjk.list_configured_members loadbalancer1 salt '*' modjk.list_configured_members loadbalancer1 other-profile ''' config = dump_config(profile) try: ret = config['worker.{0}.balance_workers'.format(lbn)] except KeyError: return [] return [_f for _f in ret.strip().split(',') if _f] def workers(profile='default'): ''' Return a list of member workers and their status CLI Examples: .. code-block:: bash salt '*' modjk.workers salt '*' modjk.workers other-profile ''' config = get_running(profile) lbn = config['worker.list'].split(',') worker_list = [] ret = {} for lb in lbn: try: worker_list.extend( config['worker.{0}.balance_workers'.format(lb)].split(',') ) except KeyError: pass worker_list = list(set(worker_list)) for worker in worker_list: ret[worker] = { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } return ret def reset_stats(lbn, profile='default'): ''' Reset all runtime statistics for the load balancer CLI Examples: .. code-block:: bash salt '*' modjk.reset_stats loadbalancer1 salt '*' modjk.reset_stats loadbalancer1 other-profile ''' cmd = { 'cmd': 'reset', 'mime': 'prop', 'w': lbn, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def lb_edit(lbn, settings, profile='default'): ''' Edit the loadbalancer settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn return _do_http(settings, profile)['worker.result.type'] == 'OK' def bulk_stop(workers, lbn, profile='default'): ''' Stop all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_stop(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_activate(workers, lbn, profile='default'): ''' Activate all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_activate(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_disable(workers, lbn, profile='default'): ''' Disable all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_disable(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_recover(workers, lbn, profile='default'): ''' Recover all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_recover(worker, lbn, profile) except Exception: ret[worker] = False return ret def worker_status(worker, profile='default'): ''' Return the state of the worker CLI Examples: .. code-block:: bash salt '*' modjk.worker_status node1 salt '*' modjk.worker_status node1 other-profile ''' config = get_running(profile) try: return { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } except KeyError: return False def worker_recover(worker, lbn, profile='default'): ''' Set the worker to recover this module will fail if it is in OK state CLI Examples: .. code-block:: bash salt '*' modjk.worker_recover node1 loadbalancer1 salt '*' modjk.worker_recover node1 loadbalancer1 other-profile ''' cmd = { 'cmd': 'recover', 'mime': 'prop', 'w': lbn, 'sw': worker, } return _do_http(cmd, profile) def worker_disable(worker, lbn, profile='default'): ''' Set the worker to disable state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_disable node1 loadbalancer1 salt '*' modjk.worker_disable node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'd', profile) def worker_activate(worker, lbn, profile='default'): ''' Set the worker to activate state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'a', profile) def worker_stop(worker, lbn, profile='default'): ''' Set the worker to stopped state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 's', profile) def worker_edit(worker, lbn, settings, profile='default'): ''' Edit the worker settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn settings['sw'] = worker return _do_http(settings, profile)['worker.result.type'] == 'OK'
saltstack/salt
salt/modules/modjk.py
lb_edit
python
def lb_edit(lbn, settings, profile='default'): ''' Edit the loadbalancer settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn return _do_http(settings, profile)['worker.result.type'] == 'OK'
Edit the loadbalancer settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" other-profile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L280-L299
[ "def _do_http(opts, profile='default'):\n '''\n Make the http request and return the data\n '''\n\n ret = {}\n\n url = __salt__['config.get']('modjk:{0}:url'.format(profile), '')\n user = __salt__['config.get']('modjk:{0}:user'.format(profile), '')\n passwd = __salt__['config.get']('modjk:{0}:pass'.format(profile), '')\n realm = __salt__['config.get']('modjk:{0}:realm'.format(profile), '')\n timeout = __salt__['config.get']('modjk:{0}:timeout'.format(profile), '')\n\n if not url:\n raise Exception('missing url in profile {0}'.format(profile))\n\n if user and passwd:\n auth = _auth(url=url, realm=realm, user=user, passwd=passwd)\n _install_opener(auth)\n\n url += '?{0}'.format(_urlencode(opts))\n\n for line in _urlopen(url, timeout=timeout).read().splitlines():\n splt = line.split('=', 1)\n if splt[0] in ret:\n ret[splt[0]] += ',{0}'.format(splt[1])\n else:\n ret[splt[0]] = splt[1]\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Control Modjk via the Apache Tomcat "Status" worker (http://tomcat.apache.org/connectors-doc/reference/status.html) Below is an example of the configuration needed for this module. This configuration data can be placed either in :ref:`grains <targeting-grains>` or :ref:`pillar <salt-pillars>`. If using grains, this can be accomplished :ref:`statically <static-custom-grains>` or via a :ref:`grain module <writing-grains>`. If using pillar, the yaml configuration can be placed directly into a pillar SLS file, making this both the easier and more dynamic method of configuring this module. .. code-block:: yaml modjk: default: url: http://localhost/jkstatus user: modjk pass: secret realm: authentication realm for digest passwords timeout: 5 otherVhost: url: http://otherVhost/jkstatus user: modjk pass: secret2 realm: authentication realm2 for digest passwords timeout: 600 ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module from salt.ext import six from salt.ext.six.moves.urllib.parse import urlencode as _urlencode from salt.ext.six.moves.urllib.request import ( HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, urlopen as _urlopen, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=import-error,no-name-in-module def __virtual__(): ''' Always load ''' return True def _auth(url, user, passwd, realm): ''' returns a authentication handler. ''' basic = _HTTPBasicAuthHandler() basic.add_password(realm=realm, uri=url, user=user, passwd=passwd) digest = _HTTPDigestAuthHandler() digest.add_password(realm=realm, uri=url, user=user, passwd=passwd) return _build_opener(basic, digest) def _do_http(opts, profile='default'): ''' Make the http request and return the data ''' ret = {} url = __salt__['config.get']('modjk:{0}:url'.format(profile), '') user = __salt__['config.get']('modjk:{0}:user'.format(profile), '') passwd = __salt__['config.get']('modjk:{0}:pass'.format(profile), '') realm = __salt__['config.get']('modjk:{0}:realm'.format(profile), '') timeout = __salt__['config.get']('modjk:{0}:timeout'.format(profile), '') if not url: raise Exception('missing url in profile {0}'.format(profile)) if user and passwd: auth = _auth(url=url, realm=realm, user=user, passwd=passwd) _install_opener(auth) url += '?{0}'.format(_urlencode(opts)) for line in _urlopen(url, timeout=timeout).read().splitlines(): splt = line.split('=', 1) if splt[0] in ret: ret[splt[0]] += ',{0}'.format(splt[1]) else: ret[splt[0]] = splt[1] return ret def _worker_ctl(worker, lbn, vwa, profile='default'): ''' enable/disable/stop a worker ''' cmd = { 'cmd': 'update', 'mime': 'prop', 'w': lbn, 'sw': worker, 'vwa': vwa, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def version(profile='default'): ''' Return the modjk version CLI Examples: .. code-block:: bash salt '*' modjk.version salt '*' modjk.version other-profile ''' cmd = { 'cmd': 'version', 'mime': 'prop', } return _do_http(cmd, profile)['worker.jk_version'].split('/')[-1] def get_running(profile='default'): ''' Get the current running config (not from disk) CLI Examples: .. code-block:: bash salt '*' modjk.get_running salt '*' modjk.get_running other-profile ''' cmd = { 'cmd': 'list', 'mime': 'prop', } return _do_http(cmd, profile) def dump_config(profile='default'): ''' Dump the original configuration that was loaded from disk CLI Examples: .. code-block:: bash salt '*' modjk.dump_config salt '*' modjk.dump_config other-profile ''' cmd = { 'cmd': 'dump', 'mime': 'prop', } return _do_http(cmd, profile) def list_configured_members(lbn, profile='default'): ''' Return a list of member workers from the configuration files CLI Examples: .. code-block:: bash salt '*' modjk.list_configured_members loadbalancer1 salt '*' modjk.list_configured_members loadbalancer1 other-profile ''' config = dump_config(profile) try: ret = config['worker.{0}.balance_workers'.format(lbn)] except KeyError: return [] return [_f for _f in ret.strip().split(',') if _f] def workers(profile='default'): ''' Return a list of member workers and their status CLI Examples: .. code-block:: bash salt '*' modjk.workers salt '*' modjk.workers other-profile ''' config = get_running(profile) lbn = config['worker.list'].split(',') worker_list = [] ret = {} for lb in lbn: try: worker_list.extend( config['worker.{0}.balance_workers'.format(lb)].split(',') ) except KeyError: pass worker_list = list(set(worker_list)) for worker in worker_list: ret[worker] = { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } return ret def recover_all(lbn, profile='default'): ''' Set the all the workers in lbn to recover and activate them if they are not CLI Examples: .. code-block:: bash salt '*' modjk.recover_all loadbalancer1 salt '*' modjk.recover_all loadbalancer1 other-profile ''' ret = {} config = get_running(profile) try: workers_ = config['worker.{0}.balance_workers'.format(lbn)].split(',') except KeyError: return ret for worker in workers_: curr_state = worker_status(worker, profile) if curr_state['activation'] != 'ACT': worker_activate(worker, lbn, profile) if not curr_state['state'].startswith('OK'): worker_recover(worker, lbn, profile) ret[worker] = worker_status(worker, profile) return ret def reset_stats(lbn, profile='default'): ''' Reset all runtime statistics for the load balancer CLI Examples: .. code-block:: bash salt '*' modjk.reset_stats loadbalancer1 salt '*' modjk.reset_stats loadbalancer1 other-profile ''' cmd = { 'cmd': 'reset', 'mime': 'prop', 'w': lbn, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def bulk_stop(workers, lbn, profile='default'): ''' Stop all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_stop(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_activate(workers, lbn, profile='default'): ''' Activate all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_activate(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_disable(workers, lbn, profile='default'): ''' Disable all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_disable(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_recover(workers, lbn, profile='default'): ''' Recover all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_recover(worker, lbn, profile) except Exception: ret[worker] = False return ret def worker_status(worker, profile='default'): ''' Return the state of the worker CLI Examples: .. code-block:: bash salt '*' modjk.worker_status node1 salt '*' modjk.worker_status node1 other-profile ''' config = get_running(profile) try: return { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } except KeyError: return False def worker_recover(worker, lbn, profile='default'): ''' Set the worker to recover this module will fail if it is in OK state CLI Examples: .. code-block:: bash salt '*' modjk.worker_recover node1 loadbalancer1 salt '*' modjk.worker_recover node1 loadbalancer1 other-profile ''' cmd = { 'cmd': 'recover', 'mime': 'prop', 'w': lbn, 'sw': worker, } return _do_http(cmd, profile) def worker_disable(worker, lbn, profile='default'): ''' Set the worker to disable state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_disable node1 loadbalancer1 salt '*' modjk.worker_disable node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'd', profile) def worker_activate(worker, lbn, profile='default'): ''' Set the worker to activate state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'a', profile) def worker_stop(worker, lbn, profile='default'): ''' Set the worker to stopped state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 's', profile) def worker_edit(worker, lbn, settings, profile='default'): ''' Edit the worker settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn settings['sw'] = worker return _do_http(settings, profile)['worker.result.type'] == 'OK'
saltstack/salt
salt/modules/modjk.py
bulk_stop
python
def bulk_stop(workers, lbn, profile='default'): ''' Stop all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_stop(worker, lbn, profile) except Exception: ret[worker] = False return ret
Stop all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 other-profile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L302-L328
[ "def worker_stop(worker, lbn, profile='default'):\n '''\n Set the worker to stopped state in the lbn load balancer\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' modjk.worker_activate node1 loadbalancer1\n salt '*' modjk.worker_activate node1 loadbalancer1 other-profile\n '''\n\n return _worker_ctl(worker, lbn, 's', profile)\n" ]
# -*- coding: utf-8 -*- ''' Control Modjk via the Apache Tomcat "Status" worker (http://tomcat.apache.org/connectors-doc/reference/status.html) Below is an example of the configuration needed for this module. This configuration data can be placed either in :ref:`grains <targeting-grains>` or :ref:`pillar <salt-pillars>`. If using grains, this can be accomplished :ref:`statically <static-custom-grains>` or via a :ref:`grain module <writing-grains>`. If using pillar, the yaml configuration can be placed directly into a pillar SLS file, making this both the easier and more dynamic method of configuring this module. .. code-block:: yaml modjk: default: url: http://localhost/jkstatus user: modjk pass: secret realm: authentication realm for digest passwords timeout: 5 otherVhost: url: http://otherVhost/jkstatus user: modjk pass: secret2 realm: authentication realm2 for digest passwords timeout: 600 ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module from salt.ext import six from salt.ext.six.moves.urllib.parse import urlencode as _urlencode from salt.ext.six.moves.urllib.request import ( HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, urlopen as _urlopen, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=import-error,no-name-in-module def __virtual__(): ''' Always load ''' return True def _auth(url, user, passwd, realm): ''' returns a authentication handler. ''' basic = _HTTPBasicAuthHandler() basic.add_password(realm=realm, uri=url, user=user, passwd=passwd) digest = _HTTPDigestAuthHandler() digest.add_password(realm=realm, uri=url, user=user, passwd=passwd) return _build_opener(basic, digest) def _do_http(opts, profile='default'): ''' Make the http request and return the data ''' ret = {} url = __salt__['config.get']('modjk:{0}:url'.format(profile), '') user = __salt__['config.get']('modjk:{0}:user'.format(profile), '') passwd = __salt__['config.get']('modjk:{0}:pass'.format(profile), '') realm = __salt__['config.get']('modjk:{0}:realm'.format(profile), '') timeout = __salt__['config.get']('modjk:{0}:timeout'.format(profile), '') if not url: raise Exception('missing url in profile {0}'.format(profile)) if user and passwd: auth = _auth(url=url, realm=realm, user=user, passwd=passwd) _install_opener(auth) url += '?{0}'.format(_urlencode(opts)) for line in _urlopen(url, timeout=timeout).read().splitlines(): splt = line.split('=', 1) if splt[0] in ret: ret[splt[0]] += ',{0}'.format(splt[1]) else: ret[splt[0]] = splt[1] return ret def _worker_ctl(worker, lbn, vwa, profile='default'): ''' enable/disable/stop a worker ''' cmd = { 'cmd': 'update', 'mime': 'prop', 'w': lbn, 'sw': worker, 'vwa': vwa, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def version(profile='default'): ''' Return the modjk version CLI Examples: .. code-block:: bash salt '*' modjk.version salt '*' modjk.version other-profile ''' cmd = { 'cmd': 'version', 'mime': 'prop', } return _do_http(cmd, profile)['worker.jk_version'].split('/')[-1] def get_running(profile='default'): ''' Get the current running config (not from disk) CLI Examples: .. code-block:: bash salt '*' modjk.get_running salt '*' modjk.get_running other-profile ''' cmd = { 'cmd': 'list', 'mime': 'prop', } return _do_http(cmd, profile) def dump_config(profile='default'): ''' Dump the original configuration that was loaded from disk CLI Examples: .. code-block:: bash salt '*' modjk.dump_config salt '*' modjk.dump_config other-profile ''' cmd = { 'cmd': 'dump', 'mime': 'prop', } return _do_http(cmd, profile) def list_configured_members(lbn, profile='default'): ''' Return a list of member workers from the configuration files CLI Examples: .. code-block:: bash salt '*' modjk.list_configured_members loadbalancer1 salt '*' modjk.list_configured_members loadbalancer1 other-profile ''' config = dump_config(profile) try: ret = config['worker.{0}.balance_workers'.format(lbn)] except KeyError: return [] return [_f for _f in ret.strip().split(',') if _f] def workers(profile='default'): ''' Return a list of member workers and their status CLI Examples: .. code-block:: bash salt '*' modjk.workers salt '*' modjk.workers other-profile ''' config = get_running(profile) lbn = config['worker.list'].split(',') worker_list = [] ret = {} for lb in lbn: try: worker_list.extend( config['worker.{0}.balance_workers'.format(lb)].split(',') ) except KeyError: pass worker_list = list(set(worker_list)) for worker in worker_list: ret[worker] = { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } return ret def recover_all(lbn, profile='default'): ''' Set the all the workers in lbn to recover and activate them if they are not CLI Examples: .. code-block:: bash salt '*' modjk.recover_all loadbalancer1 salt '*' modjk.recover_all loadbalancer1 other-profile ''' ret = {} config = get_running(profile) try: workers_ = config['worker.{0}.balance_workers'.format(lbn)].split(',') except KeyError: return ret for worker in workers_: curr_state = worker_status(worker, profile) if curr_state['activation'] != 'ACT': worker_activate(worker, lbn, profile) if not curr_state['state'].startswith('OK'): worker_recover(worker, lbn, profile) ret[worker] = worker_status(worker, profile) return ret def reset_stats(lbn, profile='default'): ''' Reset all runtime statistics for the load balancer CLI Examples: .. code-block:: bash salt '*' modjk.reset_stats loadbalancer1 salt '*' modjk.reset_stats loadbalancer1 other-profile ''' cmd = { 'cmd': 'reset', 'mime': 'prop', 'w': lbn, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def lb_edit(lbn, settings, profile='default'): ''' Edit the loadbalancer settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn return _do_http(settings, profile)['worker.result.type'] == 'OK' def bulk_activate(workers, lbn, profile='default'): ''' Activate all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_activate(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_disable(workers, lbn, profile='default'): ''' Disable all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_disable(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_recover(workers, lbn, profile='default'): ''' Recover all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_recover(worker, lbn, profile) except Exception: ret[worker] = False return ret def worker_status(worker, profile='default'): ''' Return the state of the worker CLI Examples: .. code-block:: bash salt '*' modjk.worker_status node1 salt '*' modjk.worker_status node1 other-profile ''' config = get_running(profile) try: return { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } except KeyError: return False def worker_recover(worker, lbn, profile='default'): ''' Set the worker to recover this module will fail if it is in OK state CLI Examples: .. code-block:: bash salt '*' modjk.worker_recover node1 loadbalancer1 salt '*' modjk.worker_recover node1 loadbalancer1 other-profile ''' cmd = { 'cmd': 'recover', 'mime': 'prop', 'w': lbn, 'sw': worker, } return _do_http(cmd, profile) def worker_disable(worker, lbn, profile='default'): ''' Set the worker to disable state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_disable node1 loadbalancer1 salt '*' modjk.worker_disable node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'd', profile) def worker_activate(worker, lbn, profile='default'): ''' Set the worker to activate state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'a', profile) def worker_stop(worker, lbn, profile='default'): ''' Set the worker to stopped state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 's', profile) def worker_edit(worker, lbn, settings, profile='default'): ''' Edit the worker settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn settings['sw'] = worker return _do_http(settings, profile)['worker.result.type'] == 'OK'
saltstack/salt
salt/modules/modjk.py
bulk_activate
python
def bulk_activate(workers, lbn, profile='default'): ''' Activate all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_activate(worker, lbn, profile) except Exception: ret[worker] = False return ret
Activate all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 other-profile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L331-L357
[ "def worker_activate(worker, lbn, profile='default'):\n '''\n Set the worker to activate state in the lbn load balancer\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' modjk.worker_activate node1 loadbalancer1\n salt '*' modjk.worker_activate node1 loadbalancer1 other-profile\n '''\n\n return _worker_ctl(worker, lbn, 'a', profile)\n" ]
# -*- coding: utf-8 -*- ''' Control Modjk via the Apache Tomcat "Status" worker (http://tomcat.apache.org/connectors-doc/reference/status.html) Below is an example of the configuration needed for this module. This configuration data can be placed either in :ref:`grains <targeting-grains>` or :ref:`pillar <salt-pillars>`. If using grains, this can be accomplished :ref:`statically <static-custom-grains>` or via a :ref:`grain module <writing-grains>`. If using pillar, the yaml configuration can be placed directly into a pillar SLS file, making this both the easier and more dynamic method of configuring this module. .. code-block:: yaml modjk: default: url: http://localhost/jkstatus user: modjk pass: secret realm: authentication realm for digest passwords timeout: 5 otherVhost: url: http://otherVhost/jkstatus user: modjk pass: secret2 realm: authentication realm2 for digest passwords timeout: 600 ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module from salt.ext import six from salt.ext.six.moves.urllib.parse import urlencode as _urlencode from salt.ext.six.moves.urllib.request import ( HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, urlopen as _urlopen, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=import-error,no-name-in-module def __virtual__(): ''' Always load ''' return True def _auth(url, user, passwd, realm): ''' returns a authentication handler. ''' basic = _HTTPBasicAuthHandler() basic.add_password(realm=realm, uri=url, user=user, passwd=passwd) digest = _HTTPDigestAuthHandler() digest.add_password(realm=realm, uri=url, user=user, passwd=passwd) return _build_opener(basic, digest) def _do_http(opts, profile='default'): ''' Make the http request and return the data ''' ret = {} url = __salt__['config.get']('modjk:{0}:url'.format(profile), '') user = __salt__['config.get']('modjk:{0}:user'.format(profile), '') passwd = __salt__['config.get']('modjk:{0}:pass'.format(profile), '') realm = __salt__['config.get']('modjk:{0}:realm'.format(profile), '') timeout = __salt__['config.get']('modjk:{0}:timeout'.format(profile), '') if not url: raise Exception('missing url in profile {0}'.format(profile)) if user and passwd: auth = _auth(url=url, realm=realm, user=user, passwd=passwd) _install_opener(auth) url += '?{0}'.format(_urlencode(opts)) for line in _urlopen(url, timeout=timeout).read().splitlines(): splt = line.split('=', 1) if splt[0] in ret: ret[splt[0]] += ',{0}'.format(splt[1]) else: ret[splt[0]] = splt[1] return ret def _worker_ctl(worker, lbn, vwa, profile='default'): ''' enable/disable/stop a worker ''' cmd = { 'cmd': 'update', 'mime': 'prop', 'w': lbn, 'sw': worker, 'vwa': vwa, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def version(profile='default'): ''' Return the modjk version CLI Examples: .. code-block:: bash salt '*' modjk.version salt '*' modjk.version other-profile ''' cmd = { 'cmd': 'version', 'mime': 'prop', } return _do_http(cmd, profile)['worker.jk_version'].split('/')[-1] def get_running(profile='default'): ''' Get the current running config (not from disk) CLI Examples: .. code-block:: bash salt '*' modjk.get_running salt '*' modjk.get_running other-profile ''' cmd = { 'cmd': 'list', 'mime': 'prop', } return _do_http(cmd, profile) def dump_config(profile='default'): ''' Dump the original configuration that was loaded from disk CLI Examples: .. code-block:: bash salt '*' modjk.dump_config salt '*' modjk.dump_config other-profile ''' cmd = { 'cmd': 'dump', 'mime': 'prop', } return _do_http(cmd, profile) def list_configured_members(lbn, profile='default'): ''' Return a list of member workers from the configuration files CLI Examples: .. code-block:: bash salt '*' modjk.list_configured_members loadbalancer1 salt '*' modjk.list_configured_members loadbalancer1 other-profile ''' config = dump_config(profile) try: ret = config['worker.{0}.balance_workers'.format(lbn)] except KeyError: return [] return [_f for _f in ret.strip().split(',') if _f] def workers(profile='default'): ''' Return a list of member workers and their status CLI Examples: .. code-block:: bash salt '*' modjk.workers salt '*' modjk.workers other-profile ''' config = get_running(profile) lbn = config['worker.list'].split(',') worker_list = [] ret = {} for lb in lbn: try: worker_list.extend( config['worker.{0}.balance_workers'.format(lb)].split(',') ) except KeyError: pass worker_list = list(set(worker_list)) for worker in worker_list: ret[worker] = { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } return ret def recover_all(lbn, profile='default'): ''' Set the all the workers in lbn to recover and activate them if they are not CLI Examples: .. code-block:: bash salt '*' modjk.recover_all loadbalancer1 salt '*' modjk.recover_all loadbalancer1 other-profile ''' ret = {} config = get_running(profile) try: workers_ = config['worker.{0}.balance_workers'.format(lbn)].split(',') except KeyError: return ret for worker in workers_: curr_state = worker_status(worker, profile) if curr_state['activation'] != 'ACT': worker_activate(worker, lbn, profile) if not curr_state['state'].startswith('OK'): worker_recover(worker, lbn, profile) ret[worker] = worker_status(worker, profile) return ret def reset_stats(lbn, profile='default'): ''' Reset all runtime statistics for the load balancer CLI Examples: .. code-block:: bash salt '*' modjk.reset_stats loadbalancer1 salt '*' modjk.reset_stats loadbalancer1 other-profile ''' cmd = { 'cmd': 'reset', 'mime': 'prop', 'w': lbn, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def lb_edit(lbn, settings, profile='default'): ''' Edit the loadbalancer settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn return _do_http(settings, profile)['worker.result.type'] == 'OK' def bulk_stop(workers, lbn, profile='default'): ''' Stop all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_stop(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_disable(workers, lbn, profile='default'): ''' Disable all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_disable(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_recover(workers, lbn, profile='default'): ''' Recover all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_recover(worker, lbn, profile) except Exception: ret[worker] = False return ret def worker_status(worker, profile='default'): ''' Return the state of the worker CLI Examples: .. code-block:: bash salt '*' modjk.worker_status node1 salt '*' modjk.worker_status node1 other-profile ''' config = get_running(profile) try: return { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } except KeyError: return False def worker_recover(worker, lbn, profile='default'): ''' Set the worker to recover this module will fail if it is in OK state CLI Examples: .. code-block:: bash salt '*' modjk.worker_recover node1 loadbalancer1 salt '*' modjk.worker_recover node1 loadbalancer1 other-profile ''' cmd = { 'cmd': 'recover', 'mime': 'prop', 'w': lbn, 'sw': worker, } return _do_http(cmd, profile) def worker_disable(worker, lbn, profile='default'): ''' Set the worker to disable state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_disable node1 loadbalancer1 salt '*' modjk.worker_disable node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'd', profile) def worker_activate(worker, lbn, profile='default'): ''' Set the worker to activate state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'a', profile) def worker_stop(worker, lbn, profile='default'): ''' Set the worker to stopped state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 's', profile) def worker_edit(worker, lbn, settings, profile='default'): ''' Edit the worker settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn settings['sw'] = worker return _do_http(settings, profile)['worker.result.type'] == 'OK'
saltstack/salt
salt/modules/modjk.py
bulk_disable
python
def bulk_disable(workers, lbn, profile='default'): ''' Disable all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_disable(worker, lbn, profile) except Exception: ret[worker] = False return ret
Disable all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 other-profile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L360-L386
[ "def worker_disable(worker, lbn, profile='default'):\n '''\n Set the worker to disable state in the lbn load balancer\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' modjk.worker_disable node1 loadbalancer1\n salt '*' modjk.worker_disable node1 loadbalancer1 other-profile\n '''\n\n return _worker_ctl(worker, lbn, 'd', profile)\n" ]
# -*- coding: utf-8 -*- ''' Control Modjk via the Apache Tomcat "Status" worker (http://tomcat.apache.org/connectors-doc/reference/status.html) Below is an example of the configuration needed for this module. This configuration data can be placed either in :ref:`grains <targeting-grains>` or :ref:`pillar <salt-pillars>`. If using grains, this can be accomplished :ref:`statically <static-custom-grains>` or via a :ref:`grain module <writing-grains>`. If using pillar, the yaml configuration can be placed directly into a pillar SLS file, making this both the easier and more dynamic method of configuring this module. .. code-block:: yaml modjk: default: url: http://localhost/jkstatus user: modjk pass: secret realm: authentication realm for digest passwords timeout: 5 otherVhost: url: http://otherVhost/jkstatus user: modjk pass: secret2 realm: authentication realm2 for digest passwords timeout: 600 ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module from salt.ext import six from salt.ext.six.moves.urllib.parse import urlencode as _urlencode from salt.ext.six.moves.urllib.request import ( HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, urlopen as _urlopen, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=import-error,no-name-in-module def __virtual__(): ''' Always load ''' return True def _auth(url, user, passwd, realm): ''' returns a authentication handler. ''' basic = _HTTPBasicAuthHandler() basic.add_password(realm=realm, uri=url, user=user, passwd=passwd) digest = _HTTPDigestAuthHandler() digest.add_password(realm=realm, uri=url, user=user, passwd=passwd) return _build_opener(basic, digest) def _do_http(opts, profile='default'): ''' Make the http request and return the data ''' ret = {} url = __salt__['config.get']('modjk:{0}:url'.format(profile), '') user = __salt__['config.get']('modjk:{0}:user'.format(profile), '') passwd = __salt__['config.get']('modjk:{0}:pass'.format(profile), '') realm = __salt__['config.get']('modjk:{0}:realm'.format(profile), '') timeout = __salt__['config.get']('modjk:{0}:timeout'.format(profile), '') if not url: raise Exception('missing url in profile {0}'.format(profile)) if user and passwd: auth = _auth(url=url, realm=realm, user=user, passwd=passwd) _install_opener(auth) url += '?{0}'.format(_urlencode(opts)) for line in _urlopen(url, timeout=timeout).read().splitlines(): splt = line.split('=', 1) if splt[0] in ret: ret[splt[0]] += ',{0}'.format(splt[1]) else: ret[splt[0]] = splt[1] return ret def _worker_ctl(worker, lbn, vwa, profile='default'): ''' enable/disable/stop a worker ''' cmd = { 'cmd': 'update', 'mime': 'prop', 'w': lbn, 'sw': worker, 'vwa': vwa, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def version(profile='default'): ''' Return the modjk version CLI Examples: .. code-block:: bash salt '*' modjk.version salt '*' modjk.version other-profile ''' cmd = { 'cmd': 'version', 'mime': 'prop', } return _do_http(cmd, profile)['worker.jk_version'].split('/')[-1] def get_running(profile='default'): ''' Get the current running config (not from disk) CLI Examples: .. code-block:: bash salt '*' modjk.get_running salt '*' modjk.get_running other-profile ''' cmd = { 'cmd': 'list', 'mime': 'prop', } return _do_http(cmd, profile) def dump_config(profile='default'): ''' Dump the original configuration that was loaded from disk CLI Examples: .. code-block:: bash salt '*' modjk.dump_config salt '*' modjk.dump_config other-profile ''' cmd = { 'cmd': 'dump', 'mime': 'prop', } return _do_http(cmd, profile) def list_configured_members(lbn, profile='default'): ''' Return a list of member workers from the configuration files CLI Examples: .. code-block:: bash salt '*' modjk.list_configured_members loadbalancer1 salt '*' modjk.list_configured_members loadbalancer1 other-profile ''' config = dump_config(profile) try: ret = config['worker.{0}.balance_workers'.format(lbn)] except KeyError: return [] return [_f for _f in ret.strip().split(',') if _f] def workers(profile='default'): ''' Return a list of member workers and their status CLI Examples: .. code-block:: bash salt '*' modjk.workers salt '*' modjk.workers other-profile ''' config = get_running(profile) lbn = config['worker.list'].split(',') worker_list = [] ret = {} for lb in lbn: try: worker_list.extend( config['worker.{0}.balance_workers'.format(lb)].split(',') ) except KeyError: pass worker_list = list(set(worker_list)) for worker in worker_list: ret[worker] = { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } return ret def recover_all(lbn, profile='default'): ''' Set the all the workers in lbn to recover and activate them if they are not CLI Examples: .. code-block:: bash salt '*' modjk.recover_all loadbalancer1 salt '*' modjk.recover_all loadbalancer1 other-profile ''' ret = {} config = get_running(profile) try: workers_ = config['worker.{0}.balance_workers'.format(lbn)].split(',') except KeyError: return ret for worker in workers_: curr_state = worker_status(worker, profile) if curr_state['activation'] != 'ACT': worker_activate(worker, lbn, profile) if not curr_state['state'].startswith('OK'): worker_recover(worker, lbn, profile) ret[worker] = worker_status(worker, profile) return ret def reset_stats(lbn, profile='default'): ''' Reset all runtime statistics for the load balancer CLI Examples: .. code-block:: bash salt '*' modjk.reset_stats loadbalancer1 salt '*' modjk.reset_stats loadbalancer1 other-profile ''' cmd = { 'cmd': 'reset', 'mime': 'prop', 'w': lbn, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def lb_edit(lbn, settings, profile='default'): ''' Edit the loadbalancer settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn return _do_http(settings, profile)['worker.result.type'] == 'OK' def bulk_stop(workers, lbn, profile='default'): ''' Stop all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_stop(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_activate(workers, lbn, profile='default'): ''' Activate all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_activate(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_recover(workers, lbn, profile='default'): ''' Recover all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_recover(worker, lbn, profile) except Exception: ret[worker] = False return ret def worker_status(worker, profile='default'): ''' Return the state of the worker CLI Examples: .. code-block:: bash salt '*' modjk.worker_status node1 salt '*' modjk.worker_status node1 other-profile ''' config = get_running(profile) try: return { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } except KeyError: return False def worker_recover(worker, lbn, profile='default'): ''' Set the worker to recover this module will fail if it is in OK state CLI Examples: .. code-block:: bash salt '*' modjk.worker_recover node1 loadbalancer1 salt '*' modjk.worker_recover node1 loadbalancer1 other-profile ''' cmd = { 'cmd': 'recover', 'mime': 'prop', 'w': lbn, 'sw': worker, } return _do_http(cmd, profile) def worker_disable(worker, lbn, profile='default'): ''' Set the worker to disable state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_disable node1 loadbalancer1 salt '*' modjk.worker_disable node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'd', profile) def worker_activate(worker, lbn, profile='default'): ''' Set the worker to activate state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'a', profile) def worker_stop(worker, lbn, profile='default'): ''' Set the worker to stopped state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 's', profile) def worker_edit(worker, lbn, settings, profile='default'): ''' Edit the worker settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn settings['sw'] = worker return _do_http(settings, profile)['worker.result.type'] == 'OK'
saltstack/salt
salt/modules/modjk.py
bulk_recover
python
def bulk_recover(workers, lbn, profile='default'): ''' Recover all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_recover(worker, lbn, profile) except Exception: ret[worker] = False return ret
Recover all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 other-profile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L389-L415
[ "def worker_recover(worker, lbn, profile='default'):\n '''\n Set the worker to recover\n this module will fail if it is in OK state\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' modjk.worker_recover node1 loadbalancer1\n salt '*' modjk.worker_recover node1 loadbalancer1 other-profile\n '''\n\n cmd = {\n 'cmd': 'recover',\n 'mime': 'prop',\n 'w': lbn,\n 'sw': worker,\n }\n return _do_http(cmd, profile)\n" ]
# -*- coding: utf-8 -*- ''' Control Modjk via the Apache Tomcat "Status" worker (http://tomcat.apache.org/connectors-doc/reference/status.html) Below is an example of the configuration needed for this module. This configuration data can be placed either in :ref:`grains <targeting-grains>` or :ref:`pillar <salt-pillars>`. If using grains, this can be accomplished :ref:`statically <static-custom-grains>` or via a :ref:`grain module <writing-grains>`. If using pillar, the yaml configuration can be placed directly into a pillar SLS file, making this both the easier and more dynamic method of configuring this module. .. code-block:: yaml modjk: default: url: http://localhost/jkstatus user: modjk pass: secret realm: authentication realm for digest passwords timeout: 5 otherVhost: url: http://otherVhost/jkstatus user: modjk pass: secret2 realm: authentication realm2 for digest passwords timeout: 600 ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module from salt.ext import six from salt.ext.six.moves.urllib.parse import urlencode as _urlencode from salt.ext.six.moves.urllib.request import ( HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, urlopen as _urlopen, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=import-error,no-name-in-module def __virtual__(): ''' Always load ''' return True def _auth(url, user, passwd, realm): ''' returns a authentication handler. ''' basic = _HTTPBasicAuthHandler() basic.add_password(realm=realm, uri=url, user=user, passwd=passwd) digest = _HTTPDigestAuthHandler() digest.add_password(realm=realm, uri=url, user=user, passwd=passwd) return _build_opener(basic, digest) def _do_http(opts, profile='default'): ''' Make the http request and return the data ''' ret = {} url = __salt__['config.get']('modjk:{0}:url'.format(profile), '') user = __salt__['config.get']('modjk:{0}:user'.format(profile), '') passwd = __salt__['config.get']('modjk:{0}:pass'.format(profile), '') realm = __salt__['config.get']('modjk:{0}:realm'.format(profile), '') timeout = __salt__['config.get']('modjk:{0}:timeout'.format(profile), '') if not url: raise Exception('missing url in profile {0}'.format(profile)) if user and passwd: auth = _auth(url=url, realm=realm, user=user, passwd=passwd) _install_opener(auth) url += '?{0}'.format(_urlencode(opts)) for line in _urlopen(url, timeout=timeout).read().splitlines(): splt = line.split('=', 1) if splt[0] in ret: ret[splt[0]] += ',{0}'.format(splt[1]) else: ret[splt[0]] = splt[1] return ret def _worker_ctl(worker, lbn, vwa, profile='default'): ''' enable/disable/stop a worker ''' cmd = { 'cmd': 'update', 'mime': 'prop', 'w': lbn, 'sw': worker, 'vwa': vwa, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def version(profile='default'): ''' Return the modjk version CLI Examples: .. code-block:: bash salt '*' modjk.version salt '*' modjk.version other-profile ''' cmd = { 'cmd': 'version', 'mime': 'prop', } return _do_http(cmd, profile)['worker.jk_version'].split('/')[-1] def get_running(profile='default'): ''' Get the current running config (not from disk) CLI Examples: .. code-block:: bash salt '*' modjk.get_running salt '*' modjk.get_running other-profile ''' cmd = { 'cmd': 'list', 'mime': 'prop', } return _do_http(cmd, profile) def dump_config(profile='default'): ''' Dump the original configuration that was loaded from disk CLI Examples: .. code-block:: bash salt '*' modjk.dump_config salt '*' modjk.dump_config other-profile ''' cmd = { 'cmd': 'dump', 'mime': 'prop', } return _do_http(cmd, profile) def list_configured_members(lbn, profile='default'): ''' Return a list of member workers from the configuration files CLI Examples: .. code-block:: bash salt '*' modjk.list_configured_members loadbalancer1 salt '*' modjk.list_configured_members loadbalancer1 other-profile ''' config = dump_config(profile) try: ret = config['worker.{0}.balance_workers'.format(lbn)] except KeyError: return [] return [_f for _f in ret.strip().split(',') if _f] def workers(profile='default'): ''' Return a list of member workers and their status CLI Examples: .. code-block:: bash salt '*' modjk.workers salt '*' modjk.workers other-profile ''' config = get_running(profile) lbn = config['worker.list'].split(',') worker_list = [] ret = {} for lb in lbn: try: worker_list.extend( config['worker.{0}.balance_workers'.format(lb)].split(',') ) except KeyError: pass worker_list = list(set(worker_list)) for worker in worker_list: ret[worker] = { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } return ret def recover_all(lbn, profile='default'): ''' Set the all the workers in lbn to recover and activate them if they are not CLI Examples: .. code-block:: bash salt '*' modjk.recover_all loadbalancer1 salt '*' modjk.recover_all loadbalancer1 other-profile ''' ret = {} config = get_running(profile) try: workers_ = config['worker.{0}.balance_workers'.format(lbn)].split(',') except KeyError: return ret for worker in workers_: curr_state = worker_status(worker, profile) if curr_state['activation'] != 'ACT': worker_activate(worker, lbn, profile) if not curr_state['state'].startswith('OK'): worker_recover(worker, lbn, profile) ret[worker] = worker_status(worker, profile) return ret def reset_stats(lbn, profile='default'): ''' Reset all runtime statistics for the load balancer CLI Examples: .. code-block:: bash salt '*' modjk.reset_stats loadbalancer1 salt '*' modjk.reset_stats loadbalancer1 other-profile ''' cmd = { 'cmd': 'reset', 'mime': 'prop', 'w': lbn, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def lb_edit(lbn, settings, profile='default'): ''' Edit the loadbalancer settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn return _do_http(settings, profile)['worker.result.type'] == 'OK' def bulk_stop(workers, lbn, profile='default'): ''' Stop all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_stop(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_activate(workers, lbn, profile='default'): ''' Activate all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_activate(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_disable(workers, lbn, profile='default'): ''' Disable all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_disable(worker, lbn, profile) except Exception: ret[worker] = False return ret def worker_status(worker, profile='default'): ''' Return the state of the worker CLI Examples: .. code-block:: bash salt '*' modjk.worker_status node1 salt '*' modjk.worker_status node1 other-profile ''' config = get_running(profile) try: return { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } except KeyError: return False def worker_recover(worker, lbn, profile='default'): ''' Set the worker to recover this module will fail if it is in OK state CLI Examples: .. code-block:: bash salt '*' modjk.worker_recover node1 loadbalancer1 salt '*' modjk.worker_recover node1 loadbalancer1 other-profile ''' cmd = { 'cmd': 'recover', 'mime': 'prop', 'w': lbn, 'sw': worker, } return _do_http(cmd, profile) def worker_disable(worker, lbn, profile='default'): ''' Set the worker to disable state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_disable node1 loadbalancer1 salt '*' modjk.worker_disable node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'd', profile) def worker_activate(worker, lbn, profile='default'): ''' Set the worker to activate state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'a', profile) def worker_stop(worker, lbn, profile='default'): ''' Set the worker to stopped state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 's', profile) def worker_edit(worker, lbn, settings, profile='default'): ''' Edit the worker settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn settings['sw'] = worker return _do_http(settings, profile)['worker.result.type'] == 'OK'
saltstack/salt
salt/modules/modjk.py
worker_status
python
def worker_status(worker, profile='default'): ''' Return the state of the worker CLI Examples: .. code-block:: bash salt '*' modjk.worker_status node1 salt '*' modjk.worker_status node1 other-profile ''' config = get_running(profile) try: return { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } except KeyError: return False
Return the state of the worker CLI Examples: .. code-block:: bash salt '*' modjk.worker_status node1 salt '*' modjk.worker_status node1 other-profile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L418-L437
[ "def get_running(profile='default'):\n '''\n Get the current running config (not from disk)\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' modjk.get_running\n salt '*' modjk.get_running other-profile\n '''\n\n cmd = {\n 'cmd': 'list',\n 'mime': 'prop',\n }\n return _do_http(cmd, profile)\n" ]
# -*- coding: utf-8 -*- ''' Control Modjk via the Apache Tomcat "Status" worker (http://tomcat.apache.org/connectors-doc/reference/status.html) Below is an example of the configuration needed for this module. This configuration data can be placed either in :ref:`grains <targeting-grains>` or :ref:`pillar <salt-pillars>`. If using grains, this can be accomplished :ref:`statically <static-custom-grains>` or via a :ref:`grain module <writing-grains>`. If using pillar, the yaml configuration can be placed directly into a pillar SLS file, making this both the easier and more dynamic method of configuring this module. .. code-block:: yaml modjk: default: url: http://localhost/jkstatus user: modjk pass: secret realm: authentication realm for digest passwords timeout: 5 otherVhost: url: http://otherVhost/jkstatus user: modjk pass: secret2 realm: authentication realm2 for digest passwords timeout: 600 ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module from salt.ext import six from salt.ext.six.moves.urllib.parse import urlencode as _urlencode from salt.ext.six.moves.urllib.request import ( HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, urlopen as _urlopen, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=import-error,no-name-in-module def __virtual__(): ''' Always load ''' return True def _auth(url, user, passwd, realm): ''' returns a authentication handler. ''' basic = _HTTPBasicAuthHandler() basic.add_password(realm=realm, uri=url, user=user, passwd=passwd) digest = _HTTPDigestAuthHandler() digest.add_password(realm=realm, uri=url, user=user, passwd=passwd) return _build_opener(basic, digest) def _do_http(opts, profile='default'): ''' Make the http request and return the data ''' ret = {} url = __salt__['config.get']('modjk:{0}:url'.format(profile), '') user = __salt__['config.get']('modjk:{0}:user'.format(profile), '') passwd = __salt__['config.get']('modjk:{0}:pass'.format(profile), '') realm = __salt__['config.get']('modjk:{0}:realm'.format(profile), '') timeout = __salt__['config.get']('modjk:{0}:timeout'.format(profile), '') if not url: raise Exception('missing url in profile {0}'.format(profile)) if user and passwd: auth = _auth(url=url, realm=realm, user=user, passwd=passwd) _install_opener(auth) url += '?{0}'.format(_urlencode(opts)) for line in _urlopen(url, timeout=timeout).read().splitlines(): splt = line.split('=', 1) if splt[0] in ret: ret[splt[0]] += ',{0}'.format(splt[1]) else: ret[splt[0]] = splt[1] return ret def _worker_ctl(worker, lbn, vwa, profile='default'): ''' enable/disable/stop a worker ''' cmd = { 'cmd': 'update', 'mime': 'prop', 'w': lbn, 'sw': worker, 'vwa': vwa, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def version(profile='default'): ''' Return the modjk version CLI Examples: .. code-block:: bash salt '*' modjk.version salt '*' modjk.version other-profile ''' cmd = { 'cmd': 'version', 'mime': 'prop', } return _do_http(cmd, profile)['worker.jk_version'].split('/')[-1] def get_running(profile='default'): ''' Get the current running config (not from disk) CLI Examples: .. code-block:: bash salt '*' modjk.get_running salt '*' modjk.get_running other-profile ''' cmd = { 'cmd': 'list', 'mime': 'prop', } return _do_http(cmd, profile) def dump_config(profile='default'): ''' Dump the original configuration that was loaded from disk CLI Examples: .. code-block:: bash salt '*' modjk.dump_config salt '*' modjk.dump_config other-profile ''' cmd = { 'cmd': 'dump', 'mime': 'prop', } return _do_http(cmd, profile) def list_configured_members(lbn, profile='default'): ''' Return a list of member workers from the configuration files CLI Examples: .. code-block:: bash salt '*' modjk.list_configured_members loadbalancer1 salt '*' modjk.list_configured_members loadbalancer1 other-profile ''' config = dump_config(profile) try: ret = config['worker.{0}.balance_workers'.format(lbn)] except KeyError: return [] return [_f for _f in ret.strip().split(',') if _f] def workers(profile='default'): ''' Return a list of member workers and their status CLI Examples: .. code-block:: bash salt '*' modjk.workers salt '*' modjk.workers other-profile ''' config = get_running(profile) lbn = config['worker.list'].split(',') worker_list = [] ret = {} for lb in lbn: try: worker_list.extend( config['worker.{0}.balance_workers'.format(lb)].split(',') ) except KeyError: pass worker_list = list(set(worker_list)) for worker in worker_list: ret[worker] = { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } return ret def recover_all(lbn, profile='default'): ''' Set the all the workers in lbn to recover and activate them if they are not CLI Examples: .. code-block:: bash salt '*' modjk.recover_all loadbalancer1 salt '*' modjk.recover_all loadbalancer1 other-profile ''' ret = {} config = get_running(profile) try: workers_ = config['worker.{0}.balance_workers'.format(lbn)].split(',') except KeyError: return ret for worker in workers_: curr_state = worker_status(worker, profile) if curr_state['activation'] != 'ACT': worker_activate(worker, lbn, profile) if not curr_state['state'].startswith('OK'): worker_recover(worker, lbn, profile) ret[worker] = worker_status(worker, profile) return ret def reset_stats(lbn, profile='default'): ''' Reset all runtime statistics for the load balancer CLI Examples: .. code-block:: bash salt '*' modjk.reset_stats loadbalancer1 salt '*' modjk.reset_stats loadbalancer1 other-profile ''' cmd = { 'cmd': 'reset', 'mime': 'prop', 'w': lbn, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def lb_edit(lbn, settings, profile='default'): ''' Edit the loadbalancer settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn return _do_http(settings, profile)['worker.result.type'] == 'OK' def bulk_stop(workers, lbn, profile='default'): ''' Stop all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_stop(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_activate(workers, lbn, profile='default'): ''' Activate all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_activate(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_disable(workers, lbn, profile='default'): ''' Disable all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_disable(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_recover(workers, lbn, profile='default'): ''' Recover all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_recover(worker, lbn, profile) except Exception: ret[worker] = False return ret def worker_recover(worker, lbn, profile='default'): ''' Set the worker to recover this module will fail if it is in OK state CLI Examples: .. code-block:: bash salt '*' modjk.worker_recover node1 loadbalancer1 salt '*' modjk.worker_recover node1 loadbalancer1 other-profile ''' cmd = { 'cmd': 'recover', 'mime': 'prop', 'w': lbn, 'sw': worker, } return _do_http(cmd, profile) def worker_disable(worker, lbn, profile='default'): ''' Set the worker to disable state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_disable node1 loadbalancer1 salt '*' modjk.worker_disable node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'd', profile) def worker_activate(worker, lbn, profile='default'): ''' Set the worker to activate state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'a', profile) def worker_stop(worker, lbn, profile='default'): ''' Set the worker to stopped state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 's', profile) def worker_edit(worker, lbn, settings, profile='default'): ''' Edit the worker settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn settings['sw'] = worker return _do_http(settings, profile)['worker.result.type'] == 'OK'
saltstack/salt
salt/modules/modjk.py
worker_recover
python
def worker_recover(worker, lbn, profile='default'): ''' Set the worker to recover this module will fail if it is in OK state CLI Examples: .. code-block:: bash salt '*' modjk.worker_recover node1 loadbalancer1 salt '*' modjk.worker_recover node1 loadbalancer1 other-profile ''' cmd = { 'cmd': 'recover', 'mime': 'prop', 'w': lbn, 'sw': worker, } return _do_http(cmd, profile)
Set the worker to recover this module will fail if it is in OK state CLI Examples: .. code-block:: bash salt '*' modjk.worker_recover node1 loadbalancer1 salt '*' modjk.worker_recover node1 loadbalancer1 other-profile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L440-L459
[ "def _do_http(opts, profile='default'):\n '''\n Make the http request and return the data\n '''\n\n ret = {}\n\n url = __salt__['config.get']('modjk:{0}:url'.format(profile), '')\n user = __salt__['config.get']('modjk:{0}:user'.format(profile), '')\n passwd = __salt__['config.get']('modjk:{0}:pass'.format(profile), '')\n realm = __salt__['config.get']('modjk:{0}:realm'.format(profile), '')\n timeout = __salt__['config.get']('modjk:{0}:timeout'.format(profile), '')\n\n if not url:\n raise Exception('missing url in profile {0}'.format(profile))\n\n if user and passwd:\n auth = _auth(url=url, realm=realm, user=user, passwd=passwd)\n _install_opener(auth)\n\n url += '?{0}'.format(_urlencode(opts))\n\n for line in _urlopen(url, timeout=timeout).read().splitlines():\n splt = line.split('=', 1)\n if splt[0] in ret:\n ret[splt[0]] += ',{0}'.format(splt[1])\n else:\n ret[splt[0]] = splt[1]\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Control Modjk via the Apache Tomcat "Status" worker (http://tomcat.apache.org/connectors-doc/reference/status.html) Below is an example of the configuration needed for this module. This configuration data can be placed either in :ref:`grains <targeting-grains>` or :ref:`pillar <salt-pillars>`. If using grains, this can be accomplished :ref:`statically <static-custom-grains>` or via a :ref:`grain module <writing-grains>`. If using pillar, the yaml configuration can be placed directly into a pillar SLS file, making this both the easier and more dynamic method of configuring this module. .. code-block:: yaml modjk: default: url: http://localhost/jkstatus user: modjk pass: secret realm: authentication realm for digest passwords timeout: 5 otherVhost: url: http://otherVhost/jkstatus user: modjk pass: secret2 realm: authentication realm2 for digest passwords timeout: 600 ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module from salt.ext import six from salt.ext.six.moves.urllib.parse import urlencode as _urlencode from salt.ext.six.moves.urllib.request import ( HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, urlopen as _urlopen, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=import-error,no-name-in-module def __virtual__(): ''' Always load ''' return True def _auth(url, user, passwd, realm): ''' returns a authentication handler. ''' basic = _HTTPBasicAuthHandler() basic.add_password(realm=realm, uri=url, user=user, passwd=passwd) digest = _HTTPDigestAuthHandler() digest.add_password(realm=realm, uri=url, user=user, passwd=passwd) return _build_opener(basic, digest) def _do_http(opts, profile='default'): ''' Make the http request and return the data ''' ret = {} url = __salt__['config.get']('modjk:{0}:url'.format(profile), '') user = __salt__['config.get']('modjk:{0}:user'.format(profile), '') passwd = __salt__['config.get']('modjk:{0}:pass'.format(profile), '') realm = __salt__['config.get']('modjk:{0}:realm'.format(profile), '') timeout = __salt__['config.get']('modjk:{0}:timeout'.format(profile), '') if not url: raise Exception('missing url in profile {0}'.format(profile)) if user and passwd: auth = _auth(url=url, realm=realm, user=user, passwd=passwd) _install_opener(auth) url += '?{0}'.format(_urlencode(opts)) for line in _urlopen(url, timeout=timeout).read().splitlines(): splt = line.split('=', 1) if splt[0] in ret: ret[splt[0]] += ',{0}'.format(splt[1]) else: ret[splt[0]] = splt[1] return ret def _worker_ctl(worker, lbn, vwa, profile='default'): ''' enable/disable/stop a worker ''' cmd = { 'cmd': 'update', 'mime': 'prop', 'w': lbn, 'sw': worker, 'vwa': vwa, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def version(profile='default'): ''' Return the modjk version CLI Examples: .. code-block:: bash salt '*' modjk.version salt '*' modjk.version other-profile ''' cmd = { 'cmd': 'version', 'mime': 'prop', } return _do_http(cmd, profile)['worker.jk_version'].split('/')[-1] def get_running(profile='default'): ''' Get the current running config (not from disk) CLI Examples: .. code-block:: bash salt '*' modjk.get_running salt '*' modjk.get_running other-profile ''' cmd = { 'cmd': 'list', 'mime': 'prop', } return _do_http(cmd, profile) def dump_config(profile='default'): ''' Dump the original configuration that was loaded from disk CLI Examples: .. code-block:: bash salt '*' modjk.dump_config salt '*' modjk.dump_config other-profile ''' cmd = { 'cmd': 'dump', 'mime': 'prop', } return _do_http(cmd, profile) def list_configured_members(lbn, profile='default'): ''' Return a list of member workers from the configuration files CLI Examples: .. code-block:: bash salt '*' modjk.list_configured_members loadbalancer1 salt '*' modjk.list_configured_members loadbalancer1 other-profile ''' config = dump_config(profile) try: ret = config['worker.{0}.balance_workers'.format(lbn)] except KeyError: return [] return [_f for _f in ret.strip().split(',') if _f] def workers(profile='default'): ''' Return a list of member workers and their status CLI Examples: .. code-block:: bash salt '*' modjk.workers salt '*' modjk.workers other-profile ''' config = get_running(profile) lbn = config['worker.list'].split(',') worker_list = [] ret = {} for lb in lbn: try: worker_list.extend( config['worker.{0}.balance_workers'.format(lb)].split(',') ) except KeyError: pass worker_list = list(set(worker_list)) for worker in worker_list: ret[worker] = { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } return ret def recover_all(lbn, profile='default'): ''' Set the all the workers in lbn to recover and activate them if they are not CLI Examples: .. code-block:: bash salt '*' modjk.recover_all loadbalancer1 salt '*' modjk.recover_all loadbalancer1 other-profile ''' ret = {} config = get_running(profile) try: workers_ = config['worker.{0}.balance_workers'.format(lbn)].split(',') except KeyError: return ret for worker in workers_: curr_state = worker_status(worker, profile) if curr_state['activation'] != 'ACT': worker_activate(worker, lbn, profile) if not curr_state['state'].startswith('OK'): worker_recover(worker, lbn, profile) ret[worker] = worker_status(worker, profile) return ret def reset_stats(lbn, profile='default'): ''' Reset all runtime statistics for the load balancer CLI Examples: .. code-block:: bash salt '*' modjk.reset_stats loadbalancer1 salt '*' modjk.reset_stats loadbalancer1 other-profile ''' cmd = { 'cmd': 'reset', 'mime': 'prop', 'w': lbn, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def lb_edit(lbn, settings, profile='default'): ''' Edit the loadbalancer settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn return _do_http(settings, profile)['worker.result.type'] == 'OK' def bulk_stop(workers, lbn, profile='default'): ''' Stop all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_stop(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_activate(workers, lbn, profile='default'): ''' Activate all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_activate(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_disable(workers, lbn, profile='default'): ''' Disable all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_disable(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_recover(workers, lbn, profile='default'): ''' Recover all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_recover(worker, lbn, profile) except Exception: ret[worker] = False return ret def worker_status(worker, profile='default'): ''' Return the state of the worker CLI Examples: .. code-block:: bash salt '*' modjk.worker_status node1 salt '*' modjk.worker_status node1 other-profile ''' config = get_running(profile) try: return { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } except KeyError: return False def worker_disable(worker, lbn, profile='default'): ''' Set the worker to disable state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_disable node1 loadbalancer1 salt '*' modjk.worker_disable node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'd', profile) def worker_activate(worker, lbn, profile='default'): ''' Set the worker to activate state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'a', profile) def worker_stop(worker, lbn, profile='default'): ''' Set the worker to stopped state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 's', profile) def worker_edit(worker, lbn, settings, profile='default'): ''' Edit the worker settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn settings['sw'] = worker return _do_http(settings, profile)['worker.result.type'] == 'OK'
saltstack/salt
salt/modules/modjk.py
worker_edit
python
def worker_edit(worker, lbn, settings, profile='default'): ''' Edit the worker settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn settings['sw'] = worker return _do_http(settings, profile)['worker.result.type'] == 'OK'
Edit the worker settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}" other-profile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L507-L527
[ "def _do_http(opts, profile='default'):\n '''\n Make the http request and return the data\n '''\n\n ret = {}\n\n url = __salt__['config.get']('modjk:{0}:url'.format(profile), '')\n user = __salt__['config.get']('modjk:{0}:user'.format(profile), '')\n passwd = __salt__['config.get']('modjk:{0}:pass'.format(profile), '')\n realm = __salt__['config.get']('modjk:{0}:realm'.format(profile), '')\n timeout = __salt__['config.get']('modjk:{0}:timeout'.format(profile), '')\n\n if not url:\n raise Exception('missing url in profile {0}'.format(profile))\n\n if user and passwd:\n auth = _auth(url=url, realm=realm, user=user, passwd=passwd)\n _install_opener(auth)\n\n url += '?{0}'.format(_urlencode(opts))\n\n for line in _urlopen(url, timeout=timeout).read().splitlines():\n splt = line.split('=', 1)\n if splt[0] in ret:\n ret[splt[0]] += ',{0}'.format(splt[1])\n else:\n ret[splt[0]] = splt[1]\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Control Modjk via the Apache Tomcat "Status" worker (http://tomcat.apache.org/connectors-doc/reference/status.html) Below is an example of the configuration needed for this module. This configuration data can be placed either in :ref:`grains <targeting-grains>` or :ref:`pillar <salt-pillars>`. If using grains, this can be accomplished :ref:`statically <static-custom-grains>` or via a :ref:`grain module <writing-grains>`. If using pillar, the yaml configuration can be placed directly into a pillar SLS file, making this both the easier and more dynamic method of configuring this module. .. code-block:: yaml modjk: default: url: http://localhost/jkstatus user: modjk pass: secret realm: authentication realm for digest passwords timeout: 5 otherVhost: url: http://otherVhost/jkstatus user: modjk pass: secret2 realm: authentication realm2 for digest passwords timeout: 600 ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module from salt.ext import six from salt.ext.six.moves.urllib.parse import urlencode as _urlencode from salt.ext.six.moves.urllib.request import ( HTTPBasicAuthHandler as _HTTPBasicAuthHandler, HTTPDigestAuthHandler as _HTTPDigestAuthHandler, urlopen as _urlopen, build_opener as _build_opener, install_opener as _install_opener ) # pylint: enable=import-error,no-name-in-module def __virtual__(): ''' Always load ''' return True def _auth(url, user, passwd, realm): ''' returns a authentication handler. ''' basic = _HTTPBasicAuthHandler() basic.add_password(realm=realm, uri=url, user=user, passwd=passwd) digest = _HTTPDigestAuthHandler() digest.add_password(realm=realm, uri=url, user=user, passwd=passwd) return _build_opener(basic, digest) def _do_http(opts, profile='default'): ''' Make the http request and return the data ''' ret = {} url = __salt__['config.get']('modjk:{0}:url'.format(profile), '') user = __salt__['config.get']('modjk:{0}:user'.format(profile), '') passwd = __salt__['config.get']('modjk:{0}:pass'.format(profile), '') realm = __salt__['config.get']('modjk:{0}:realm'.format(profile), '') timeout = __salt__['config.get']('modjk:{0}:timeout'.format(profile), '') if not url: raise Exception('missing url in profile {0}'.format(profile)) if user and passwd: auth = _auth(url=url, realm=realm, user=user, passwd=passwd) _install_opener(auth) url += '?{0}'.format(_urlencode(opts)) for line in _urlopen(url, timeout=timeout).read().splitlines(): splt = line.split('=', 1) if splt[0] in ret: ret[splt[0]] += ',{0}'.format(splt[1]) else: ret[splt[0]] = splt[1] return ret def _worker_ctl(worker, lbn, vwa, profile='default'): ''' enable/disable/stop a worker ''' cmd = { 'cmd': 'update', 'mime': 'prop', 'w': lbn, 'sw': worker, 'vwa': vwa, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def version(profile='default'): ''' Return the modjk version CLI Examples: .. code-block:: bash salt '*' modjk.version salt '*' modjk.version other-profile ''' cmd = { 'cmd': 'version', 'mime': 'prop', } return _do_http(cmd, profile)['worker.jk_version'].split('/')[-1] def get_running(profile='default'): ''' Get the current running config (not from disk) CLI Examples: .. code-block:: bash salt '*' modjk.get_running salt '*' modjk.get_running other-profile ''' cmd = { 'cmd': 'list', 'mime': 'prop', } return _do_http(cmd, profile) def dump_config(profile='default'): ''' Dump the original configuration that was loaded from disk CLI Examples: .. code-block:: bash salt '*' modjk.dump_config salt '*' modjk.dump_config other-profile ''' cmd = { 'cmd': 'dump', 'mime': 'prop', } return _do_http(cmd, profile) def list_configured_members(lbn, profile='default'): ''' Return a list of member workers from the configuration files CLI Examples: .. code-block:: bash salt '*' modjk.list_configured_members loadbalancer1 salt '*' modjk.list_configured_members loadbalancer1 other-profile ''' config = dump_config(profile) try: ret = config['worker.{0}.balance_workers'.format(lbn)] except KeyError: return [] return [_f for _f in ret.strip().split(',') if _f] def workers(profile='default'): ''' Return a list of member workers and their status CLI Examples: .. code-block:: bash salt '*' modjk.workers salt '*' modjk.workers other-profile ''' config = get_running(profile) lbn = config['worker.list'].split(',') worker_list = [] ret = {} for lb in lbn: try: worker_list.extend( config['worker.{0}.balance_workers'.format(lb)].split(',') ) except KeyError: pass worker_list = list(set(worker_list)) for worker in worker_list: ret[worker] = { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } return ret def recover_all(lbn, profile='default'): ''' Set the all the workers in lbn to recover and activate them if they are not CLI Examples: .. code-block:: bash salt '*' modjk.recover_all loadbalancer1 salt '*' modjk.recover_all loadbalancer1 other-profile ''' ret = {} config = get_running(profile) try: workers_ = config['worker.{0}.balance_workers'.format(lbn)].split(',') except KeyError: return ret for worker in workers_: curr_state = worker_status(worker, profile) if curr_state['activation'] != 'ACT': worker_activate(worker, lbn, profile) if not curr_state['state'].startswith('OK'): worker_recover(worker, lbn, profile) ret[worker] = worker_status(worker, profile) return ret def reset_stats(lbn, profile='default'): ''' Reset all runtime statistics for the load balancer CLI Examples: .. code-block:: bash salt '*' modjk.reset_stats loadbalancer1 salt '*' modjk.reset_stats loadbalancer1 other-profile ''' cmd = { 'cmd': 'reset', 'mime': 'prop', 'w': lbn, } return _do_http(cmd, profile)['worker.result.type'] == 'OK' def lb_edit(lbn, settings, profile='default'): ''' Edit the loadbalancer settings Note: http://tomcat.apache.org/connectors-doc/reference/status.html Data Parameters for the standard Update Action CLI Examples: .. code-block:: bash salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" salt '*' modjk.lb_edit loadbalancer1 "{'vlr': 1, 'vlt': 60}" other-profile ''' settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn return _do_http(settings, profile)['worker.result.type'] == 'OK' def bulk_stop(workers, lbn, profile='default'): ''' Stop all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_stop node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_stop ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_stop(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_activate(workers, lbn, profile='default'): ''' Activate all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_activate ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_activate(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_disable(workers, lbn, profile='default'): ''' Disable all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_disable node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_disable ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_disable(worker, lbn, profile) except Exception: ret[worker] = False return ret def bulk_recover(workers, lbn, profile='default'): ''' Recover all the given workers in the specific load balancer CLI Examples: .. code-block:: bash salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 other-profile salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 salt '*' modjk.bulk_recover ["node1","node2","node3"] loadbalancer1 other-profile ''' ret = {} if isinstance(workers, six.string_types): workers = workers.split(',') for worker in workers: try: ret[worker] = worker_recover(worker, lbn, profile) except Exception: ret[worker] = False return ret def worker_status(worker, profile='default'): ''' Return the state of the worker CLI Examples: .. code-block:: bash salt '*' modjk.worker_status node1 salt '*' modjk.worker_status node1 other-profile ''' config = get_running(profile) try: return { 'activation': config['worker.{0}.activation'.format(worker)], 'state': config['worker.{0}.state'.format(worker)], } except KeyError: return False def worker_recover(worker, lbn, profile='default'): ''' Set the worker to recover this module will fail if it is in OK state CLI Examples: .. code-block:: bash salt '*' modjk.worker_recover node1 loadbalancer1 salt '*' modjk.worker_recover node1 loadbalancer1 other-profile ''' cmd = { 'cmd': 'recover', 'mime': 'prop', 'w': lbn, 'sw': worker, } return _do_http(cmd, profile) def worker_disable(worker, lbn, profile='default'): ''' Set the worker to disable state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_disable node1 loadbalancer1 salt '*' modjk.worker_disable node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'd', profile) def worker_activate(worker, lbn, profile='default'): ''' Set the worker to activate state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 'a', profile) def worker_stop(worker, lbn, profile='default'): ''' Set the worker to stopped state in the lbn load balancer CLI Examples: .. code-block:: bash salt '*' modjk.worker_activate node1 loadbalancer1 salt '*' modjk.worker_activate node1 loadbalancer1 other-profile ''' return _worker_ctl(worker, lbn, 's', profile)
saltstack/salt
salt/modules/nginx.py
build_info
python
def build_info(): ''' Return server and build arguments CLI Example: .. code-block:: bash salt '*' nginx.build_info ''' ret = {'info': []} out = __salt__['cmd.run']('{0} -V'.format(__detect_os())) for i in out.splitlines(): if i.startswith('configure argument'): ret['build arguments'] = re.findall(r"(?:[^\s]*'.*')|(?:[^\s]+)", i)[2:] continue ret['info'].append(i) return ret
Return server and build arguments CLI Example: .. code-block:: bash salt '*' nginx.build_info
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nginx.py#L50-L70
null
# -*- coding: utf-8 -*- ''' Support for nginx ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs from salt.ext.six.moves.urllib.request import urlopen as _urlopen # pylint: disable=no-name-in-module,import-error # Import salt libs import salt.utils.path import salt.utils.decorators as decorators import re # Cache the output of running which('nginx') so this module # doesn't needlessly walk $PATH looking for the same binary # for nginx over and over and over for each function herein @decorators.memoize def __detect_os(): return salt.utils.path.which('nginx') def __virtual__(): ''' Only load the module if nginx is installed ''' if __detect_os(): return True return (False, 'The nginx execution module cannot be loaded: nginx is not installed.') def version(): ''' Return server version from nginx -v CLI Example: .. code-block:: bash salt '*' nginx.version ''' cmd = '{0} -v'.format(__detect_os()) out = __salt__['cmd.run'](cmd).splitlines() ret = out[0].split(': ')[-1].split('/') return ret[-1] def configtest(): ''' test configuration and exit CLI Example: .. code-block:: bash salt '*' nginx.configtest ''' ret = {} cmd = '{0} -t'.format(__detect_os()) out = __salt__['cmd.run_all'](cmd) if out['retcode'] != 0: ret['comment'] = 'Syntax Error' ret['stderr'] = out['stderr'] ret['result'] = False return ret ret['comment'] = 'Syntax OK' ret['stdout'] = out['stderr'] ret['result'] = True return ret def signal(signal=None): ''' Signals nginx to start, reload, reopen or stop. CLI Example: .. code-block:: bash salt '*' nginx.signal reload ''' valid_signals = ('start', 'reopen', 'stop', 'quit', 'reload') if signal not in valid_signals: return # Make sure you use the right arguments if signal == "start": arguments = '' else: arguments = ' -s {0}'.format(signal) cmd = __detect_os() + arguments out = __salt__['cmd.run_all'](cmd) # A non-zero return code means fail if out['retcode'] and out['stderr']: ret = out['stderr'].strip() # 'nginxctl configtest' returns 'Syntax OK' to stderr elif out['stderr']: ret = out['stderr'].strip() elif out['stdout']: ret = out['stdout'].strip() # No output for something like: nginxctl graceful else: ret = 'Command: "{0}" completed successfully!'.format(cmd) return ret def status(url="http://127.0.0.1/status"): """ Return the data from an Nginx status page as a dictionary. http://wiki.nginx.org/HttpStubStatusModule url The URL of the status page. Defaults to 'http://127.0.0.1/status' CLI Example: .. code-block:: bash salt '*' nginx.status """ resp = _urlopen(url) status_data = resp.read() resp.close() lines = status_data.splitlines() if not len(lines) == 4: return # "Active connections: 1 " active_connections = lines[0].split()[2] # "server accepts handled requests" # " 12 12 9 " accepted, handled, requests = lines[2].split() # "Reading: 0 Writing: 1 Waiting: 0 " _, reading, _, writing, _, waiting = lines[3].split() return { 'active connections': int(active_connections), 'accepted': int(accepted), 'handled': int(handled), 'requests': int(requests), 'reading': int(reading), 'writing': int(writing), 'waiting': int(waiting), }
saltstack/salt
salt/modules/nginx.py
signal
python
def signal(signal=None): ''' Signals nginx to start, reload, reopen or stop. CLI Example: .. code-block:: bash salt '*' nginx.signal reload ''' valid_signals = ('start', 'reopen', 'stop', 'quit', 'reload') if signal not in valid_signals: return # Make sure you use the right arguments if signal == "start": arguments = '' else: arguments = ' -s {0}'.format(signal) cmd = __detect_os() + arguments out = __salt__['cmd.run_all'](cmd) # A non-zero return code means fail if out['retcode'] and out['stderr']: ret = out['stderr'].strip() # 'nginxctl configtest' returns 'Syntax OK' to stderr elif out['stderr']: ret = out['stderr'].strip() elif out['stdout']: ret = out['stdout'].strip() # No output for something like: nginxctl graceful else: ret = 'Command: "{0}" completed successfully!'.format(cmd) return ret
Signals nginx to start, reload, reopen or stop. CLI Example: .. code-block:: bash salt '*' nginx.signal reload
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nginx.py#L102-L136
null
# -*- coding: utf-8 -*- ''' Support for nginx ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs from salt.ext.six.moves.urllib.request import urlopen as _urlopen # pylint: disable=no-name-in-module,import-error # Import salt libs import salt.utils.path import salt.utils.decorators as decorators import re # Cache the output of running which('nginx') so this module # doesn't needlessly walk $PATH looking for the same binary # for nginx over and over and over for each function herein @decorators.memoize def __detect_os(): return salt.utils.path.which('nginx') def __virtual__(): ''' Only load the module if nginx is installed ''' if __detect_os(): return True return (False, 'The nginx execution module cannot be loaded: nginx is not installed.') def version(): ''' Return server version from nginx -v CLI Example: .. code-block:: bash salt '*' nginx.version ''' cmd = '{0} -v'.format(__detect_os()) out = __salt__['cmd.run'](cmd).splitlines() ret = out[0].split(': ')[-1].split('/') return ret[-1] def build_info(): ''' Return server and build arguments CLI Example: .. code-block:: bash salt '*' nginx.build_info ''' ret = {'info': []} out = __salt__['cmd.run']('{0} -V'.format(__detect_os())) for i in out.splitlines(): if i.startswith('configure argument'): ret['build arguments'] = re.findall(r"(?:[^\s]*'.*')|(?:[^\s]+)", i)[2:] continue ret['info'].append(i) return ret def configtest(): ''' test configuration and exit CLI Example: .. code-block:: bash salt '*' nginx.configtest ''' ret = {} cmd = '{0} -t'.format(__detect_os()) out = __salt__['cmd.run_all'](cmd) if out['retcode'] != 0: ret['comment'] = 'Syntax Error' ret['stderr'] = out['stderr'] ret['result'] = False return ret ret['comment'] = 'Syntax OK' ret['stdout'] = out['stderr'] ret['result'] = True return ret def status(url="http://127.0.0.1/status"): """ Return the data from an Nginx status page as a dictionary. http://wiki.nginx.org/HttpStubStatusModule url The URL of the status page. Defaults to 'http://127.0.0.1/status' CLI Example: .. code-block:: bash salt '*' nginx.status """ resp = _urlopen(url) status_data = resp.read() resp.close() lines = status_data.splitlines() if not len(lines) == 4: return # "Active connections: 1 " active_connections = lines[0].split()[2] # "server accepts handled requests" # " 12 12 9 " accepted, handled, requests = lines[2].split() # "Reading: 0 Writing: 1 Waiting: 0 " _, reading, _, writing, _, waiting = lines[3].split() return { 'active connections': int(active_connections), 'accepted': int(accepted), 'handled': int(handled), 'requests': int(requests), 'reading': int(reading), 'writing': int(writing), 'waiting': int(waiting), }
saltstack/salt
salt/modules/nginx.py
status
python
def status(url="http://127.0.0.1/status"): resp = _urlopen(url) status_data = resp.read() resp.close() lines = status_data.splitlines() if not len(lines) == 4: return # "Active connections: 1 " active_connections = lines[0].split()[2] # "server accepts handled requests" # " 12 12 9 " accepted, handled, requests = lines[2].split() # "Reading: 0 Writing: 1 Waiting: 0 " _, reading, _, writing, _, waiting = lines[3].split() return { 'active connections': int(active_connections), 'accepted': int(accepted), 'handled': int(handled), 'requests': int(requests), 'reading': int(reading), 'writing': int(writing), 'waiting': int(waiting), }
Return the data from an Nginx status page as a dictionary. http://wiki.nginx.org/HttpStubStatusModule url The URL of the status page. Defaults to 'http://127.0.0.1/status' CLI Example: .. code-block:: bash salt '*' nginx.status
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nginx.py#L139-L175
null
# -*- coding: utf-8 -*- ''' Support for nginx ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs from salt.ext.six.moves.urllib.request import urlopen as _urlopen # pylint: disable=no-name-in-module,import-error # Import salt libs import salt.utils.path import salt.utils.decorators as decorators import re # Cache the output of running which('nginx') so this module # doesn't needlessly walk $PATH looking for the same binary # for nginx over and over and over for each function herein @decorators.memoize def __detect_os(): return salt.utils.path.which('nginx') def __virtual__(): ''' Only load the module if nginx is installed ''' if __detect_os(): return True return (False, 'The nginx execution module cannot be loaded: nginx is not installed.') def version(): ''' Return server version from nginx -v CLI Example: .. code-block:: bash salt '*' nginx.version ''' cmd = '{0} -v'.format(__detect_os()) out = __salt__['cmd.run'](cmd).splitlines() ret = out[0].split(': ')[-1].split('/') return ret[-1] def build_info(): ''' Return server and build arguments CLI Example: .. code-block:: bash salt '*' nginx.build_info ''' ret = {'info': []} out = __salt__['cmd.run']('{0} -V'.format(__detect_os())) for i in out.splitlines(): if i.startswith('configure argument'): ret['build arguments'] = re.findall(r"(?:[^\s]*'.*')|(?:[^\s]+)", i)[2:] continue ret['info'].append(i) return ret def configtest(): ''' test configuration and exit CLI Example: .. code-block:: bash salt '*' nginx.configtest ''' ret = {} cmd = '{0} -t'.format(__detect_os()) out = __salt__['cmd.run_all'](cmd) if out['retcode'] != 0: ret['comment'] = 'Syntax Error' ret['stderr'] = out['stderr'] ret['result'] = False return ret ret['comment'] = 'Syntax OK' ret['stdout'] = out['stderr'] ret['result'] = True return ret def signal(signal=None): ''' Signals nginx to start, reload, reopen or stop. CLI Example: .. code-block:: bash salt '*' nginx.signal reload ''' valid_signals = ('start', 'reopen', 'stop', 'quit', 'reload') if signal not in valid_signals: return # Make sure you use the right arguments if signal == "start": arguments = '' else: arguments = ' -s {0}'.format(signal) cmd = __detect_os() + arguments out = __salt__['cmd.run_all'](cmd) # A non-zero return code means fail if out['retcode'] and out['stderr']: ret = out['stderr'].strip() # 'nginxctl configtest' returns 'Syntax OK' to stderr elif out['stderr']: ret = out['stderr'].strip() elif out['stdout']: ret = out['stdout'].strip() # No output for something like: nginxctl graceful else: ret = 'Command: "{0}" completed successfully!'.format(cmd) return ret
saltstack/salt
salt/proxy/esxi.py
init
python
def init(opts): ''' This function gets called when the proxy starts up. For ESXi devices, the host, login credentials, and, if configured, the protocol and port are cached. ''' log.debug('Initting esxi proxy module in process %s', os.getpid()) log.debug('Validating esxi proxy input') schema = EsxiProxySchema.serialize() log.trace('esxi_proxy_schema = %s', schema) proxy_conf = merge(opts.get('proxy', {}), __pillar__.get('proxy', {})) log.trace('proxy_conf = %s', proxy_conf) try: jsonschema.validate(proxy_conf, schema) except jsonschema.exceptions.ValidationError as exc: raise InvalidConfigError(exc) DETAILS['proxytype'] = proxy_conf['proxytype'] if ('host' not in proxy_conf) and ('vcenter' not in proxy_conf): log.critical('Neither \'host\' nor \'vcenter\' keys found in pillar ' 'for this proxy.') return False if 'host' in proxy_conf: # We have started the proxy by connecting directly to the host if 'username' not in proxy_conf: log.critical('No \'username\' key found in pillar for this proxy.') return False if 'passwords' not in proxy_conf: log.critical('No \'passwords\' key found in pillar for this proxy.') return False host = proxy_conf['host'] # Get the correct login details try: username, password = find_credentials(host) except SaltSystemExit as err: log.critical('Error: %s', err) return False # Set configuration details DETAILS['host'] = host DETAILS['username'] = username DETAILS['password'] = password DETAILS['protocol'] = proxy_conf.get('protocol') DETAILS['port'] = proxy_conf.get('port') return True if 'vcenter' in proxy_conf: vcenter = proxy_conf['vcenter'] if not proxy_conf.get('esxi_host'): log.critical('No \'esxi_host\' key found in pillar for this proxy.') DETAILS['esxi_host'] = proxy_conf['esxi_host'] # We have started the proxy by connecting via the vCenter if 'mechanism' not in proxy_conf: log.critical('No \'mechanism\' key found in pillar for this proxy.') return False mechanism = proxy_conf['mechanism'] # Save mandatory fields in cache for key in ('vcenter', 'mechanism'): DETAILS[key] = proxy_conf[key] if mechanism == 'userpass': if 'username' not in proxy_conf: log.critical('No \'username\' key found in pillar for this ' 'proxy.') return False if 'passwords' not in proxy_conf and proxy_conf['passwords']: log.critical('Mechanism is set to \'userpass\' , but no ' '\'passwords\' key found in pillar for this ' 'proxy.') return False for key in ('username', 'passwords'): DETAILS[key] = proxy_conf[key] elif mechanism == 'sspi': if 'domain' not in proxy_conf: log.critical('Mechanism is set to \'sspi\' , but no ' '\'domain\' key found in pillar for this proxy.') return False if 'principal' not in proxy_conf: log.critical('Mechanism is set to \'sspi\' , but no ' '\'principal\' key found in pillar for this ' 'proxy.') return False for key in ('domain', 'principal'): DETAILS[key] = proxy_conf[key] if mechanism == 'userpass': # Get the correct login details log.debug('Retrieving credentials and testing vCenter connection' ' for mehchanism \'userpass\'') try: username, password = find_credentials(DETAILS['vcenter']) DETAILS['password'] = password except SaltSystemExit as err: log.critical('Error: %s', err) return False # Save optional DETAILS['protocol'] = proxy_conf.get('protocol', 'https') DETAILS['port'] = proxy_conf.get('port', '443') DETAILS['credstore'] = proxy_conf.get('credstore')
This function gets called when the proxy starts up. For ESXi devices, the host, login credentials, and, if configured, the protocol and port are cached.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/esxi.py#L314-L414
[ "def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False):\n if strategy == 'smart':\n if renderer.split('|')[-1] == 'yamlex' or renderer.startswith('yamlex_'):\n strategy = 'aggregate'\n else:\n strategy = 'recurse'\n\n if strategy == 'list':\n merged = merge_list(obj_a, obj_b)\n elif strategy == 'recurse':\n merged = merge_recurse(obj_a, obj_b, merge_lists)\n elif strategy == 'aggregate':\n #: level = 1 merge at least root data\n merged = merge_aggregate(obj_a, obj_b)\n elif strategy == 'overwrite':\n merged = merge_overwrite(obj_a, obj_b, merge_lists)\n elif strategy == 'none':\n # If we do not want to merge, there is only one pillar passed, so we can safely use the default recurse,\n # we just do not want to log an error\n merged = merge_recurse(obj_a, obj_b)\n else:\n log.warning(\n 'Unknown merging strategy \\'%s\\', fallback to recurse',\n strategy\n )\n merged = merge_recurse(obj_a, obj_b)\n\n return merged\n", "def find_credentials(host):\n '''\n Cycle through all the possible credentials and return the first one that\n works.\n '''\n user_names = [__pillar__['proxy'].get('username', 'root')]\n passwords = __pillar__['proxy']['passwords']\n for user in user_names:\n for password in passwords:\n try:\n # Try to authenticate with the given user/password combination\n ret = __salt__['vsphere.system_info'](host=host,\n username=user,\n password=password)\n except SaltSystemExit:\n # If we can't authenticate, continue on to try the next password.\n continue\n # If we have data returned from above, we've successfully authenticated.\n if ret:\n DETAILS['username'] = user\n DETAILS['password'] = password\n return user, password\n # We've reached the end of the list without successfully authenticating.\n raise SaltSystemExit('Cannot complete login due to an incorrect user name or password.')\n", "def serialize(cls, id_=None):\n # The order matters\n serialized = OrderedDict()\n if id_ is not None:\n # This is meant as a configuration section, sub json schema\n serialized['id'] = '{0}/{1}.json#'.format(BASE_SCHEMA_URL, id_)\n else:\n # Main configuration block, json schema\n serialized['$schema'] = 'http://json-schema.org/draft-04/schema#'\n if cls.title is not None:\n serialized['title'] = cls.title\n if cls.description is not None:\n if cls.description == cls.__doc__:\n serialized['description'] = textwrap.dedent(cls.description).strip()\n else:\n serialized['description'] = cls.description\n\n required = []\n ordering = []\n serialized['type'] = 'object'\n properties = OrderedDict()\n cls.after_items_update = []\n for name in cls._order: # pylint: disable=E1133\n skip_order = False\n item_name = None\n if name in cls._sections: # pylint: disable=E1135\n section = cls._sections[name]\n serialized_section = section.serialize(None if section.__flatten__ is True else name)\n if section.__flatten__ is True:\n # Flatten the configuration section into the parent\n # configuration\n properties.update(serialized_section['properties'])\n if 'x-ordering' in serialized_section:\n ordering.extend(serialized_section['x-ordering'])\n if 'required' in serialized_section:\n required.extend(serialized_section['required'])\n if hasattr(section, 'after_items_update'):\n cls.after_items_update.extend(section.after_items_update)\n skip_order = True\n else:\n # Store it as a configuration section\n properties[name] = serialized_section\n\n if name in cls._items: # pylint: disable=E1135\n config = cls._items[name]\n item_name = config.__item_name__ or name\n # Handle the configuration items defined in the class instance\n if config.__flatten__ is True:\n serialized_config = config.serialize()\n cls.after_items_update.append(serialized_config)\n skip_order = True\n else:\n properties[item_name] = config.serialize()\n\n if config.required:\n # If it's a required item, add it to the required list\n required.append(item_name)\n\n if skip_order is False:\n # Store the order of the item\n if item_name is not None:\n if item_name not in ordering:\n ordering.append(item_name)\n else:\n if name not in ordering:\n ordering.append(name)\n\n if properties:\n serialized['properties'] = properties\n\n # Update the serialized object with any items to include after properties.\n # Do not overwrite properties already existing in the serialized dict.\n if cls.after_items_update:\n after_items_update = {}\n for entry in cls.after_items_update:\n for name, data in six.iteritems(entry):\n if name in after_items_update:\n if isinstance(after_items_update[name], list):\n after_items_update[name].extend(data)\n else:\n after_items_update[name] = data\n if after_items_update:\n after_items_update.update(serialized)\n serialized = after_items_update\n\n if required:\n # Only include required if not empty\n serialized['required'] = required\n if ordering:\n # Only include ordering if not empty\n serialized['x-ordering'] = ordering\n serialized['additionalProperties'] = cls.__allow_additional_items__\n return serialized\n" ]
# -*- coding: utf-8 -*- ''' Proxy Minion interface module for managing VMware ESXi hosts. .. versionadded:: 2015.8.4 **Special Note: SaltStack thanks** `Adobe Corporation <http://adobe.com/>`_ **for their support in creating this Proxy Minion integration.** This proxy minion enables VMware ESXi (hereafter referred to as simply 'ESXi') hosts to be treated individually like a Salt Minion. Since the ESXi host may not necessarily run on an OS capable of hosting a Python stack, the ESXi host can't run a Salt Minion directly. Salt's "Proxy Minion" functionality enables you to designate another machine to host a minion process that "proxies" communication from the Salt Master. The master does not know nor care that the target is not a "real" Salt Minion. More in-depth conceptual reading on Proxy Minions can be found in the :ref:`Proxy Minion <proxy-minion>` section of Salt's documentation. Dependencies ============ - pyVmomi Python Module - ESXCLI pyVmomi ------- PyVmomi can be installed via pip: .. code-block:: bash pip install pyVmomi .. note:: Version 6.0 of pyVmomi has some problems with SSL error handling on certain versions of Python. If using version 6.0 of pyVmomi, Python 2.6, Python 2.7.9, or newer must be present. This is due to an upstream dependency in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the version of Python is not in the supported range, you will need to install an earlier version of pyVmomi. See `Issue #29537`_ for more information. .. _Issue #29537: https://github.com/saltstack/salt/issues/29537 Based on the note above, to install an earlier version of pyVmomi than the version currently listed in PyPi, run the following: .. code-block:: bash pip install pyVmomi==5.5.0.2014.1.1 The 5.5.0.2014.1.1 is a known stable version that this original ESXi State Module was developed against. ESXCLI ------ Currently, about a third of the functions used in the vSphere Execution Module require the ESXCLI package be installed on the machine running the Proxy Minion process. The ESXCLI package is also referred to as the VMware vSphere CLI, or vCLI. VMware provides vCLI package installation instructions for `vSphere 5.5`_ and `vSphere 6.0`_. .. _vSphere 5.5: http://pubs.vmware.com/vsphere-55/index.jsp#com.vmware.vcli.getstart.doc/cli_install.4.2.html .. _vSphere 6.0: http://pubs.vmware.com/vsphere-60/index.jsp#com.vmware.vcli.getstart.doc/cli_install.4.2.html Once all of the required dependencies are in place and the vCLI package is installed, you can check to see if you can connect to your ESXi host or vCenter server by running the following command: .. code-block:: bash esxcli -s <host-location> -u <username> -p <password> system syslog config get If the connection was successful, ESXCLI was successfully installed on your system. You should see output related to the ESXi host's syslog configuration. Configuration ============= To use this integration proxy module, please configure the following: Pillar ------ Proxy minions get their configuration from Salt's Pillar. Every proxy must have a stanza in Pillar and a reference in the Pillar top-file that matches the ID. At a minimum for communication with the ESXi host, the pillar should look like this: .. code-block:: yaml proxy: proxytype: esxi host: <ip or dns name of esxi host> username: <ESXi username> passwords: - first_password - second_password - third_password credstore: <path to credential store> proxytype ^^^^^^^^^ The ``proxytype`` key and value pair is critical, as it tells Salt which interface to load from the ``proxy`` directory in Salt's install hierarchy, or from ``/srv/salt/_proxy`` on the Salt Master (if you have created your own proxy module, for example). To use this ESXi Proxy Module, set this to ``esxi``. host ^^^^ The location, or ip/dns, of the ESXi host. Required. username ^^^^^^^^ The username used to login to the ESXi host, such as ``root``. Required. passwords ^^^^^^^^^ A list of passwords to be used to try and login to the ESXi host. At least one password in this list is required. The proxy integration will try the passwords listed in order. It is configured this way so you can have a regular password and the password you may be updating for an ESXi host either via the :mod:`vsphere.update_host_password <salt.modules.vsphere.update_host_password>` execution module function or via the :mod:`esxi.password_present <salt.states.esxi.password_present>` state function. This way, after the password is changed, you should not need to restart the proxy minion--it should just pick up the the new password provided in the list. You can then change pillar at will to move that password to the front and retire the unused ones. This also allows you to use any number of potential fallback passwords. .. note:: When a password is changed on the host to one in the list of possible passwords, the further down on the list the password is, the longer individual commands will take to return. This is due to the nature of pyVmomi's login system. We have to wait for the first attempt to fail before trying the next password on the list. This scenario is especially true, and even slower, when the proxy minion first starts. If the correct password is not the first password on the list, it may take up to a minute for ``test.ping`` to respond with a ``True`` result. Once the initial authorization is complete, the responses for commands will be a little faster. To avoid these longer waiting periods, SaltStack recommends moving the correct password to the top of the list and restarting the proxy minion at your earliest convenience. protocol ^^^^^^^^ If the ESXi host is not using the default protocol, set this value to an alternate protocol. Default is ``https``. port ^^^^ If the ESXi host is not using the default port, set this value to an alternate port. Default is ``443``. credstore ^^^^^^^^^ If the ESXi host is using an untrusted SSL certificate, set this value to the file path where the credential store is located. This file is passed to ``esxcli``. Default is ``<HOME>/.vmware/credstore/vicredentials.xml`` on Linux and ``<APPDATA>/VMware/credstore/vicredentials.xml`` on Windows. .. note:: ``HOME`` variable is sometimes not set for processes running as system services. If you want to rely on the default credential store location, make sure ``HOME`` is set for the proxy process. Salt Proxy ---------- After your pillar is in place, you can test the proxy. The proxy can run on any machine that has network connectivity to your Salt Master and to the ESXi host in question. SaltStack recommends that the machine running the salt-proxy process also run a regular minion, though it is not strictly necessary. On the machine that will run the proxy, make sure there is an ``/etc/salt/proxy`` file with at least the following in it: .. code-block:: yaml master: <ip or hostname of salt-master> You can then start the salt-proxy process with: .. code-block:: bash salt-proxy --proxyid <id you want to give the host> You may want to add ``-l debug`` to run the above in the foreground in debug mode just to make sure everything is OK. Next, accept the key for the proxy on your salt-master, just like you would for a regular minion: .. code-block:: bash salt-key -a <id you gave the esxi host> You can confirm that the pillar data is in place for the proxy: .. code-block:: bash salt <id> pillar.items And now you should be able to ping the ESXi host to make sure it is responding: .. code-block:: bash salt <id> test.ping At this point you can execute one-off commands against the host. For example, you can get the ESXi host's system information: .. code-block:: bash salt <id> esxi.cmd system_info Note that you don't need to provide credentials or an ip/hostname. Salt knows to use the credentials you stored in Pillar. It's important to understand how this particular proxy works. :mod:`Salt.modules.vsphere <salt.modules.vsphere>` is a standard Salt execution module. If you pull up the docs for it you'll see that almost every function in the module takes credentials and a target host. When credentials and a host aren't passed, Salt runs commands through ``pyVmomi`` against the local machine. If you wanted, you could run functions from this module on any host where an appropriate version of ``pyVmomi`` is installed, and that host would reach out over the network and communicate with the ESXi host. ``esxi.cmd`` acts as a "shim" between the execution module and the proxy. Its first parameter is always the function from salt.modules.vsphere. If the function takes more positional or keyword arguments you can append them to the call. It's this shim that speaks to the ESXi host through the proxy, arranging for the credentials and hostname to be pulled from the Pillar section for this Proxy Minion. Because of the presence of the shim, to lookup documentation for what functions you can use to interface with the ESXi host, you'll want to look in :mod:`salt.modules.vsphere <salt.modules.vsphere>` instead of :mod:`salt.modules.esxi <salt.modules.esxi>`. States ------ Associated states are thoroughly documented in :mod:`salt.states.esxi <salt.states.esxi>`. Look there to find an example structure for Pillar as well as an example ``.sls`` file for standing up an ESXi host from scratch. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os # Import Salt Libs from salt.exceptions import SaltSystemExit, InvalidConfigError from salt.config.schemas.esxi import EsxiProxySchema from salt.utils.dictupdate import merge # This must be present or the Salt loader won't load this module. __proxyenabled__ = ['esxi'] # External libraries try: import jsonschema HAS_JSONSCHEMA = True except ImportError: HAS_JSONSCHEMA = False # Variables are scoped to this module so we can have persistent data # across calls to fns in here. GRAINS_CACHE = {} DETAILS = {} # Set up logging log = logging.getLogger(__file__) # Define the module's virtual name __virtualname__ = 'esxi' def __virtual__(): ''' Only load if the ESXi execution module is available. ''' if HAS_JSONSCHEMA: return __virtualname__ return False, 'The ESXi Proxy Minion module did not load.' def grains(): ''' Get the grains from the proxy device. ''' if not GRAINS_CACHE: return _grains(DETAILS['host'], DETAILS['protocol'], DETAILS['port']) return GRAINS_CACHE def grains_refresh(): ''' Refresh the grains from the proxy device. ''' GRAINS_CACHE = {} return grains() def ping(): ''' Returns True if connection is to be done via a vCenter (no connection is attempted). Check to see if the host is responding when connecting directly via an ESXi host. CLI Example: .. code-block:: bash salt esxi-host test.ping ''' if DETAILS.get('esxi_host'): return True else: # TODO Check connection if mechanism is SSPI if DETAILS['mechanism'] == 'userpass': find_credentials(DETAILS['host']) try: __salt__['vsphere.system_info'](host=DETAILS['host'], username=DETAILS['username'], password=DETAILS['password']) except SaltSystemExit as err: log.warning(err) return False return True def shutdown(): ''' Shutdown the connection to the proxy device. For this proxy, shutdown is a no-op. ''' log.debug('ESXi proxy shutdown() called...') def ch_config(cmd, *args, **kwargs): ''' This function is called by the :mod:`salt.modules.esxi.cmd <salt.modules.esxi.cmd>` shim. It then calls whatever is passed in ``cmd`` inside the :mod:`salt.modules.vsphere <salt.modules.vsphere>` module. Passes the return through from the vsphere module. cmd The command to call inside salt.modules.vsphere args Arguments that need to be passed to that command. kwargs Keyword arguments that need to be passed to that command. ''' # Strip the __pub_ keys...is there a better way to do this? for k in kwargs: if k.startswith('__pub_'): kwargs.pop(k) kwargs['host'] = DETAILS['host'] kwargs['username'] = DETAILS['username'] kwargs['password'] = DETAILS['password'] kwargs['port'] = DETAILS['port'] kwargs['protocol'] = DETAILS['protocol'] kwargs['credstore'] = DETAILS['credstore'] if 'vsphere.' + cmd not in __salt__: return {'retcode': -1, 'message': 'vsphere.' + cmd + ' is not available.'} else: return __salt__['vsphere.' + cmd](*args, **kwargs) def find_credentials(host): ''' Cycle through all the possible credentials and return the first one that works. ''' user_names = [__pillar__['proxy'].get('username', 'root')] passwords = __pillar__['proxy']['passwords'] for user in user_names: for password in passwords: try: # Try to authenticate with the given user/password combination ret = __salt__['vsphere.system_info'](host=host, username=user, password=password) except SaltSystemExit: # If we can't authenticate, continue on to try the next password. continue # If we have data returned from above, we've successfully authenticated. if ret: DETAILS['username'] = user DETAILS['password'] = password return user, password # We've reached the end of the list without successfully authenticating. raise SaltSystemExit('Cannot complete login due to an incorrect user name or password.') def _grains(host, protocol=None, port=None): ''' Helper function to the grains from the proxied device. ''' username, password = find_credentials(DETAILS['host']) ret = __salt__['vsphere.system_info'](host=host, username=username, password=password, protocol=protocol, port=port) GRAINS_CACHE.update(ret) return GRAINS_CACHE def is_connected_via_vcenter(): return True if 'vcenter' in DETAILS else False def get_details(): ''' Return the proxy details ''' return DETAILS
saltstack/salt
salt/proxy/esxi.py
ping
python
def ping(): ''' Returns True if connection is to be done via a vCenter (no connection is attempted). Check to see if the host is responding when connecting directly via an ESXi host. CLI Example: .. code-block:: bash salt esxi-host test.ping ''' if DETAILS.get('esxi_host'): return True else: # TODO Check connection if mechanism is SSPI if DETAILS['mechanism'] == 'userpass': find_credentials(DETAILS['host']) try: __salt__['vsphere.system_info'](host=DETAILS['host'], username=DETAILS['username'], password=DETAILS['password']) except SaltSystemExit as err: log.warning(err) return False return True
Returns True if connection is to be done via a vCenter (no connection is attempted). Check to see if the host is responding when connecting directly via an ESXi host. CLI Example: .. code-block:: bash salt esxi-host test.ping
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/esxi.py#L436-L461
null
# -*- coding: utf-8 -*- ''' Proxy Minion interface module for managing VMware ESXi hosts. .. versionadded:: 2015.8.4 **Special Note: SaltStack thanks** `Adobe Corporation <http://adobe.com/>`_ **for their support in creating this Proxy Minion integration.** This proxy minion enables VMware ESXi (hereafter referred to as simply 'ESXi') hosts to be treated individually like a Salt Minion. Since the ESXi host may not necessarily run on an OS capable of hosting a Python stack, the ESXi host can't run a Salt Minion directly. Salt's "Proxy Minion" functionality enables you to designate another machine to host a minion process that "proxies" communication from the Salt Master. The master does not know nor care that the target is not a "real" Salt Minion. More in-depth conceptual reading on Proxy Minions can be found in the :ref:`Proxy Minion <proxy-minion>` section of Salt's documentation. Dependencies ============ - pyVmomi Python Module - ESXCLI pyVmomi ------- PyVmomi can be installed via pip: .. code-block:: bash pip install pyVmomi .. note:: Version 6.0 of pyVmomi has some problems with SSL error handling on certain versions of Python. If using version 6.0 of pyVmomi, Python 2.6, Python 2.7.9, or newer must be present. This is due to an upstream dependency in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the version of Python is not in the supported range, you will need to install an earlier version of pyVmomi. See `Issue #29537`_ for more information. .. _Issue #29537: https://github.com/saltstack/salt/issues/29537 Based on the note above, to install an earlier version of pyVmomi than the version currently listed in PyPi, run the following: .. code-block:: bash pip install pyVmomi==5.5.0.2014.1.1 The 5.5.0.2014.1.1 is a known stable version that this original ESXi State Module was developed against. ESXCLI ------ Currently, about a third of the functions used in the vSphere Execution Module require the ESXCLI package be installed on the machine running the Proxy Minion process. The ESXCLI package is also referred to as the VMware vSphere CLI, or vCLI. VMware provides vCLI package installation instructions for `vSphere 5.5`_ and `vSphere 6.0`_. .. _vSphere 5.5: http://pubs.vmware.com/vsphere-55/index.jsp#com.vmware.vcli.getstart.doc/cli_install.4.2.html .. _vSphere 6.0: http://pubs.vmware.com/vsphere-60/index.jsp#com.vmware.vcli.getstart.doc/cli_install.4.2.html Once all of the required dependencies are in place and the vCLI package is installed, you can check to see if you can connect to your ESXi host or vCenter server by running the following command: .. code-block:: bash esxcli -s <host-location> -u <username> -p <password> system syslog config get If the connection was successful, ESXCLI was successfully installed on your system. You should see output related to the ESXi host's syslog configuration. Configuration ============= To use this integration proxy module, please configure the following: Pillar ------ Proxy minions get their configuration from Salt's Pillar. Every proxy must have a stanza in Pillar and a reference in the Pillar top-file that matches the ID. At a minimum for communication with the ESXi host, the pillar should look like this: .. code-block:: yaml proxy: proxytype: esxi host: <ip or dns name of esxi host> username: <ESXi username> passwords: - first_password - second_password - third_password credstore: <path to credential store> proxytype ^^^^^^^^^ The ``proxytype`` key and value pair is critical, as it tells Salt which interface to load from the ``proxy`` directory in Salt's install hierarchy, or from ``/srv/salt/_proxy`` on the Salt Master (if you have created your own proxy module, for example). To use this ESXi Proxy Module, set this to ``esxi``. host ^^^^ The location, or ip/dns, of the ESXi host. Required. username ^^^^^^^^ The username used to login to the ESXi host, such as ``root``. Required. passwords ^^^^^^^^^ A list of passwords to be used to try and login to the ESXi host. At least one password in this list is required. The proxy integration will try the passwords listed in order. It is configured this way so you can have a regular password and the password you may be updating for an ESXi host either via the :mod:`vsphere.update_host_password <salt.modules.vsphere.update_host_password>` execution module function or via the :mod:`esxi.password_present <salt.states.esxi.password_present>` state function. This way, after the password is changed, you should not need to restart the proxy minion--it should just pick up the the new password provided in the list. You can then change pillar at will to move that password to the front and retire the unused ones. This also allows you to use any number of potential fallback passwords. .. note:: When a password is changed on the host to one in the list of possible passwords, the further down on the list the password is, the longer individual commands will take to return. This is due to the nature of pyVmomi's login system. We have to wait for the first attempt to fail before trying the next password on the list. This scenario is especially true, and even slower, when the proxy minion first starts. If the correct password is not the first password on the list, it may take up to a minute for ``test.ping`` to respond with a ``True`` result. Once the initial authorization is complete, the responses for commands will be a little faster. To avoid these longer waiting periods, SaltStack recommends moving the correct password to the top of the list and restarting the proxy minion at your earliest convenience. protocol ^^^^^^^^ If the ESXi host is not using the default protocol, set this value to an alternate protocol. Default is ``https``. port ^^^^ If the ESXi host is not using the default port, set this value to an alternate port. Default is ``443``. credstore ^^^^^^^^^ If the ESXi host is using an untrusted SSL certificate, set this value to the file path where the credential store is located. This file is passed to ``esxcli``. Default is ``<HOME>/.vmware/credstore/vicredentials.xml`` on Linux and ``<APPDATA>/VMware/credstore/vicredentials.xml`` on Windows. .. note:: ``HOME`` variable is sometimes not set for processes running as system services. If you want to rely on the default credential store location, make sure ``HOME`` is set for the proxy process. Salt Proxy ---------- After your pillar is in place, you can test the proxy. The proxy can run on any machine that has network connectivity to your Salt Master and to the ESXi host in question. SaltStack recommends that the machine running the salt-proxy process also run a regular minion, though it is not strictly necessary. On the machine that will run the proxy, make sure there is an ``/etc/salt/proxy`` file with at least the following in it: .. code-block:: yaml master: <ip or hostname of salt-master> You can then start the salt-proxy process with: .. code-block:: bash salt-proxy --proxyid <id you want to give the host> You may want to add ``-l debug`` to run the above in the foreground in debug mode just to make sure everything is OK. Next, accept the key for the proxy on your salt-master, just like you would for a regular minion: .. code-block:: bash salt-key -a <id you gave the esxi host> You can confirm that the pillar data is in place for the proxy: .. code-block:: bash salt <id> pillar.items And now you should be able to ping the ESXi host to make sure it is responding: .. code-block:: bash salt <id> test.ping At this point you can execute one-off commands against the host. For example, you can get the ESXi host's system information: .. code-block:: bash salt <id> esxi.cmd system_info Note that you don't need to provide credentials or an ip/hostname. Salt knows to use the credentials you stored in Pillar. It's important to understand how this particular proxy works. :mod:`Salt.modules.vsphere <salt.modules.vsphere>` is a standard Salt execution module. If you pull up the docs for it you'll see that almost every function in the module takes credentials and a target host. When credentials and a host aren't passed, Salt runs commands through ``pyVmomi`` against the local machine. If you wanted, you could run functions from this module on any host where an appropriate version of ``pyVmomi`` is installed, and that host would reach out over the network and communicate with the ESXi host. ``esxi.cmd`` acts as a "shim" between the execution module and the proxy. Its first parameter is always the function from salt.modules.vsphere. If the function takes more positional or keyword arguments you can append them to the call. It's this shim that speaks to the ESXi host through the proxy, arranging for the credentials and hostname to be pulled from the Pillar section for this Proxy Minion. Because of the presence of the shim, to lookup documentation for what functions you can use to interface with the ESXi host, you'll want to look in :mod:`salt.modules.vsphere <salt.modules.vsphere>` instead of :mod:`salt.modules.esxi <salt.modules.esxi>`. States ------ Associated states are thoroughly documented in :mod:`salt.states.esxi <salt.states.esxi>`. Look there to find an example structure for Pillar as well as an example ``.sls`` file for standing up an ESXi host from scratch. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os # Import Salt Libs from salt.exceptions import SaltSystemExit, InvalidConfigError from salt.config.schemas.esxi import EsxiProxySchema from salt.utils.dictupdate import merge # This must be present or the Salt loader won't load this module. __proxyenabled__ = ['esxi'] # External libraries try: import jsonschema HAS_JSONSCHEMA = True except ImportError: HAS_JSONSCHEMA = False # Variables are scoped to this module so we can have persistent data # across calls to fns in here. GRAINS_CACHE = {} DETAILS = {} # Set up logging log = logging.getLogger(__file__) # Define the module's virtual name __virtualname__ = 'esxi' def __virtual__(): ''' Only load if the ESXi execution module is available. ''' if HAS_JSONSCHEMA: return __virtualname__ return False, 'The ESXi Proxy Minion module did not load.' def init(opts): ''' This function gets called when the proxy starts up. For ESXi devices, the host, login credentials, and, if configured, the protocol and port are cached. ''' log.debug('Initting esxi proxy module in process %s', os.getpid()) log.debug('Validating esxi proxy input') schema = EsxiProxySchema.serialize() log.trace('esxi_proxy_schema = %s', schema) proxy_conf = merge(opts.get('proxy', {}), __pillar__.get('proxy', {})) log.trace('proxy_conf = %s', proxy_conf) try: jsonschema.validate(proxy_conf, schema) except jsonschema.exceptions.ValidationError as exc: raise InvalidConfigError(exc) DETAILS['proxytype'] = proxy_conf['proxytype'] if ('host' not in proxy_conf) and ('vcenter' not in proxy_conf): log.critical('Neither \'host\' nor \'vcenter\' keys found in pillar ' 'for this proxy.') return False if 'host' in proxy_conf: # We have started the proxy by connecting directly to the host if 'username' not in proxy_conf: log.critical('No \'username\' key found in pillar for this proxy.') return False if 'passwords' not in proxy_conf: log.critical('No \'passwords\' key found in pillar for this proxy.') return False host = proxy_conf['host'] # Get the correct login details try: username, password = find_credentials(host) except SaltSystemExit as err: log.critical('Error: %s', err) return False # Set configuration details DETAILS['host'] = host DETAILS['username'] = username DETAILS['password'] = password DETAILS['protocol'] = proxy_conf.get('protocol') DETAILS['port'] = proxy_conf.get('port') return True if 'vcenter' in proxy_conf: vcenter = proxy_conf['vcenter'] if not proxy_conf.get('esxi_host'): log.critical('No \'esxi_host\' key found in pillar for this proxy.') DETAILS['esxi_host'] = proxy_conf['esxi_host'] # We have started the proxy by connecting via the vCenter if 'mechanism' not in proxy_conf: log.critical('No \'mechanism\' key found in pillar for this proxy.') return False mechanism = proxy_conf['mechanism'] # Save mandatory fields in cache for key in ('vcenter', 'mechanism'): DETAILS[key] = proxy_conf[key] if mechanism == 'userpass': if 'username' not in proxy_conf: log.critical('No \'username\' key found in pillar for this ' 'proxy.') return False if 'passwords' not in proxy_conf and proxy_conf['passwords']: log.critical('Mechanism is set to \'userpass\' , but no ' '\'passwords\' key found in pillar for this ' 'proxy.') return False for key in ('username', 'passwords'): DETAILS[key] = proxy_conf[key] elif mechanism == 'sspi': if 'domain' not in proxy_conf: log.critical('Mechanism is set to \'sspi\' , but no ' '\'domain\' key found in pillar for this proxy.') return False if 'principal' not in proxy_conf: log.critical('Mechanism is set to \'sspi\' , but no ' '\'principal\' key found in pillar for this ' 'proxy.') return False for key in ('domain', 'principal'): DETAILS[key] = proxy_conf[key] if mechanism == 'userpass': # Get the correct login details log.debug('Retrieving credentials and testing vCenter connection' ' for mehchanism \'userpass\'') try: username, password = find_credentials(DETAILS['vcenter']) DETAILS['password'] = password except SaltSystemExit as err: log.critical('Error: %s', err) return False # Save optional DETAILS['protocol'] = proxy_conf.get('protocol', 'https') DETAILS['port'] = proxy_conf.get('port', '443') DETAILS['credstore'] = proxy_conf.get('credstore') def grains(): ''' Get the grains from the proxy device. ''' if not GRAINS_CACHE: return _grains(DETAILS['host'], DETAILS['protocol'], DETAILS['port']) return GRAINS_CACHE def grains_refresh(): ''' Refresh the grains from the proxy device. ''' GRAINS_CACHE = {} return grains() def shutdown(): ''' Shutdown the connection to the proxy device. For this proxy, shutdown is a no-op. ''' log.debug('ESXi proxy shutdown() called...') def ch_config(cmd, *args, **kwargs): ''' This function is called by the :mod:`salt.modules.esxi.cmd <salt.modules.esxi.cmd>` shim. It then calls whatever is passed in ``cmd`` inside the :mod:`salt.modules.vsphere <salt.modules.vsphere>` module. Passes the return through from the vsphere module. cmd The command to call inside salt.modules.vsphere args Arguments that need to be passed to that command. kwargs Keyword arguments that need to be passed to that command. ''' # Strip the __pub_ keys...is there a better way to do this? for k in kwargs: if k.startswith('__pub_'): kwargs.pop(k) kwargs['host'] = DETAILS['host'] kwargs['username'] = DETAILS['username'] kwargs['password'] = DETAILS['password'] kwargs['port'] = DETAILS['port'] kwargs['protocol'] = DETAILS['protocol'] kwargs['credstore'] = DETAILS['credstore'] if 'vsphere.' + cmd not in __salt__: return {'retcode': -1, 'message': 'vsphere.' + cmd + ' is not available.'} else: return __salt__['vsphere.' + cmd](*args, **kwargs) def find_credentials(host): ''' Cycle through all the possible credentials and return the first one that works. ''' user_names = [__pillar__['proxy'].get('username', 'root')] passwords = __pillar__['proxy']['passwords'] for user in user_names: for password in passwords: try: # Try to authenticate with the given user/password combination ret = __salt__['vsphere.system_info'](host=host, username=user, password=password) except SaltSystemExit: # If we can't authenticate, continue on to try the next password. continue # If we have data returned from above, we've successfully authenticated. if ret: DETAILS['username'] = user DETAILS['password'] = password return user, password # We've reached the end of the list without successfully authenticating. raise SaltSystemExit('Cannot complete login due to an incorrect user name or password.') def _grains(host, protocol=None, port=None): ''' Helper function to the grains from the proxied device. ''' username, password = find_credentials(DETAILS['host']) ret = __salt__['vsphere.system_info'](host=host, username=username, password=password, protocol=protocol, port=port) GRAINS_CACHE.update(ret) return GRAINS_CACHE def is_connected_via_vcenter(): return True if 'vcenter' in DETAILS else False def get_details(): ''' Return the proxy details ''' return DETAILS
saltstack/salt
salt/proxy/esxi.py
ch_config
python
def ch_config(cmd, *args, **kwargs): ''' This function is called by the :mod:`salt.modules.esxi.cmd <salt.modules.esxi.cmd>` shim. It then calls whatever is passed in ``cmd`` inside the :mod:`salt.modules.vsphere <salt.modules.vsphere>` module. Passes the return through from the vsphere module. cmd The command to call inside salt.modules.vsphere args Arguments that need to be passed to that command. kwargs Keyword arguments that need to be passed to that command. ''' # Strip the __pub_ keys...is there a better way to do this? for k in kwargs: if k.startswith('__pub_'): kwargs.pop(k) kwargs['host'] = DETAILS['host'] kwargs['username'] = DETAILS['username'] kwargs['password'] = DETAILS['password'] kwargs['port'] = DETAILS['port'] kwargs['protocol'] = DETAILS['protocol'] kwargs['credstore'] = DETAILS['credstore'] if 'vsphere.' + cmd not in __salt__: return {'retcode': -1, 'message': 'vsphere.' + cmd + ' is not available.'} else: return __salt__['vsphere.' + cmd](*args, **kwargs)
This function is called by the :mod:`salt.modules.esxi.cmd <salt.modules.esxi.cmd>` shim. It then calls whatever is passed in ``cmd`` inside the :mod:`salt.modules.vsphere <salt.modules.vsphere>` module. Passes the return through from the vsphere module. cmd The command to call inside salt.modules.vsphere args Arguments that need to be passed to that command. kwargs Keyword arguments that need to be passed to that command.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/esxi.py#L472-L505
null
# -*- coding: utf-8 -*- ''' Proxy Minion interface module for managing VMware ESXi hosts. .. versionadded:: 2015.8.4 **Special Note: SaltStack thanks** `Adobe Corporation <http://adobe.com/>`_ **for their support in creating this Proxy Minion integration.** This proxy minion enables VMware ESXi (hereafter referred to as simply 'ESXi') hosts to be treated individually like a Salt Minion. Since the ESXi host may not necessarily run on an OS capable of hosting a Python stack, the ESXi host can't run a Salt Minion directly. Salt's "Proxy Minion" functionality enables you to designate another machine to host a minion process that "proxies" communication from the Salt Master. The master does not know nor care that the target is not a "real" Salt Minion. More in-depth conceptual reading on Proxy Minions can be found in the :ref:`Proxy Minion <proxy-minion>` section of Salt's documentation. Dependencies ============ - pyVmomi Python Module - ESXCLI pyVmomi ------- PyVmomi can be installed via pip: .. code-block:: bash pip install pyVmomi .. note:: Version 6.0 of pyVmomi has some problems with SSL error handling on certain versions of Python. If using version 6.0 of pyVmomi, Python 2.6, Python 2.7.9, or newer must be present. This is due to an upstream dependency in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the version of Python is not in the supported range, you will need to install an earlier version of pyVmomi. See `Issue #29537`_ for more information. .. _Issue #29537: https://github.com/saltstack/salt/issues/29537 Based on the note above, to install an earlier version of pyVmomi than the version currently listed in PyPi, run the following: .. code-block:: bash pip install pyVmomi==5.5.0.2014.1.1 The 5.5.0.2014.1.1 is a known stable version that this original ESXi State Module was developed against. ESXCLI ------ Currently, about a third of the functions used in the vSphere Execution Module require the ESXCLI package be installed on the machine running the Proxy Minion process. The ESXCLI package is also referred to as the VMware vSphere CLI, or vCLI. VMware provides vCLI package installation instructions for `vSphere 5.5`_ and `vSphere 6.0`_. .. _vSphere 5.5: http://pubs.vmware.com/vsphere-55/index.jsp#com.vmware.vcli.getstart.doc/cli_install.4.2.html .. _vSphere 6.0: http://pubs.vmware.com/vsphere-60/index.jsp#com.vmware.vcli.getstart.doc/cli_install.4.2.html Once all of the required dependencies are in place and the vCLI package is installed, you can check to see if you can connect to your ESXi host or vCenter server by running the following command: .. code-block:: bash esxcli -s <host-location> -u <username> -p <password> system syslog config get If the connection was successful, ESXCLI was successfully installed on your system. You should see output related to the ESXi host's syslog configuration. Configuration ============= To use this integration proxy module, please configure the following: Pillar ------ Proxy minions get their configuration from Salt's Pillar. Every proxy must have a stanza in Pillar and a reference in the Pillar top-file that matches the ID. At a minimum for communication with the ESXi host, the pillar should look like this: .. code-block:: yaml proxy: proxytype: esxi host: <ip or dns name of esxi host> username: <ESXi username> passwords: - first_password - second_password - third_password credstore: <path to credential store> proxytype ^^^^^^^^^ The ``proxytype`` key and value pair is critical, as it tells Salt which interface to load from the ``proxy`` directory in Salt's install hierarchy, or from ``/srv/salt/_proxy`` on the Salt Master (if you have created your own proxy module, for example). To use this ESXi Proxy Module, set this to ``esxi``. host ^^^^ The location, or ip/dns, of the ESXi host. Required. username ^^^^^^^^ The username used to login to the ESXi host, such as ``root``. Required. passwords ^^^^^^^^^ A list of passwords to be used to try and login to the ESXi host. At least one password in this list is required. The proxy integration will try the passwords listed in order. It is configured this way so you can have a regular password and the password you may be updating for an ESXi host either via the :mod:`vsphere.update_host_password <salt.modules.vsphere.update_host_password>` execution module function or via the :mod:`esxi.password_present <salt.states.esxi.password_present>` state function. This way, after the password is changed, you should not need to restart the proxy minion--it should just pick up the the new password provided in the list. You can then change pillar at will to move that password to the front and retire the unused ones. This also allows you to use any number of potential fallback passwords. .. note:: When a password is changed on the host to one in the list of possible passwords, the further down on the list the password is, the longer individual commands will take to return. This is due to the nature of pyVmomi's login system. We have to wait for the first attempt to fail before trying the next password on the list. This scenario is especially true, and even slower, when the proxy minion first starts. If the correct password is not the first password on the list, it may take up to a minute for ``test.ping`` to respond with a ``True`` result. Once the initial authorization is complete, the responses for commands will be a little faster. To avoid these longer waiting periods, SaltStack recommends moving the correct password to the top of the list and restarting the proxy minion at your earliest convenience. protocol ^^^^^^^^ If the ESXi host is not using the default protocol, set this value to an alternate protocol. Default is ``https``. port ^^^^ If the ESXi host is not using the default port, set this value to an alternate port. Default is ``443``. credstore ^^^^^^^^^ If the ESXi host is using an untrusted SSL certificate, set this value to the file path where the credential store is located. This file is passed to ``esxcli``. Default is ``<HOME>/.vmware/credstore/vicredentials.xml`` on Linux and ``<APPDATA>/VMware/credstore/vicredentials.xml`` on Windows. .. note:: ``HOME`` variable is sometimes not set for processes running as system services. If you want to rely on the default credential store location, make sure ``HOME`` is set for the proxy process. Salt Proxy ---------- After your pillar is in place, you can test the proxy. The proxy can run on any machine that has network connectivity to your Salt Master and to the ESXi host in question. SaltStack recommends that the machine running the salt-proxy process also run a regular minion, though it is not strictly necessary. On the machine that will run the proxy, make sure there is an ``/etc/salt/proxy`` file with at least the following in it: .. code-block:: yaml master: <ip or hostname of salt-master> You can then start the salt-proxy process with: .. code-block:: bash salt-proxy --proxyid <id you want to give the host> You may want to add ``-l debug`` to run the above in the foreground in debug mode just to make sure everything is OK. Next, accept the key for the proxy on your salt-master, just like you would for a regular minion: .. code-block:: bash salt-key -a <id you gave the esxi host> You can confirm that the pillar data is in place for the proxy: .. code-block:: bash salt <id> pillar.items And now you should be able to ping the ESXi host to make sure it is responding: .. code-block:: bash salt <id> test.ping At this point you can execute one-off commands against the host. For example, you can get the ESXi host's system information: .. code-block:: bash salt <id> esxi.cmd system_info Note that you don't need to provide credentials or an ip/hostname. Salt knows to use the credentials you stored in Pillar. It's important to understand how this particular proxy works. :mod:`Salt.modules.vsphere <salt.modules.vsphere>` is a standard Salt execution module. If you pull up the docs for it you'll see that almost every function in the module takes credentials and a target host. When credentials and a host aren't passed, Salt runs commands through ``pyVmomi`` against the local machine. If you wanted, you could run functions from this module on any host where an appropriate version of ``pyVmomi`` is installed, and that host would reach out over the network and communicate with the ESXi host. ``esxi.cmd`` acts as a "shim" between the execution module and the proxy. Its first parameter is always the function from salt.modules.vsphere. If the function takes more positional or keyword arguments you can append them to the call. It's this shim that speaks to the ESXi host through the proxy, arranging for the credentials and hostname to be pulled from the Pillar section for this Proxy Minion. Because of the presence of the shim, to lookup documentation for what functions you can use to interface with the ESXi host, you'll want to look in :mod:`salt.modules.vsphere <salt.modules.vsphere>` instead of :mod:`salt.modules.esxi <salt.modules.esxi>`. States ------ Associated states are thoroughly documented in :mod:`salt.states.esxi <salt.states.esxi>`. Look there to find an example structure for Pillar as well as an example ``.sls`` file for standing up an ESXi host from scratch. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os # Import Salt Libs from salt.exceptions import SaltSystemExit, InvalidConfigError from salt.config.schemas.esxi import EsxiProxySchema from salt.utils.dictupdate import merge # This must be present or the Salt loader won't load this module. __proxyenabled__ = ['esxi'] # External libraries try: import jsonschema HAS_JSONSCHEMA = True except ImportError: HAS_JSONSCHEMA = False # Variables are scoped to this module so we can have persistent data # across calls to fns in here. GRAINS_CACHE = {} DETAILS = {} # Set up logging log = logging.getLogger(__file__) # Define the module's virtual name __virtualname__ = 'esxi' def __virtual__(): ''' Only load if the ESXi execution module is available. ''' if HAS_JSONSCHEMA: return __virtualname__ return False, 'The ESXi Proxy Minion module did not load.' def init(opts): ''' This function gets called when the proxy starts up. For ESXi devices, the host, login credentials, and, if configured, the protocol and port are cached. ''' log.debug('Initting esxi proxy module in process %s', os.getpid()) log.debug('Validating esxi proxy input') schema = EsxiProxySchema.serialize() log.trace('esxi_proxy_schema = %s', schema) proxy_conf = merge(opts.get('proxy', {}), __pillar__.get('proxy', {})) log.trace('proxy_conf = %s', proxy_conf) try: jsonschema.validate(proxy_conf, schema) except jsonschema.exceptions.ValidationError as exc: raise InvalidConfigError(exc) DETAILS['proxytype'] = proxy_conf['proxytype'] if ('host' not in proxy_conf) and ('vcenter' not in proxy_conf): log.critical('Neither \'host\' nor \'vcenter\' keys found in pillar ' 'for this proxy.') return False if 'host' in proxy_conf: # We have started the proxy by connecting directly to the host if 'username' not in proxy_conf: log.critical('No \'username\' key found in pillar for this proxy.') return False if 'passwords' not in proxy_conf: log.critical('No \'passwords\' key found in pillar for this proxy.') return False host = proxy_conf['host'] # Get the correct login details try: username, password = find_credentials(host) except SaltSystemExit as err: log.critical('Error: %s', err) return False # Set configuration details DETAILS['host'] = host DETAILS['username'] = username DETAILS['password'] = password DETAILS['protocol'] = proxy_conf.get('protocol') DETAILS['port'] = proxy_conf.get('port') return True if 'vcenter' in proxy_conf: vcenter = proxy_conf['vcenter'] if not proxy_conf.get('esxi_host'): log.critical('No \'esxi_host\' key found in pillar for this proxy.') DETAILS['esxi_host'] = proxy_conf['esxi_host'] # We have started the proxy by connecting via the vCenter if 'mechanism' not in proxy_conf: log.critical('No \'mechanism\' key found in pillar for this proxy.') return False mechanism = proxy_conf['mechanism'] # Save mandatory fields in cache for key in ('vcenter', 'mechanism'): DETAILS[key] = proxy_conf[key] if mechanism == 'userpass': if 'username' not in proxy_conf: log.critical('No \'username\' key found in pillar for this ' 'proxy.') return False if 'passwords' not in proxy_conf and proxy_conf['passwords']: log.critical('Mechanism is set to \'userpass\' , but no ' '\'passwords\' key found in pillar for this ' 'proxy.') return False for key in ('username', 'passwords'): DETAILS[key] = proxy_conf[key] elif mechanism == 'sspi': if 'domain' not in proxy_conf: log.critical('Mechanism is set to \'sspi\' , but no ' '\'domain\' key found in pillar for this proxy.') return False if 'principal' not in proxy_conf: log.critical('Mechanism is set to \'sspi\' , but no ' '\'principal\' key found in pillar for this ' 'proxy.') return False for key in ('domain', 'principal'): DETAILS[key] = proxy_conf[key] if mechanism == 'userpass': # Get the correct login details log.debug('Retrieving credentials and testing vCenter connection' ' for mehchanism \'userpass\'') try: username, password = find_credentials(DETAILS['vcenter']) DETAILS['password'] = password except SaltSystemExit as err: log.critical('Error: %s', err) return False # Save optional DETAILS['protocol'] = proxy_conf.get('protocol', 'https') DETAILS['port'] = proxy_conf.get('port', '443') DETAILS['credstore'] = proxy_conf.get('credstore') def grains(): ''' Get the grains from the proxy device. ''' if not GRAINS_CACHE: return _grains(DETAILS['host'], DETAILS['protocol'], DETAILS['port']) return GRAINS_CACHE def grains_refresh(): ''' Refresh the grains from the proxy device. ''' GRAINS_CACHE = {} return grains() def ping(): ''' Returns True if connection is to be done via a vCenter (no connection is attempted). Check to see if the host is responding when connecting directly via an ESXi host. CLI Example: .. code-block:: bash salt esxi-host test.ping ''' if DETAILS.get('esxi_host'): return True else: # TODO Check connection if mechanism is SSPI if DETAILS['mechanism'] == 'userpass': find_credentials(DETAILS['host']) try: __salt__['vsphere.system_info'](host=DETAILS['host'], username=DETAILS['username'], password=DETAILS['password']) except SaltSystemExit as err: log.warning(err) return False return True def shutdown(): ''' Shutdown the connection to the proxy device. For this proxy, shutdown is a no-op. ''' log.debug('ESXi proxy shutdown() called...') def find_credentials(host): ''' Cycle through all the possible credentials and return the first one that works. ''' user_names = [__pillar__['proxy'].get('username', 'root')] passwords = __pillar__['proxy']['passwords'] for user in user_names: for password in passwords: try: # Try to authenticate with the given user/password combination ret = __salt__['vsphere.system_info'](host=host, username=user, password=password) except SaltSystemExit: # If we can't authenticate, continue on to try the next password. continue # If we have data returned from above, we've successfully authenticated. if ret: DETAILS['username'] = user DETAILS['password'] = password return user, password # We've reached the end of the list without successfully authenticating. raise SaltSystemExit('Cannot complete login due to an incorrect user name or password.') def _grains(host, protocol=None, port=None): ''' Helper function to the grains from the proxied device. ''' username, password = find_credentials(DETAILS['host']) ret = __salt__['vsphere.system_info'](host=host, username=username, password=password, protocol=protocol, port=port) GRAINS_CACHE.update(ret) return GRAINS_CACHE def is_connected_via_vcenter(): return True if 'vcenter' in DETAILS else False def get_details(): ''' Return the proxy details ''' return DETAILS
saltstack/salt
salt/proxy/esxi.py
find_credentials
python
def find_credentials(host): ''' Cycle through all the possible credentials and return the first one that works. ''' user_names = [__pillar__['proxy'].get('username', 'root')] passwords = __pillar__['proxy']['passwords'] for user in user_names: for password in passwords: try: # Try to authenticate with the given user/password combination ret = __salt__['vsphere.system_info'](host=host, username=user, password=password) except SaltSystemExit: # If we can't authenticate, continue on to try the next password. continue # If we have data returned from above, we've successfully authenticated. if ret: DETAILS['username'] = user DETAILS['password'] = password return user, password # We've reached the end of the list without successfully authenticating. raise SaltSystemExit('Cannot complete login due to an incorrect user name or password.')
Cycle through all the possible credentials and return the first one that works.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/esxi.py#L508-L531
null
# -*- coding: utf-8 -*- ''' Proxy Minion interface module for managing VMware ESXi hosts. .. versionadded:: 2015.8.4 **Special Note: SaltStack thanks** `Adobe Corporation <http://adobe.com/>`_ **for their support in creating this Proxy Minion integration.** This proxy minion enables VMware ESXi (hereafter referred to as simply 'ESXi') hosts to be treated individually like a Salt Minion. Since the ESXi host may not necessarily run on an OS capable of hosting a Python stack, the ESXi host can't run a Salt Minion directly. Salt's "Proxy Minion" functionality enables you to designate another machine to host a minion process that "proxies" communication from the Salt Master. The master does not know nor care that the target is not a "real" Salt Minion. More in-depth conceptual reading on Proxy Minions can be found in the :ref:`Proxy Minion <proxy-minion>` section of Salt's documentation. Dependencies ============ - pyVmomi Python Module - ESXCLI pyVmomi ------- PyVmomi can be installed via pip: .. code-block:: bash pip install pyVmomi .. note:: Version 6.0 of pyVmomi has some problems with SSL error handling on certain versions of Python. If using version 6.0 of pyVmomi, Python 2.6, Python 2.7.9, or newer must be present. This is due to an upstream dependency in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the version of Python is not in the supported range, you will need to install an earlier version of pyVmomi. See `Issue #29537`_ for more information. .. _Issue #29537: https://github.com/saltstack/salt/issues/29537 Based on the note above, to install an earlier version of pyVmomi than the version currently listed in PyPi, run the following: .. code-block:: bash pip install pyVmomi==5.5.0.2014.1.1 The 5.5.0.2014.1.1 is a known stable version that this original ESXi State Module was developed against. ESXCLI ------ Currently, about a third of the functions used in the vSphere Execution Module require the ESXCLI package be installed on the machine running the Proxy Minion process. The ESXCLI package is also referred to as the VMware vSphere CLI, or vCLI. VMware provides vCLI package installation instructions for `vSphere 5.5`_ and `vSphere 6.0`_. .. _vSphere 5.5: http://pubs.vmware.com/vsphere-55/index.jsp#com.vmware.vcli.getstart.doc/cli_install.4.2.html .. _vSphere 6.0: http://pubs.vmware.com/vsphere-60/index.jsp#com.vmware.vcli.getstart.doc/cli_install.4.2.html Once all of the required dependencies are in place and the vCLI package is installed, you can check to see if you can connect to your ESXi host or vCenter server by running the following command: .. code-block:: bash esxcli -s <host-location> -u <username> -p <password> system syslog config get If the connection was successful, ESXCLI was successfully installed on your system. You should see output related to the ESXi host's syslog configuration. Configuration ============= To use this integration proxy module, please configure the following: Pillar ------ Proxy minions get their configuration from Salt's Pillar. Every proxy must have a stanza in Pillar and a reference in the Pillar top-file that matches the ID. At a minimum for communication with the ESXi host, the pillar should look like this: .. code-block:: yaml proxy: proxytype: esxi host: <ip or dns name of esxi host> username: <ESXi username> passwords: - first_password - second_password - third_password credstore: <path to credential store> proxytype ^^^^^^^^^ The ``proxytype`` key and value pair is critical, as it tells Salt which interface to load from the ``proxy`` directory in Salt's install hierarchy, or from ``/srv/salt/_proxy`` on the Salt Master (if you have created your own proxy module, for example). To use this ESXi Proxy Module, set this to ``esxi``. host ^^^^ The location, or ip/dns, of the ESXi host. Required. username ^^^^^^^^ The username used to login to the ESXi host, such as ``root``. Required. passwords ^^^^^^^^^ A list of passwords to be used to try and login to the ESXi host. At least one password in this list is required. The proxy integration will try the passwords listed in order. It is configured this way so you can have a regular password and the password you may be updating for an ESXi host either via the :mod:`vsphere.update_host_password <salt.modules.vsphere.update_host_password>` execution module function or via the :mod:`esxi.password_present <salt.states.esxi.password_present>` state function. This way, after the password is changed, you should not need to restart the proxy minion--it should just pick up the the new password provided in the list. You can then change pillar at will to move that password to the front and retire the unused ones. This also allows you to use any number of potential fallback passwords. .. note:: When a password is changed on the host to one in the list of possible passwords, the further down on the list the password is, the longer individual commands will take to return. This is due to the nature of pyVmomi's login system. We have to wait for the first attempt to fail before trying the next password on the list. This scenario is especially true, and even slower, when the proxy minion first starts. If the correct password is not the first password on the list, it may take up to a minute for ``test.ping`` to respond with a ``True`` result. Once the initial authorization is complete, the responses for commands will be a little faster. To avoid these longer waiting periods, SaltStack recommends moving the correct password to the top of the list and restarting the proxy minion at your earliest convenience. protocol ^^^^^^^^ If the ESXi host is not using the default protocol, set this value to an alternate protocol. Default is ``https``. port ^^^^ If the ESXi host is not using the default port, set this value to an alternate port. Default is ``443``. credstore ^^^^^^^^^ If the ESXi host is using an untrusted SSL certificate, set this value to the file path where the credential store is located. This file is passed to ``esxcli``. Default is ``<HOME>/.vmware/credstore/vicredentials.xml`` on Linux and ``<APPDATA>/VMware/credstore/vicredentials.xml`` on Windows. .. note:: ``HOME`` variable is sometimes not set for processes running as system services. If you want to rely on the default credential store location, make sure ``HOME`` is set for the proxy process. Salt Proxy ---------- After your pillar is in place, you can test the proxy. The proxy can run on any machine that has network connectivity to your Salt Master and to the ESXi host in question. SaltStack recommends that the machine running the salt-proxy process also run a regular minion, though it is not strictly necessary. On the machine that will run the proxy, make sure there is an ``/etc/salt/proxy`` file with at least the following in it: .. code-block:: yaml master: <ip or hostname of salt-master> You can then start the salt-proxy process with: .. code-block:: bash salt-proxy --proxyid <id you want to give the host> You may want to add ``-l debug`` to run the above in the foreground in debug mode just to make sure everything is OK. Next, accept the key for the proxy on your salt-master, just like you would for a regular minion: .. code-block:: bash salt-key -a <id you gave the esxi host> You can confirm that the pillar data is in place for the proxy: .. code-block:: bash salt <id> pillar.items And now you should be able to ping the ESXi host to make sure it is responding: .. code-block:: bash salt <id> test.ping At this point you can execute one-off commands against the host. For example, you can get the ESXi host's system information: .. code-block:: bash salt <id> esxi.cmd system_info Note that you don't need to provide credentials or an ip/hostname. Salt knows to use the credentials you stored in Pillar. It's important to understand how this particular proxy works. :mod:`Salt.modules.vsphere <salt.modules.vsphere>` is a standard Salt execution module. If you pull up the docs for it you'll see that almost every function in the module takes credentials and a target host. When credentials and a host aren't passed, Salt runs commands through ``pyVmomi`` against the local machine. If you wanted, you could run functions from this module on any host where an appropriate version of ``pyVmomi`` is installed, and that host would reach out over the network and communicate with the ESXi host. ``esxi.cmd`` acts as a "shim" between the execution module and the proxy. Its first parameter is always the function from salt.modules.vsphere. If the function takes more positional or keyword arguments you can append them to the call. It's this shim that speaks to the ESXi host through the proxy, arranging for the credentials and hostname to be pulled from the Pillar section for this Proxy Minion. Because of the presence of the shim, to lookup documentation for what functions you can use to interface with the ESXi host, you'll want to look in :mod:`salt.modules.vsphere <salt.modules.vsphere>` instead of :mod:`salt.modules.esxi <salt.modules.esxi>`. States ------ Associated states are thoroughly documented in :mod:`salt.states.esxi <salt.states.esxi>`. Look there to find an example structure for Pillar as well as an example ``.sls`` file for standing up an ESXi host from scratch. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os # Import Salt Libs from salt.exceptions import SaltSystemExit, InvalidConfigError from salt.config.schemas.esxi import EsxiProxySchema from salt.utils.dictupdate import merge # This must be present or the Salt loader won't load this module. __proxyenabled__ = ['esxi'] # External libraries try: import jsonschema HAS_JSONSCHEMA = True except ImportError: HAS_JSONSCHEMA = False # Variables are scoped to this module so we can have persistent data # across calls to fns in here. GRAINS_CACHE = {} DETAILS = {} # Set up logging log = logging.getLogger(__file__) # Define the module's virtual name __virtualname__ = 'esxi' def __virtual__(): ''' Only load if the ESXi execution module is available. ''' if HAS_JSONSCHEMA: return __virtualname__ return False, 'The ESXi Proxy Minion module did not load.' def init(opts): ''' This function gets called when the proxy starts up. For ESXi devices, the host, login credentials, and, if configured, the protocol and port are cached. ''' log.debug('Initting esxi proxy module in process %s', os.getpid()) log.debug('Validating esxi proxy input') schema = EsxiProxySchema.serialize() log.trace('esxi_proxy_schema = %s', schema) proxy_conf = merge(opts.get('proxy', {}), __pillar__.get('proxy', {})) log.trace('proxy_conf = %s', proxy_conf) try: jsonschema.validate(proxy_conf, schema) except jsonschema.exceptions.ValidationError as exc: raise InvalidConfigError(exc) DETAILS['proxytype'] = proxy_conf['proxytype'] if ('host' not in proxy_conf) and ('vcenter' not in proxy_conf): log.critical('Neither \'host\' nor \'vcenter\' keys found in pillar ' 'for this proxy.') return False if 'host' in proxy_conf: # We have started the proxy by connecting directly to the host if 'username' not in proxy_conf: log.critical('No \'username\' key found in pillar for this proxy.') return False if 'passwords' not in proxy_conf: log.critical('No \'passwords\' key found in pillar for this proxy.') return False host = proxy_conf['host'] # Get the correct login details try: username, password = find_credentials(host) except SaltSystemExit as err: log.critical('Error: %s', err) return False # Set configuration details DETAILS['host'] = host DETAILS['username'] = username DETAILS['password'] = password DETAILS['protocol'] = proxy_conf.get('protocol') DETAILS['port'] = proxy_conf.get('port') return True if 'vcenter' in proxy_conf: vcenter = proxy_conf['vcenter'] if not proxy_conf.get('esxi_host'): log.critical('No \'esxi_host\' key found in pillar for this proxy.') DETAILS['esxi_host'] = proxy_conf['esxi_host'] # We have started the proxy by connecting via the vCenter if 'mechanism' not in proxy_conf: log.critical('No \'mechanism\' key found in pillar for this proxy.') return False mechanism = proxy_conf['mechanism'] # Save mandatory fields in cache for key in ('vcenter', 'mechanism'): DETAILS[key] = proxy_conf[key] if mechanism == 'userpass': if 'username' not in proxy_conf: log.critical('No \'username\' key found in pillar for this ' 'proxy.') return False if 'passwords' not in proxy_conf and proxy_conf['passwords']: log.critical('Mechanism is set to \'userpass\' , but no ' '\'passwords\' key found in pillar for this ' 'proxy.') return False for key in ('username', 'passwords'): DETAILS[key] = proxy_conf[key] elif mechanism == 'sspi': if 'domain' not in proxy_conf: log.critical('Mechanism is set to \'sspi\' , but no ' '\'domain\' key found in pillar for this proxy.') return False if 'principal' not in proxy_conf: log.critical('Mechanism is set to \'sspi\' , but no ' '\'principal\' key found in pillar for this ' 'proxy.') return False for key in ('domain', 'principal'): DETAILS[key] = proxy_conf[key] if mechanism == 'userpass': # Get the correct login details log.debug('Retrieving credentials and testing vCenter connection' ' for mehchanism \'userpass\'') try: username, password = find_credentials(DETAILS['vcenter']) DETAILS['password'] = password except SaltSystemExit as err: log.critical('Error: %s', err) return False # Save optional DETAILS['protocol'] = proxy_conf.get('protocol', 'https') DETAILS['port'] = proxy_conf.get('port', '443') DETAILS['credstore'] = proxy_conf.get('credstore') def grains(): ''' Get the grains from the proxy device. ''' if not GRAINS_CACHE: return _grains(DETAILS['host'], DETAILS['protocol'], DETAILS['port']) return GRAINS_CACHE def grains_refresh(): ''' Refresh the grains from the proxy device. ''' GRAINS_CACHE = {} return grains() def ping(): ''' Returns True if connection is to be done via a vCenter (no connection is attempted). Check to see if the host is responding when connecting directly via an ESXi host. CLI Example: .. code-block:: bash salt esxi-host test.ping ''' if DETAILS.get('esxi_host'): return True else: # TODO Check connection if mechanism is SSPI if DETAILS['mechanism'] == 'userpass': find_credentials(DETAILS['host']) try: __salt__['vsphere.system_info'](host=DETAILS['host'], username=DETAILS['username'], password=DETAILS['password']) except SaltSystemExit as err: log.warning(err) return False return True def shutdown(): ''' Shutdown the connection to the proxy device. For this proxy, shutdown is a no-op. ''' log.debug('ESXi proxy shutdown() called...') def ch_config(cmd, *args, **kwargs): ''' This function is called by the :mod:`salt.modules.esxi.cmd <salt.modules.esxi.cmd>` shim. It then calls whatever is passed in ``cmd`` inside the :mod:`salt.modules.vsphere <salt.modules.vsphere>` module. Passes the return through from the vsphere module. cmd The command to call inside salt.modules.vsphere args Arguments that need to be passed to that command. kwargs Keyword arguments that need to be passed to that command. ''' # Strip the __pub_ keys...is there a better way to do this? for k in kwargs: if k.startswith('__pub_'): kwargs.pop(k) kwargs['host'] = DETAILS['host'] kwargs['username'] = DETAILS['username'] kwargs['password'] = DETAILS['password'] kwargs['port'] = DETAILS['port'] kwargs['protocol'] = DETAILS['protocol'] kwargs['credstore'] = DETAILS['credstore'] if 'vsphere.' + cmd not in __salt__: return {'retcode': -1, 'message': 'vsphere.' + cmd + ' is not available.'} else: return __salt__['vsphere.' + cmd](*args, **kwargs) def _grains(host, protocol=None, port=None): ''' Helper function to the grains from the proxied device. ''' username, password = find_credentials(DETAILS['host']) ret = __salt__['vsphere.system_info'](host=host, username=username, password=password, protocol=protocol, port=port) GRAINS_CACHE.update(ret) return GRAINS_CACHE def is_connected_via_vcenter(): return True if 'vcenter' in DETAILS else False def get_details(): ''' Return the proxy details ''' return DETAILS
saltstack/salt
salt/proxy/esxi.py
_grains
python
def _grains(host, protocol=None, port=None): ''' Helper function to the grains from the proxied device. ''' username, password = find_credentials(DETAILS['host']) ret = __salt__['vsphere.system_info'](host=host, username=username, password=password, protocol=protocol, port=port) GRAINS_CACHE.update(ret) return GRAINS_CACHE
Helper function to the grains from the proxied device.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/esxi.py#L534-L545
[ "def find_credentials(host):\n '''\n Cycle through all the possible credentials and return the first one that\n works.\n '''\n user_names = [__pillar__['proxy'].get('username', 'root')]\n passwords = __pillar__['proxy']['passwords']\n for user in user_names:\n for password in passwords:\n try:\n # Try to authenticate with the given user/password combination\n ret = __salt__['vsphere.system_info'](host=host,\n username=user,\n password=password)\n except SaltSystemExit:\n # If we can't authenticate, continue on to try the next password.\n continue\n # If we have data returned from above, we've successfully authenticated.\n if ret:\n DETAILS['username'] = user\n DETAILS['password'] = password\n return user, password\n # We've reached the end of the list without successfully authenticating.\n raise SaltSystemExit('Cannot complete login due to an incorrect user name or password.')\n" ]
# -*- coding: utf-8 -*- ''' Proxy Minion interface module for managing VMware ESXi hosts. .. versionadded:: 2015.8.4 **Special Note: SaltStack thanks** `Adobe Corporation <http://adobe.com/>`_ **for their support in creating this Proxy Minion integration.** This proxy minion enables VMware ESXi (hereafter referred to as simply 'ESXi') hosts to be treated individually like a Salt Minion. Since the ESXi host may not necessarily run on an OS capable of hosting a Python stack, the ESXi host can't run a Salt Minion directly. Salt's "Proxy Minion" functionality enables you to designate another machine to host a minion process that "proxies" communication from the Salt Master. The master does not know nor care that the target is not a "real" Salt Minion. More in-depth conceptual reading on Proxy Minions can be found in the :ref:`Proxy Minion <proxy-minion>` section of Salt's documentation. Dependencies ============ - pyVmomi Python Module - ESXCLI pyVmomi ------- PyVmomi can be installed via pip: .. code-block:: bash pip install pyVmomi .. note:: Version 6.0 of pyVmomi has some problems with SSL error handling on certain versions of Python. If using version 6.0 of pyVmomi, Python 2.6, Python 2.7.9, or newer must be present. This is due to an upstream dependency in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the version of Python is not in the supported range, you will need to install an earlier version of pyVmomi. See `Issue #29537`_ for more information. .. _Issue #29537: https://github.com/saltstack/salt/issues/29537 Based on the note above, to install an earlier version of pyVmomi than the version currently listed in PyPi, run the following: .. code-block:: bash pip install pyVmomi==5.5.0.2014.1.1 The 5.5.0.2014.1.1 is a known stable version that this original ESXi State Module was developed against. ESXCLI ------ Currently, about a third of the functions used in the vSphere Execution Module require the ESXCLI package be installed on the machine running the Proxy Minion process. The ESXCLI package is also referred to as the VMware vSphere CLI, or vCLI. VMware provides vCLI package installation instructions for `vSphere 5.5`_ and `vSphere 6.0`_. .. _vSphere 5.5: http://pubs.vmware.com/vsphere-55/index.jsp#com.vmware.vcli.getstart.doc/cli_install.4.2.html .. _vSphere 6.0: http://pubs.vmware.com/vsphere-60/index.jsp#com.vmware.vcli.getstart.doc/cli_install.4.2.html Once all of the required dependencies are in place and the vCLI package is installed, you can check to see if you can connect to your ESXi host or vCenter server by running the following command: .. code-block:: bash esxcli -s <host-location> -u <username> -p <password> system syslog config get If the connection was successful, ESXCLI was successfully installed on your system. You should see output related to the ESXi host's syslog configuration. Configuration ============= To use this integration proxy module, please configure the following: Pillar ------ Proxy minions get their configuration from Salt's Pillar. Every proxy must have a stanza in Pillar and a reference in the Pillar top-file that matches the ID. At a minimum for communication with the ESXi host, the pillar should look like this: .. code-block:: yaml proxy: proxytype: esxi host: <ip or dns name of esxi host> username: <ESXi username> passwords: - first_password - second_password - third_password credstore: <path to credential store> proxytype ^^^^^^^^^ The ``proxytype`` key and value pair is critical, as it tells Salt which interface to load from the ``proxy`` directory in Salt's install hierarchy, or from ``/srv/salt/_proxy`` on the Salt Master (if you have created your own proxy module, for example). To use this ESXi Proxy Module, set this to ``esxi``. host ^^^^ The location, or ip/dns, of the ESXi host. Required. username ^^^^^^^^ The username used to login to the ESXi host, such as ``root``. Required. passwords ^^^^^^^^^ A list of passwords to be used to try and login to the ESXi host. At least one password in this list is required. The proxy integration will try the passwords listed in order. It is configured this way so you can have a regular password and the password you may be updating for an ESXi host either via the :mod:`vsphere.update_host_password <salt.modules.vsphere.update_host_password>` execution module function or via the :mod:`esxi.password_present <salt.states.esxi.password_present>` state function. This way, after the password is changed, you should not need to restart the proxy minion--it should just pick up the the new password provided in the list. You can then change pillar at will to move that password to the front and retire the unused ones. This also allows you to use any number of potential fallback passwords. .. note:: When a password is changed on the host to one in the list of possible passwords, the further down on the list the password is, the longer individual commands will take to return. This is due to the nature of pyVmomi's login system. We have to wait for the first attempt to fail before trying the next password on the list. This scenario is especially true, and even slower, when the proxy minion first starts. If the correct password is not the first password on the list, it may take up to a minute for ``test.ping`` to respond with a ``True`` result. Once the initial authorization is complete, the responses for commands will be a little faster. To avoid these longer waiting periods, SaltStack recommends moving the correct password to the top of the list and restarting the proxy minion at your earliest convenience. protocol ^^^^^^^^ If the ESXi host is not using the default protocol, set this value to an alternate protocol. Default is ``https``. port ^^^^ If the ESXi host is not using the default port, set this value to an alternate port. Default is ``443``. credstore ^^^^^^^^^ If the ESXi host is using an untrusted SSL certificate, set this value to the file path where the credential store is located. This file is passed to ``esxcli``. Default is ``<HOME>/.vmware/credstore/vicredentials.xml`` on Linux and ``<APPDATA>/VMware/credstore/vicredentials.xml`` on Windows. .. note:: ``HOME`` variable is sometimes not set for processes running as system services. If you want to rely on the default credential store location, make sure ``HOME`` is set for the proxy process. Salt Proxy ---------- After your pillar is in place, you can test the proxy. The proxy can run on any machine that has network connectivity to your Salt Master and to the ESXi host in question. SaltStack recommends that the machine running the salt-proxy process also run a regular minion, though it is not strictly necessary. On the machine that will run the proxy, make sure there is an ``/etc/salt/proxy`` file with at least the following in it: .. code-block:: yaml master: <ip or hostname of salt-master> You can then start the salt-proxy process with: .. code-block:: bash salt-proxy --proxyid <id you want to give the host> You may want to add ``-l debug`` to run the above in the foreground in debug mode just to make sure everything is OK. Next, accept the key for the proxy on your salt-master, just like you would for a regular minion: .. code-block:: bash salt-key -a <id you gave the esxi host> You can confirm that the pillar data is in place for the proxy: .. code-block:: bash salt <id> pillar.items And now you should be able to ping the ESXi host to make sure it is responding: .. code-block:: bash salt <id> test.ping At this point you can execute one-off commands against the host. For example, you can get the ESXi host's system information: .. code-block:: bash salt <id> esxi.cmd system_info Note that you don't need to provide credentials or an ip/hostname. Salt knows to use the credentials you stored in Pillar. It's important to understand how this particular proxy works. :mod:`Salt.modules.vsphere <salt.modules.vsphere>` is a standard Salt execution module. If you pull up the docs for it you'll see that almost every function in the module takes credentials and a target host. When credentials and a host aren't passed, Salt runs commands through ``pyVmomi`` against the local machine. If you wanted, you could run functions from this module on any host where an appropriate version of ``pyVmomi`` is installed, and that host would reach out over the network and communicate with the ESXi host. ``esxi.cmd`` acts as a "shim" between the execution module and the proxy. Its first parameter is always the function from salt.modules.vsphere. If the function takes more positional or keyword arguments you can append them to the call. It's this shim that speaks to the ESXi host through the proxy, arranging for the credentials and hostname to be pulled from the Pillar section for this Proxy Minion. Because of the presence of the shim, to lookup documentation for what functions you can use to interface with the ESXi host, you'll want to look in :mod:`salt.modules.vsphere <salt.modules.vsphere>` instead of :mod:`salt.modules.esxi <salt.modules.esxi>`. States ------ Associated states are thoroughly documented in :mod:`salt.states.esxi <salt.states.esxi>`. Look there to find an example structure for Pillar as well as an example ``.sls`` file for standing up an ESXi host from scratch. ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os # Import Salt Libs from salt.exceptions import SaltSystemExit, InvalidConfigError from salt.config.schemas.esxi import EsxiProxySchema from salt.utils.dictupdate import merge # This must be present or the Salt loader won't load this module. __proxyenabled__ = ['esxi'] # External libraries try: import jsonschema HAS_JSONSCHEMA = True except ImportError: HAS_JSONSCHEMA = False # Variables are scoped to this module so we can have persistent data # across calls to fns in here. GRAINS_CACHE = {} DETAILS = {} # Set up logging log = logging.getLogger(__file__) # Define the module's virtual name __virtualname__ = 'esxi' def __virtual__(): ''' Only load if the ESXi execution module is available. ''' if HAS_JSONSCHEMA: return __virtualname__ return False, 'The ESXi Proxy Minion module did not load.' def init(opts): ''' This function gets called when the proxy starts up. For ESXi devices, the host, login credentials, and, if configured, the protocol and port are cached. ''' log.debug('Initting esxi proxy module in process %s', os.getpid()) log.debug('Validating esxi proxy input') schema = EsxiProxySchema.serialize() log.trace('esxi_proxy_schema = %s', schema) proxy_conf = merge(opts.get('proxy', {}), __pillar__.get('proxy', {})) log.trace('proxy_conf = %s', proxy_conf) try: jsonschema.validate(proxy_conf, schema) except jsonschema.exceptions.ValidationError as exc: raise InvalidConfigError(exc) DETAILS['proxytype'] = proxy_conf['proxytype'] if ('host' not in proxy_conf) and ('vcenter' not in proxy_conf): log.critical('Neither \'host\' nor \'vcenter\' keys found in pillar ' 'for this proxy.') return False if 'host' in proxy_conf: # We have started the proxy by connecting directly to the host if 'username' not in proxy_conf: log.critical('No \'username\' key found in pillar for this proxy.') return False if 'passwords' not in proxy_conf: log.critical('No \'passwords\' key found in pillar for this proxy.') return False host = proxy_conf['host'] # Get the correct login details try: username, password = find_credentials(host) except SaltSystemExit as err: log.critical('Error: %s', err) return False # Set configuration details DETAILS['host'] = host DETAILS['username'] = username DETAILS['password'] = password DETAILS['protocol'] = proxy_conf.get('protocol') DETAILS['port'] = proxy_conf.get('port') return True if 'vcenter' in proxy_conf: vcenter = proxy_conf['vcenter'] if not proxy_conf.get('esxi_host'): log.critical('No \'esxi_host\' key found in pillar for this proxy.') DETAILS['esxi_host'] = proxy_conf['esxi_host'] # We have started the proxy by connecting via the vCenter if 'mechanism' not in proxy_conf: log.critical('No \'mechanism\' key found in pillar for this proxy.') return False mechanism = proxy_conf['mechanism'] # Save mandatory fields in cache for key in ('vcenter', 'mechanism'): DETAILS[key] = proxy_conf[key] if mechanism == 'userpass': if 'username' not in proxy_conf: log.critical('No \'username\' key found in pillar for this ' 'proxy.') return False if 'passwords' not in proxy_conf and proxy_conf['passwords']: log.critical('Mechanism is set to \'userpass\' , but no ' '\'passwords\' key found in pillar for this ' 'proxy.') return False for key in ('username', 'passwords'): DETAILS[key] = proxy_conf[key] elif mechanism == 'sspi': if 'domain' not in proxy_conf: log.critical('Mechanism is set to \'sspi\' , but no ' '\'domain\' key found in pillar for this proxy.') return False if 'principal' not in proxy_conf: log.critical('Mechanism is set to \'sspi\' , but no ' '\'principal\' key found in pillar for this ' 'proxy.') return False for key in ('domain', 'principal'): DETAILS[key] = proxy_conf[key] if mechanism == 'userpass': # Get the correct login details log.debug('Retrieving credentials and testing vCenter connection' ' for mehchanism \'userpass\'') try: username, password = find_credentials(DETAILS['vcenter']) DETAILS['password'] = password except SaltSystemExit as err: log.critical('Error: %s', err) return False # Save optional DETAILS['protocol'] = proxy_conf.get('protocol', 'https') DETAILS['port'] = proxy_conf.get('port', '443') DETAILS['credstore'] = proxy_conf.get('credstore') def grains(): ''' Get the grains from the proxy device. ''' if not GRAINS_CACHE: return _grains(DETAILS['host'], DETAILS['protocol'], DETAILS['port']) return GRAINS_CACHE def grains_refresh(): ''' Refresh the grains from the proxy device. ''' GRAINS_CACHE = {} return grains() def ping(): ''' Returns True if connection is to be done via a vCenter (no connection is attempted). Check to see if the host is responding when connecting directly via an ESXi host. CLI Example: .. code-block:: bash salt esxi-host test.ping ''' if DETAILS.get('esxi_host'): return True else: # TODO Check connection if mechanism is SSPI if DETAILS['mechanism'] == 'userpass': find_credentials(DETAILS['host']) try: __salt__['vsphere.system_info'](host=DETAILS['host'], username=DETAILS['username'], password=DETAILS['password']) except SaltSystemExit as err: log.warning(err) return False return True def shutdown(): ''' Shutdown the connection to the proxy device. For this proxy, shutdown is a no-op. ''' log.debug('ESXi proxy shutdown() called...') def ch_config(cmd, *args, **kwargs): ''' This function is called by the :mod:`salt.modules.esxi.cmd <salt.modules.esxi.cmd>` shim. It then calls whatever is passed in ``cmd`` inside the :mod:`salt.modules.vsphere <salt.modules.vsphere>` module. Passes the return through from the vsphere module. cmd The command to call inside salt.modules.vsphere args Arguments that need to be passed to that command. kwargs Keyword arguments that need to be passed to that command. ''' # Strip the __pub_ keys...is there a better way to do this? for k in kwargs: if k.startswith('__pub_'): kwargs.pop(k) kwargs['host'] = DETAILS['host'] kwargs['username'] = DETAILS['username'] kwargs['password'] = DETAILS['password'] kwargs['port'] = DETAILS['port'] kwargs['protocol'] = DETAILS['protocol'] kwargs['credstore'] = DETAILS['credstore'] if 'vsphere.' + cmd not in __salt__: return {'retcode': -1, 'message': 'vsphere.' + cmd + ' is not available.'} else: return __salt__['vsphere.' + cmd](*args, **kwargs) def find_credentials(host): ''' Cycle through all the possible credentials and return the first one that works. ''' user_names = [__pillar__['proxy'].get('username', 'root')] passwords = __pillar__['proxy']['passwords'] for user in user_names: for password in passwords: try: # Try to authenticate with the given user/password combination ret = __salt__['vsphere.system_info'](host=host, username=user, password=password) except SaltSystemExit: # If we can't authenticate, continue on to try the next password. continue # If we have data returned from above, we've successfully authenticated. if ret: DETAILS['username'] = user DETAILS['password'] = password return user, password # We've reached the end of the list without successfully authenticating. raise SaltSystemExit('Cannot complete login due to an incorrect user name or password.') def is_connected_via_vcenter(): return True if 'vcenter' in DETAILS else False def get_details(): ''' Return the proxy details ''' return DETAILS
saltstack/salt
salt/modules/telegram.py
post_message
python
def post_message(message, chat_id=None, token=None): ''' Send a message to a Telegram chat. :param message: The message to send to the Telegram chat. :param chat_id: (optional) The Telegram chat id. :param token: (optional) The Telegram API token. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' telegram.post_message message="Hello Telegram!" ''' if not chat_id: chat_id = _get_chat_id() if not token: token = _get_token() if not message: log.error('message is a required option.') return _post_message(message=message, chat_id=chat_id, token=token)
Send a message to a Telegram chat. :param message: The message to send to the Telegram chat. :param chat_id: (optional) The Telegram chat id. :param token: (optional) The Telegram API token. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' telegram.post_message message="Hello Telegram!"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/telegram.py#L71-L97
[ "def _get_token():\n '''\n Retrieves and return the Telegram's configured token\n\n :return: String: the token string\n '''\n token = __salt__['config.get']('telegram:token') or \\\n __salt__['config.get']('telegram.token')\n if not token:\n raise SaltInvocationError('No Telegram token found')\n\n return token\n", "def _post_message(message, chat_id, token):\n '''\n Send a message to a Telegram chat.\n\n :param chat_id: The chat id.\n :param message: The message to send to the telegram chat.\n :param token: The Telegram API token.\n :return: Boolean if message was sent successfully.\n '''\n url = 'https://api.telegram.org/bot{0}/sendMessage'.format(token)\n\n parameters = dict()\n if chat_id:\n parameters['chat_id'] = chat_id\n if message:\n parameters['text'] = message\n\n try:\n response = requests.post(\n url,\n data=parameters\n )\n result = response.json()\n\n log.debug('Raw response of the telegram request is %s', response)\n\n except Exception:\n log.exception(\n 'Sending telegram api request failed'\n )\n return False\n\n # Check if the Telegram Bot API returned successfully.\n if not result.get('ok', False):\n log.debug(\n 'Sending telegram api request failed due to error %s (%s)',\n result.get('error_code'), result.get('description')\n )\n return False\n\n return True\n", "def _get_chat_id():\n '''\n Retrieves and return the Telegram's configured chat id\n\n :return: String: the chat id string\n '''\n chat_id = __salt__['config.get']('telegram:chat_id') or \\\n __salt__['config.get']('telegram.chat_id')\n if not chat_id:\n raise SaltInvocationError('No Telegram chat id found')\n\n return chat_id\n" ]
# -*- coding: utf-8 -*- ''' Module for sending messages via Telegram. :configuration: In order to send a message via the Telegram, certain configuration is required in /etc/salt/minion on the relevant minions or in the pillar. Some sample configs might look like:: telegram.chat_id: '123456789' telegram.token: '00000000:xxxxxxxxxxxxxxxxxxxxxxxx' ''' from __future__ import absolute_import # Import Python libs import logging from salt.exceptions import SaltInvocationError # Import 3rd-party libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False log = logging.getLogger(__name__) __virtualname__ = 'telegram' def __virtual__(): ''' Return virtual name of the module. :return: The virtual name of the module. ''' if not HAS_REQUESTS: return False return __virtualname__ def _get_chat_id(): ''' Retrieves and return the Telegram's configured chat id :return: String: the chat id string ''' chat_id = __salt__['config.get']('telegram:chat_id') or \ __salt__['config.get']('telegram.chat_id') if not chat_id: raise SaltInvocationError('No Telegram chat id found') return chat_id def _get_token(): ''' Retrieves and return the Telegram's configured token :return: String: the token string ''' token = __salt__['config.get']('telegram:token') or \ __salt__['config.get']('telegram.token') if not token: raise SaltInvocationError('No Telegram token found') return token def _post_message(message, chat_id, token): ''' Send a message to a Telegram chat. :param chat_id: The chat id. :param message: The message to send to the telegram chat. :param token: The Telegram API token. :return: Boolean if message was sent successfully. ''' url = 'https://api.telegram.org/bot{0}/sendMessage'.format(token) parameters = dict() if chat_id: parameters['chat_id'] = chat_id if message: parameters['text'] = message try: response = requests.post( url, data=parameters ) result = response.json() log.debug('Raw response of the telegram request is %s', response) except Exception: log.exception( 'Sending telegram api request failed' ) return False # Check if the Telegram Bot API returned successfully. if not result.get('ok', False): log.debug( 'Sending telegram api request failed due to error %s (%s)', result.get('error_code'), result.get('description') ) return False return True
saltstack/salt
salt/modules/telegram.py
_post_message
python
def _post_message(message, chat_id, token): ''' Send a message to a Telegram chat. :param chat_id: The chat id. :param message: The message to send to the telegram chat. :param token: The Telegram API token. :return: Boolean if message was sent successfully. ''' url = 'https://api.telegram.org/bot{0}/sendMessage'.format(token) parameters = dict() if chat_id: parameters['chat_id'] = chat_id if message: parameters['text'] = message try: response = requests.post( url, data=parameters ) result = response.json() log.debug('Raw response of the telegram request is %s', response) except Exception: log.exception( 'Sending telegram api request failed' ) return False # Check if the Telegram Bot API returned successfully. if not result.get('ok', False): log.debug( 'Sending telegram api request failed due to error %s (%s)', result.get('error_code'), result.get('description') ) return False return True
Send a message to a Telegram chat. :param chat_id: The chat id. :param message: The message to send to the telegram chat. :param token: The Telegram API token. :return: Boolean if message was sent successfully.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/telegram.py#L100-L140
null
# -*- coding: utf-8 -*- ''' Module for sending messages via Telegram. :configuration: In order to send a message via the Telegram, certain configuration is required in /etc/salt/minion on the relevant minions or in the pillar. Some sample configs might look like:: telegram.chat_id: '123456789' telegram.token: '00000000:xxxxxxxxxxxxxxxxxxxxxxxx' ''' from __future__ import absolute_import # Import Python libs import logging from salt.exceptions import SaltInvocationError # Import 3rd-party libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False log = logging.getLogger(__name__) __virtualname__ = 'telegram' def __virtual__(): ''' Return virtual name of the module. :return: The virtual name of the module. ''' if not HAS_REQUESTS: return False return __virtualname__ def _get_chat_id(): ''' Retrieves and return the Telegram's configured chat id :return: String: the chat id string ''' chat_id = __salt__['config.get']('telegram:chat_id') or \ __salt__['config.get']('telegram.chat_id') if not chat_id: raise SaltInvocationError('No Telegram chat id found') return chat_id def _get_token(): ''' Retrieves and return the Telegram's configured token :return: String: the token string ''' token = __salt__['config.get']('telegram:token') or \ __salt__['config.get']('telegram.token') if not token: raise SaltInvocationError('No Telegram token found') return token def post_message(message, chat_id=None, token=None): ''' Send a message to a Telegram chat. :param message: The message to send to the Telegram chat. :param chat_id: (optional) The Telegram chat id. :param token: (optional) The Telegram API token. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' telegram.post_message message="Hello Telegram!" ''' if not chat_id: chat_id = _get_chat_id() if not token: token = _get_token() if not message: log.error('message is a required option.') return _post_message(message=message, chat_id=chat_id, token=token)
saltstack/salt
salt/roster/ansible.py
targets
python
def targets(tgt, tgt_type='glob', **kwargs): ''' Return the targets from the ansible inventory_file Default: /etc/salt/roster ''' inventory = __runner__['salt.cmd']('cmd.run', 'ansible-inventory -i {0} --list'.format(get_roster_file(__opts__))) __context__['inventory'] = __utils__['json.loads'](__utils__['stringutils.to_str'](inventory)) if tgt_type == 'glob': hosts = [host for host in _get_hosts_from_group('all') if fnmatch.fnmatch(host, tgt)] elif tgt_type == 'nodegroup': hosts = _get_hosts_from_group(tgt) return {host: _get_hostvars(host) for host in hosts}
Return the targets from the ansible inventory_file Default: /etc/salt/roster
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/ansible.py#L115-L127
[ "def get_roster_file(options):\n '''\n Find respective roster file.\n\n :param options:\n :return:\n '''\n template = None\n # The __disable_custom_roster is always True if Salt SSH Client comes\n # from Salt API. In that case no way to define own 'roster_file', instead\n # this file needs to be chosen from already validated rosters\n # (see /etc/salt/master config).\n if options.get('__disable_custom_roster') and options.get('roster_file'):\n roster = options.get('roster_file').strip('/')\n for roster_location in options.get('rosters'):\n r_file = os.path.join(roster_location, roster)\n if os.path.isfile(r_file):\n template = r_file\n break\n del options['roster_file']\n\n if not template:\n if options.get('roster_file'):\n template = options.get('roster_file')\n elif 'config_dir' in options.get('__master_opts__', {}):\n template = os.path.join(options['__master_opts__']['config_dir'],\n 'roster')\n elif 'config_dir' in options:\n template = os.path.join(options['config_dir'], 'roster')\n else:\n template = os.path.join(salt.syspaths.CONFIG_DIR, 'roster')\n\n if not os.path.isfile(template):\n raise IOError('Roster file \"{0}\" not found'.format(template))\n\n if not os.access(template, os.R_OK):\n raise IOError('Access denied to roster \"{0}\"'.format(template))\n\n return template\n", "def _get_hosts_from_group(group):\n inventory = __context__['inventory']\n hosts = [host for host in inventory[group].get('hosts', [])]\n for child in inventory[group].get('children', []):\n hosts.extend(_get_hosts_from_group(child))\n return hosts\n" ]
# -*- coding: utf-8 -*- ''' Read in an Ansible inventory file or script Flat inventory files should be in the regular ansible inventory format. .. code-block:: ini [servers] salt.gtmanfred.com ansible_ssh_user=gtmanfred ansible_ssh_host=127.0.0.1 ansible_ssh_port=22 ansible_ssh_pass='password' [desktop] home ansible_ssh_user=gtmanfred ansible_ssh_host=12.34.56.78 ansible_ssh_port=23 ansible_ssh_pass='password' [computers:children] desktop servers [names:vars] http_port=80 then salt-ssh can be used to hit any of them .. code-block:: bash [~]# salt-ssh -N all test.ping salt.gtmanfred.com: True home: True [~]# salt-ssh -N desktop test.ping home: True [~]# salt-ssh -N computers test.ping salt.gtmanfred.com: True home: True [~]# salt-ssh salt.gtmanfred.com test.ping salt.gtmanfred.com: True There is also the option of specifying a dynamic inventory, and generating it on the fly .. code-block:: bash #!/bin/bash echo '{ "servers": [ "salt.gtmanfred.com" ], "desktop": [ "home" ], "computers": { "hosts": [], "children": [ "desktop", "servers" ] }, "_meta": { "hostvars": { "salt.gtmanfred.com": { "ansible_ssh_user": "gtmanfred", "ansible_ssh_host": "127.0.0.1", "ansible_sudo_pass": "password", "ansible_ssh_port": 22 }, "home": { "ansible_ssh_user": "gtmanfred", "ansible_ssh_host": "12.34.56.78", "ansible_sudo_pass": "password", "ansible_ssh_port": 23 } } } }' This is the format that an inventory script needs to output to work with ansible, and thus here. .. code-block:: bash [~]# salt-ssh --roster-file /etc/salt/hosts salt.gtmanfred.com test.ping salt.gtmanfred.com: True Any of the [groups] or direct hostnames will return. The 'all' is special, and returns everything. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import copy import fnmatch # Import Salt libs import salt.utils.path from salt.roster import get_roster_file CONVERSION = { 'ansible_ssh_host': 'host', 'ansible_ssh_port': 'port', 'ansible_ssh_user': 'user', 'ansible_ssh_pass': 'passwd', 'ansible_sudo_pass': 'sudo', 'ansible_ssh_private_key_file': 'priv' } __virtualname__ = 'ansible' def __virtual__(): return salt.utils.path.which('ansible-inventory') and __virtualname__, 'Install `ansible` to use inventory' def _get_hosts_from_group(group): inventory = __context__['inventory'] hosts = [host for host in inventory[group].get('hosts', [])] for child in inventory[group].get('children', []): hosts.extend(_get_hosts_from_group(child)) return hosts def _get_hostvars(host): hostvars = __context__['inventory']['_meta'].get('hostvars', {}).get(host, {}) ret = copy.deepcopy(__opts__.get('roster_defaults', {})) for value in CONVERSION: if value in hostvars: ret[CONVERSION[value]] = hostvars.pop(value) ret['minion_opts'] = hostvars if 'host' not in ret: ret['host'] = host return ret
saltstack/salt
salt/sdb/cache.py
set_
python
def set_(key, value, service=None, profile=None): # pylint: disable=W0613 ''' Set a key/value pair in the cache service ''' key, profile = _parse_key(key, profile) cache = salt.cache.Cache(__opts__) cache.store(profile['bank'], key, value) return get(key, service, profile)
Set a key/value pair in the cache service
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/cache.py#L66-L73
[ "def get(key, service=None, profile=None): # pylint: disable=W0613\n '''\n Get a value from the cache service\n '''\n key, profile = _parse_key(key, profile)\n cache = salt.cache.Cache(__opts__)\n return cache.fetch(profile['bank'], key=key)\n", "def _parse_key(key, profile):\n '''\n Parse out a key and update the opts with any override data\n '''\n comps = key.split('?')\n if len(comps) > 1:\n for item in comps[1].split('&'):\n newkey, newval = item.split('=')\n profile[newkey] = newval\n if 'cachedir' in profile:\n __opts__['cachedir'] = profile['cachedir']\n return comps[0], profile\n", "def store(self, bank, key, data):\n '''\n Store data using the specified module\n\n :param bank:\n The name of the location inside the cache which will hold the key\n and its associated data.\n\n :param key:\n The name of the key (or file inside a directory) which will hold\n the data. File extensions should not be provided, as they will be\n added by the driver itself.\n\n :param data:\n The data which will be stored in the cache. This data should be\n in a format which can be serialized by msgpack/json/yaml/etc.\n\n :raises SaltCacheError:\n Raises an exception if cache driver detected an error accessing data\n in the cache backend (auth, permissions, etc).\n '''\n fun = '{0}.store'.format(self.driver)\n return self.modules[fun](bank, key, data, **self._kwargs)\n" ]
# -*- coding: utf-8 -*- ''' cache Module :maintainer: SaltStack :maturity: New :platform: all .. versionadded:: 2017.7.0 This module provides access to Salt's cache subsystem. Like all sdb modules, the cache module requires a configuration profile to be configured in either the minion or master configuration file. This profile requires very little. In the example: .. code-block:: yaml mastercloudcache: driver: cache bank: cloud/active/ec2/my-ec2-conf/saltmaster cachedir: /var/cache/salt The ``driver`` refers to the cache module, ``bank`` refers to the cache bank that contains the data and ``cachedir`` (optional), if used, points to an alternate directory for cache data storage. .. code-block:: yaml master_ip: sdb://mastercloudcache/public_ips It is also possible to override both the ``bank`` and ``cachedir`` options inside the SDB URI: .. code-block:: yaml master_ip: sdb://mastercloudcache/public_ips?cachedir=/var/cache/salt For this reason, both the ``bank`` and the ``cachedir`` options can be omitted from the SDB profile. However, if the ``bank`` option is omitted, it must be specified in the URI: .. code-block:: yaml master_ip: sdb://mastercloudcache/public_ips?bank=cloud/active/ec2/my-ec2-conf/saltmaster ''' # import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.cache __func_alias__ = { 'set_': 'set' } __virtualname__ = 'cache' def __virtual__(): ''' Only load the module if keyring is installed ''' return __virtualname__ def get(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the cache service ''' key, profile = _parse_key(key, profile) cache = salt.cache.Cache(__opts__) return cache.fetch(profile['bank'], key=key) def delete(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the cache service ''' key, profile = _parse_key(key, profile) cache = salt.cache.Cache(__opts__) try: cache.flush(profile['bank'], key=key) return True except Exception: return False def _parse_key(key, profile): ''' Parse out a key and update the opts with any override data ''' comps = key.split('?') if len(comps) > 1: for item in comps[1].split('&'): newkey, newval = item.split('=') profile[newkey] = newval if 'cachedir' in profile: __opts__['cachedir'] = profile['cachedir'] return comps[0], profile
saltstack/salt
salt/sdb/cache.py
get
python
def get(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the cache service ''' key, profile = _parse_key(key, profile) cache = salt.cache.Cache(__opts__) return cache.fetch(profile['bank'], key=key)
Get a value from the cache service
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/cache.py#L76-L82
[ "def _parse_key(key, profile):\n '''\n Parse out a key and update the opts with any override data\n '''\n comps = key.split('?')\n if len(comps) > 1:\n for item in comps[1].split('&'):\n newkey, newval = item.split('=')\n profile[newkey] = newval\n if 'cachedir' in profile:\n __opts__['cachedir'] = profile['cachedir']\n return comps[0], profile\n", "def fetch(self, bank, key):\n '''\n Fetch data using the specified module\n\n :param bank:\n The name of the location inside the cache which will hold the key\n and its associated data.\n\n :param key:\n The name of the key (or file inside a directory) which will hold\n the data. File extensions should not be provided, as they will be\n added by the driver itself.\n\n :return:\n Return a python object fetched from the cache or an empty dict if\n the given path or key not found.\n\n :raises SaltCacheError:\n Raises an exception if cache driver detected an error accessing data\n in the cache backend (auth, permissions, etc).\n '''\n fun = '{0}.fetch'.format(self.driver)\n return self.modules[fun](bank, key, **self._kwargs)\n" ]
# -*- coding: utf-8 -*- ''' cache Module :maintainer: SaltStack :maturity: New :platform: all .. versionadded:: 2017.7.0 This module provides access to Salt's cache subsystem. Like all sdb modules, the cache module requires a configuration profile to be configured in either the minion or master configuration file. This profile requires very little. In the example: .. code-block:: yaml mastercloudcache: driver: cache bank: cloud/active/ec2/my-ec2-conf/saltmaster cachedir: /var/cache/salt The ``driver`` refers to the cache module, ``bank`` refers to the cache bank that contains the data and ``cachedir`` (optional), if used, points to an alternate directory for cache data storage. .. code-block:: yaml master_ip: sdb://mastercloudcache/public_ips It is also possible to override both the ``bank`` and ``cachedir`` options inside the SDB URI: .. code-block:: yaml master_ip: sdb://mastercloudcache/public_ips?cachedir=/var/cache/salt For this reason, both the ``bank`` and the ``cachedir`` options can be omitted from the SDB profile. However, if the ``bank`` option is omitted, it must be specified in the URI: .. code-block:: yaml master_ip: sdb://mastercloudcache/public_ips?bank=cloud/active/ec2/my-ec2-conf/saltmaster ''' # import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.cache __func_alias__ = { 'set_': 'set' } __virtualname__ = 'cache' def __virtual__(): ''' Only load the module if keyring is installed ''' return __virtualname__ def set_(key, value, service=None, profile=None): # pylint: disable=W0613 ''' Set a key/value pair in the cache service ''' key, profile = _parse_key(key, profile) cache = salt.cache.Cache(__opts__) cache.store(profile['bank'], key, value) return get(key, service, profile) def delete(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the cache service ''' key, profile = _parse_key(key, profile) cache = salt.cache.Cache(__opts__) try: cache.flush(profile['bank'], key=key) return True except Exception: return False def _parse_key(key, profile): ''' Parse out a key and update the opts with any override data ''' comps = key.split('?') if len(comps) > 1: for item in comps[1].split('&'): newkey, newval = item.split('=') profile[newkey] = newval if 'cachedir' in profile: __opts__['cachedir'] = profile['cachedir'] return comps[0], profile
saltstack/salt
salt/sdb/cache.py
delete
python
def delete(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the cache service ''' key, profile = _parse_key(key, profile) cache = salt.cache.Cache(__opts__) try: cache.flush(profile['bank'], key=key) return True except Exception: return False
Get a value from the cache service
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/cache.py#L85-L95
[ "def _parse_key(key, profile):\n '''\n Parse out a key and update the opts with any override data\n '''\n comps = key.split('?')\n if len(comps) > 1:\n for item in comps[1].split('&'):\n newkey, newval = item.split('=')\n profile[newkey] = newval\n if 'cachedir' in profile:\n __opts__['cachedir'] = profile['cachedir']\n return comps[0], profile\n", "def flush(self, bank, key=None):\n '''\n Remove the key from the cache bank with all the key content. If no key is specified remove\n the entire bank with all keys and sub-banks inside.\n\n :param bank:\n The name of the location inside the cache which will hold the key\n and its associated data.\n\n :param key:\n The name of the key (or file inside a directory) which will hold\n the data. File extensions should not be provided, as they will be\n added by the driver itself.\n\n :raises SaltCacheError:\n Raises an exception if cache driver detected an error accessing data\n in the cache backend (auth, permissions, etc).\n '''\n fun = '{0}.flush'.format(self.driver)\n return self.modules[fun](bank, key=key, **self._kwargs)\n" ]
# -*- coding: utf-8 -*- ''' cache Module :maintainer: SaltStack :maturity: New :platform: all .. versionadded:: 2017.7.0 This module provides access to Salt's cache subsystem. Like all sdb modules, the cache module requires a configuration profile to be configured in either the minion or master configuration file. This profile requires very little. In the example: .. code-block:: yaml mastercloudcache: driver: cache bank: cloud/active/ec2/my-ec2-conf/saltmaster cachedir: /var/cache/salt The ``driver`` refers to the cache module, ``bank`` refers to the cache bank that contains the data and ``cachedir`` (optional), if used, points to an alternate directory for cache data storage. .. code-block:: yaml master_ip: sdb://mastercloudcache/public_ips It is also possible to override both the ``bank`` and ``cachedir`` options inside the SDB URI: .. code-block:: yaml master_ip: sdb://mastercloudcache/public_ips?cachedir=/var/cache/salt For this reason, both the ``bank`` and the ``cachedir`` options can be omitted from the SDB profile. However, if the ``bank`` option is omitted, it must be specified in the URI: .. code-block:: yaml master_ip: sdb://mastercloudcache/public_ips?bank=cloud/active/ec2/my-ec2-conf/saltmaster ''' # import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.cache __func_alias__ = { 'set_': 'set' } __virtualname__ = 'cache' def __virtual__(): ''' Only load the module if keyring is installed ''' return __virtualname__ def set_(key, value, service=None, profile=None): # pylint: disable=W0613 ''' Set a key/value pair in the cache service ''' key, profile = _parse_key(key, profile) cache = salt.cache.Cache(__opts__) cache.store(profile['bank'], key, value) return get(key, service, profile) def get(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the cache service ''' key, profile = _parse_key(key, profile) cache = salt.cache.Cache(__opts__) return cache.fetch(profile['bank'], key=key) def _parse_key(key, profile): ''' Parse out a key and update the opts with any override data ''' comps = key.split('?') if len(comps) > 1: for item in comps[1].split('&'): newkey, newval = item.split('=') profile[newkey] = newval if 'cachedir' in profile: __opts__['cachedir'] = profile['cachedir'] return comps[0], profile
saltstack/salt
salt/sdb/cache.py
_parse_key
python
def _parse_key(key, profile): ''' Parse out a key and update the opts with any override data ''' comps = key.split('?') if len(comps) > 1: for item in comps[1].split('&'): newkey, newval = item.split('=') profile[newkey] = newval if 'cachedir' in profile: __opts__['cachedir'] = profile['cachedir'] return comps[0], profile
Parse out a key and update the opts with any override data
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/cache.py#L98-L109
null
# -*- coding: utf-8 -*- ''' cache Module :maintainer: SaltStack :maturity: New :platform: all .. versionadded:: 2017.7.0 This module provides access to Salt's cache subsystem. Like all sdb modules, the cache module requires a configuration profile to be configured in either the minion or master configuration file. This profile requires very little. In the example: .. code-block:: yaml mastercloudcache: driver: cache bank: cloud/active/ec2/my-ec2-conf/saltmaster cachedir: /var/cache/salt The ``driver`` refers to the cache module, ``bank`` refers to the cache bank that contains the data and ``cachedir`` (optional), if used, points to an alternate directory for cache data storage. .. code-block:: yaml master_ip: sdb://mastercloudcache/public_ips It is also possible to override both the ``bank`` and ``cachedir`` options inside the SDB URI: .. code-block:: yaml master_ip: sdb://mastercloudcache/public_ips?cachedir=/var/cache/salt For this reason, both the ``bank`` and the ``cachedir`` options can be omitted from the SDB profile. However, if the ``bank`` option is omitted, it must be specified in the URI: .. code-block:: yaml master_ip: sdb://mastercloudcache/public_ips?bank=cloud/active/ec2/my-ec2-conf/saltmaster ''' # import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.cache __func_alias__ = { 'set_': 'set' } __virtualname__ = 'cache' def __virtual__(): ''' Only load the module if keyring is installed ''' return __virtualname__ def set_(key, value, service=None, profile=None): # pylint: disable=W0613 ''' Set a key/value pair in the cache service ''' key, profile = _parse_key(key, profile) cache = salt.cache.Cache(__opts__) cache.store(profile['bank'], key, value) return get(key, service, profile) def get(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the cache service ''' key, profile = _parse_key(key, profile) cache = salt.cache.Cache(__opts__) return cache.fetch(profile['bank'], key=key) def delete(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the cache service ''' key, profile = _parse_key(key, profile) cache = salt.cache.Cache(__opts__) try: cache.flush(profile['bank'], key=key) return True except Exception: return False
saltstack/salt
salt/tokens/rediscluster.py
_redis_client
python
def _redis_client(opts): ''' Connect to the redis host and return a StrictRedisCluster client object. If connection fails then return None. ''' redis_host = opts.get("eauth_redis_host", "localhost") redis_port = opts.get("eauth_redis_port", 6379) try: return rediscluster.StrictRedisCluster(host=redis_host, port=redis_port, decode_responses=True) except rediscluster.exceptions.RedisClusterException as err: log.warning( 'Failed to connect to redis at %s:%s - %s', redis_host, redis_port, err ) return None
Connect to the redis host and return a StrictRedisCluster client object. If connection fails then return None.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tokens/rediscluster.py#L48-L62
null
# -*- coding: utf-8 -*- ''' Provide token storage in Redis cluster. To get started simply start a redis cluster and assign all hashslots to the connected nodes. Add the redis hostname and port to master configs as eauth_redis_host and eauth_redis_port. Default values for these configs are as follow: .. code-block:: yaml eauth_redis_host: localhost eauth_redis_port: 6379 :depends: - redis-py-cluster Python package ''' from __future__ import absolute_import, print_function, unicode_literals try: import rediscluster HAS_REDIS = True except ImportError: HAS_REDIS = False import os import logging import hashlib import salt.payload from salt.ext import six log = logging.getLogger(__name__) __virtualname__ = 'rediscluster' def __virtual__(): if not HAS_REDIS: return False, 'Could not use redis for tokens; '\ 'rediscluster python client is not installed.' return __virtualname__ def mk_token(opts, tdata): ''' Mint a new token using the config option hash_type and store tdata with 'token' attribute set to the token. This module uses the hash of random 512 bytes as a token. :param opts: Salt master config options :param tdata: Token data to be stored with 'token' attirbute of this dict set to the token. :returns: tdata with token if successful. Empty dict if failed. ''' redis_client = _redis_client(opts) if not redis_client: return {} hash_type = getattr(hashlib, opts.get('hash_type', 'md5')) tok = six.text_type(hash_type(os.urandom(512)).hexdigest()) try: while redis_client.get(tok) is not None: tok = six.text_type(hash_type(os.urandom(512)).hexdigest()) except Exception as err: log.warning( 'Authentication failure: cannot get token %s from redis: %s', tok, err ) return {} tdata['token'] = tok serial = salt.payload.Serial(opts) try: redis_client.set(tok, serial.dumps(tdata)) except Exception as err: log.warning( 'Authentication failure: cannot save token %s to redis: %s', tok, err ) return {} return tdata def get_token(opts, tok): ''' Fetch the token data from the store. :param opts: Salt master config options :param tok: Token value to get :returns: Token data if successful. Empty dict if failed. ''' redis_client = _redis_client(opts) if not redis_client: return {} serial = salt.payload.Serial(opts) try: tdata = serial.loads(redis_client.get(tok)) return tdata except Exception as err: log.warning( 'Authentication failure: cannot get token %s from redis: %s', tok, err ) return {} def rm_token(opts, tok): ''' Remove token from the store. :param opts: Salt master config options :param tok: Token to remove :returns: Empty dict if successful. None if failed. ''' redis_client = _redis_client(opts) if not redis_client: return try: redis_client.delete(tok) return {} except Exception as err: log.warning('Could not remove token %s: %s', tok, err) def list_tokens(opts): ''' List all tokens in the store. :param opts: Salt master config options :returns: List of dicts (token_data) ''' ret = [] redis_client = _redis_client(opts) if not redis_client: return [] serial = salt.payload.Serial(opts) try: return [k.decode('utf8') for k in redis_client.keys()] except Exception as err: log.warning('Failed to list keys: %s', err) return []
saltstack/salt
salt/tokens/rediscluster.py
mk_token
python
def mk_token(opts, tdata): ''' Mint a new token using the config option hash_type and store tdata with 'token' attribute set to the token. This module uses the hash of random 512 bytes as a token. :param opts: Salt master config options :param tdata: Token data to be stored with 'token' attirbute of this dict set to the token. :returns: tdata with token if successful. Empty dict if failed. ''' redis_client = _redis_client(opts) if not redis_client: return {} hash_type = getattr(hashlib, opts.get('hash_type', 'md5')) tok = six.text_type(hash_type(os.urandom(512)).hexdigest()) try: while redis_client.get(tok) is not None: tok = six.text_type(hash_type(os.urandom(512)).hexdigest()) except Exception as err: log.warning( 'Authentication failure: cannot get token %s from redis: %s', tok, err ) return {} tdata['token'] = tok serial = salt.payload.Serial(opts) try: redis_client.set(tok, serial.dumps(tdata)) except Exception as err: log.warning( 'Authentication failure: cannot save token %s to redis: %s', tok, err ) return {} return tdata
Mint a new token using the config option hash_type and store tdata with 'token' attribute set to the token. This module uses the hash of random 512 bytes as a token. :param opts: Salt master config options :param tdata: Token data to be stored with 'token' attirbute of this dict set to the token. :returns: tdata with token if successful. Empty dict if failed.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tokens/rediscluster.py#L65-L99
[ "def _redis_client(opts):\n '''\n Connect to the redis host and return a StrictRedisCluster client object.\n If connection fails then return None.\n '''\n redis_host = opts.get(\"eauth_redis_host\", \"localhost\")\n redis_port = opts.get(\"eauth_redis_port\", 6379)\n try:\n return rediscluster.StrictRedisCluster(host=redis_host, port=redis_port, decode_responses=True)\n except rediscluster.exceptions.RedisClusterException as err:\n log.warning(\n 'Failed to connect to redis at %s:%s - %s',\n redis_host, redis_port, err\n )\n return None\n", "def dumps(self, msg, use_bin_type=False):\n '''\n Run the correct dumps serialization format\n\n :param use_bin_type: Useful for Python 3 support. Tells msgpack to\n differentiate between 'str' and 'bytes' types\n by encoding them differently.\n Since this changes the wire protocol, this\n option should not be used outside of IPC.\n '''\n def ext_type_encoder(obj):\n if isinstance(obj, six.integer_types):\n # msgpack can't handle the very long Python longs for jids\n # Convert any very long longs to strings\n return six.text_type(obj)\n elif isinstance(obj, (datetime.datetime, datetime.date)):\n # msgpack doesn't support datetime.datetime and datetime.date datatypes.\n # So here we have converted these types to custom datatype\n # This is msgpack Extended types numbered 78\n return msgpack.ExtType(78, salt.utils.stringutils.to_bytes(\n obj.strftime('%Y%m%dT%H:%M:%S.%f')))\n # The same for immutable types\n elif isinstance(obj, immutabletypes.ImmutableDict):\n return dict(obj)\n elif isinstance(obj, immutabletypes.ImmutableList):\n return list(obj)\n elif isinstance(obj, (set, immutabletypes.ImmutableSet)):\n # msgpack can't handle set so translate it to tuple\n return tuple(obj)\n elif isinstance(obj, CaseInsensitiveDict):\n return dict(obj)\n # Nothing known exceptions found. Let msgpack raise it's own.\n return obj\n\n try:\n if msgpack.version >= (0, 4, 0):\n # msgpack only supports 'use_bin_type' starting in 0.4.0.\n # Due to this, if we don't need it, don't pass it at all so\n # that under Python 2 we can still work with older versions\n # of msgpack.\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n use_bin_type=use_bin_type,\n _msgpack_module=msgpack)\n else:\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n _msgpack_module=msgpack)\n except (OverflowError, msgpack.exceptions.PackValueError):\n # msgpack<=0.4.6 don't call ext encoder on very long integers raising the error instead.\n # Convert any very long longs to strings and call dumps again.\n def verylong_encoder(obj, context):\n # Make sure we catch recursion here.\n objid = id(obj)\n if objid in context:\n return '<Recursion on {} with id={}>'.format(type(obj).__name__, id(obj))\n context.add(objid)\n\n if isinstance(obj, dict):\n for key, value in six.iteritems(obj.copy()):\n obj[key] = verylong_encoder(value, context)\n return dict(obj)\n elif isinstance(obj, (list, tuple)):\n obj = list(obj)\n for idx, entry in enumerate(obj):\n obj[idx] = verylong_encoder(entry, context)\n return obj\n # A value of an Integer object is limited from -(2^63) upto (2^64)-1 by MessagePack\n # spec. Here we care only of JIDs that are positive integers.\n if isinstance(obj, six.integer_types) and obj >= pow(2, 64):\n return six.text_type(obj)\n else:\n return obj\n\n msg = verylong_encoder(msg, set())\n if msgpack.version >= (0, 4, 0):\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n use_bin_type=use_bin_type,\n _msgpack_module=msgpack)\n else:\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n _msgpack_module=msgpack)\n" ]
# -*- coding: utf-8 -*- ''' Provide token storage in Redis cluster. To get started simply start a redis cluster and assign all hashslots to the connected nodes. Add the redis hostname and port to master configs as eauth_redis_host and eauth_redis_port. Default values for these configs are as follow: .. code-block:: yaml eauth_redis_host: localhost eauth_redis_port: 6379 :depends: - redis-py-cluster Python package ''' from __future__ import absolute_import, print_function, unicode_literals try: import rediscluster HAS_REDIS = True except ImportError: HAS_REDIS = False import os import logging import hashlib import salt.payload from salt.ext import six log = logging.getLogger(__name__) __virtualname__ = 'rediscluster' def __virtual__(): if not HAS_REDIS: return False, 'Could not use redis for tokens; '\ 'rediscluster python client is not installed.' return __virtualname__ def _redis_client(opts): ''' Connect to the redis host and return a StrictRedisCluster client object. If connection fails then return None. ''' redis_host = opts.get("eauth_redis_host", "localhost") redis_port = opts.get("eauth_redis_port", 6379) try: return rediscluster.StrictRedisCluster(host=redis_host, port=redis_port, decode_responses=True) except rediscluster.exceptions.RedisClusterException as err: log.warning( 'Failed to connect to redis at %s:%s - %s', redis_host, redis_port, err ) return None def get_token(opts, tok): ''' Fetch the token data from the store. :param opts: Salt master config options :param tok: Token value to get :returns: Token data if successful. Empty dict if failed. ''' redis_client = _redis_client(opts) if not redis_client: return {} serial = salt.payload.Serial(opts) try: tdata = serial.loads(redis_client.get(tok)) return tdata except Exception as err: log.warning( 'Authentication failure: cannot get token %s from redis: %s', tok, err ) return {} def rm_token(opts, tok): ''' Remove token from the store. :param opts: Salt master config options :param tok: Token to remove :returns: Empty dict if successful. None if failed. ''' redis_client = _redis_client(opts) if not redis_client: return try: redis_client.delete(tok) return {} except Exception as err: log.warning('Could not remove token %s: %s', tok, err) def list_tokens(opts): ''' List all tokens in the store. :param opts: Salt master config options :returns: List of dicts (token_data) ''' ret = [] redis_client = _redis_client(opts) if not redis_client: return [] serial = salt.payload.Serial(opts) try: return [k.decode('utf8') for k in redis_client.keys()] except Exception as err: log.warning('Failed to list keys: %s', err) return []
saltstack/salt
salt/tokens/rediscluster.py
get_token
python
def get_token(opts, tok): ''' Fetch the token data from the store. :param opts: Salt master config options :param tok: Token value to get :returns: Token data if successful. Empty dict if failed. ''' redis_client = _redis_client(opts) if not redis_client: return {} serial = salt.payload.Serial(opts) try: tdata = serial.loads(redis_client.get(tok)) return tdata except Exception as err: log.warning( 'Authentication failure: cannot get token %s from redis: %s', tok, err ) return {}
Fetch the token data from the store. :param opts: Salt master config options :param tok: Token value to get :returns: Token data if successful. Empty dict if failed.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tokens/rediscluster.py#L102-L122
[ "def _redis_client(opts):\n '''\n Connect to the redis host and return a StrictRedisCluster client object.\n If connection fails then return None.\n '''\n redis_host = opts.get(\"eauth_redis_host\", \"localhost\")\n redis_port = opts.get(\"eauth_redis_port\", 6379)\n try:\n return rediscluster.StrictRedisCluster(host=redis_host, port=redis_port, decode_responses=True)\n except rediscluster.exceptions.RedisClusterException as err:\n log.warning(\n 'Failed to connect to redis at %s:%s - %s',\n redis_host, redis_port, err\n )\n return None\n", "def loads(self, msg, encoding=None, raw=False):\n '''\n Run the correct loads serialization format\n\n :param encoding: Useful for Python 3 support. If the msgpack data\n was encoded using \"use_bin_type=True\", this will\n differentiate between the 'bytes' type and the\n 'str' type by decoding contents with 'str' type\n to what the encoding was set as. Recommended\n encoding is 'utf-8' when using Python 3.\n If the msgpack data was not encoded using\n \"use_bin_type=True\", it will try to decode\n all 'bytes' and 'str' data (the distinction has\n been lost in this case) to what the encoding is\n set as. In this case, it will fail if any of\n the contents cannot be converted.\n '''\n try:\n def ext_type_decoder(code, data):\n if code == 78:\n data = salt.utils.stringutils.to_unicode(data)\n return datetime.datetime.strptime(data, '%Y%m%dT%H:%M:%S.%f')\n return data\n\n gc.disable() # performance optimization for msgpack\n if msgpack.version >= (0, 4, 0):\n # msgpack only supports 'encoding' starting in 0.4.0.\n # Due to this, if we don't need it, don't pass it at all so\n # that under Python 2 we can still work with older versions\n # of msgpack.\n try:\n ret = salt.utils.msgpack.loads(msg, use_list=True,\n ext_hook=ext_type_decoder,\n encoding=encoding,\n _msgpack_module=msgpack)\n except UnicodeDecodeError:\n # msg contains binary data\n ret = msgpack.loads(msg, use_list=True, ext_hook=ext_type_decoder)\n else:\n ret = salt.utils.msgpack.loads(msg, use_list=True,\n ext_hook=ext_type_decoder,\n _msgpack_module=msgpack)\n if six.PY3 and encoding is None and not raw:\n ret = salt.transport.frame.decode_embedded_strs(ret)\n except Exception as exc:\n log.critical(\n 'Could not deserialize msgpack message. This often happens '\n 'when trying to read a file not in binary mode. '\n 'To see message payload, enable debug logging and retry. '\n 'Exception: %s', exc\n )\n log.debug('Msgpack deserialization failure on message: %s', msg)\n gc.collect()\n raise\n finally:\n gc.enable()\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Provide token storage in Redis cluster. To get started simply start a redis cluster and assign all hashslots to the connected nodes. Add the redis hostname and port to master configs as eauth_redis_host and eauth_redis_port. Default values for these configs are as follow: .. code-block:: yaml eauth_redis_host: localhost eauth_redis_port: 6379 :depends: - redis-py-cluster Python package ''' from __future__ import absolute_import, print_function, unicode_literals try: import rediscluster HAS_REDIS = True except ImportError: HAS_REDIS = False import os import logging import hashlib import salt.payload from salt.ext import six log = logging.getLogger(__name__) __virtualname__ = 'rediscluster' def __virtual__(): if not HAS_REDIS: return False, 'Could not use redis for tokens; '\ 'rediscluster python client is not installed.' return __virtualname__ def _redis_client(opts): ''' Connect to the redis host and return a StrictRedisCluster client object. If connection fails then return None. ''' redis_host = opts.get("eauth_redis_host", "localhost") redis_port = opts.get("eauth_redis_port", 6379) try: return rediscluster.StrictRedisCluster(host=redis_host, port=redis_port, decode_responses=True) except rediscluster.exceptions.RedisClusterException as err: log.warning( 'Failed to connect to redis at %s:%s - %s', redis_host, redis_port, err ) return None def mk_token(opts, tdata): ''' Mint a new token using the config option hash_type and store tdata with 'token' attribute set to the token. This module uses the hash of random 512 bytes as a token. :param opts: Salt master config options :param tdata: Token data to be stored with 'token' attirbute of this dict set to the token. :returns: tdata with token if successful. Empty dict if failed. ''' redis_client = _redis_client(opts) if not redis_client: return {} hash_type = getattr(hashlib, opts.get('hash_type', 'md5')) tok = six.text_type(hash_type(os.urandom(512)).hexdigest()) try: while redis_client.get(tok) is not None: tok = six.text_type(hash_type(os.urandom(512)).hexdigest()) except Exception as err: log.warning( 'Authentication failure: cannot get token %s from redis: %s', tok, err ) return {} tdata['token'] = tok serial = salt.payload.Serial(opts) try: redis_client.set(tok, serial.dumps(tdata)) except Exception as err: log.warning( 'Authentication failure: cannot save token %s to redis: %s', tok, err ) return {} return tdata def rm_token(opts, tok): ''' Remove token from the store. :param opts: Salt master config options :param tok: Token to remove :returns: Empty dict if successful. None if failed. ''' redis_client = _redis_client(opts) if not redis_client: return try: redis_client.delete(tok) return {} except Exception as err: log.warning('Could not remove token %s: %s', tok, err) def list_tokens(opts): ''' List all tokens in the store. :param opts: Salt master config options :returns: List of dicts (token_data) ''' ret = [] redis_client = _redis_client(opts) if not redis_client: return [] serial = salt.payload.Serial(opts) try: return [k.decode('utf8') for k in redis_client.keys()] except Exception as err: log.warning('Failed to list keys: %s', err) return []
saltstack/salt
salt/tokens/rediscluster.py
rm_token
python
def rm_token(opts, tok): ''' Remove token from the store. :param opts: Salt master config options :param tok: Token to remove :returns: Empty dict if successful. None if failed. ''' redis_client = _redis_client(opts) if not redis_client: return try: redis_client.delete(tok) return {} except Exception as err: log.warning('Could not remove token %s: %s', tok, err)
Remove token from the store. :param opts: Salt master config options :param tok: Token to remove :returns: Empty dict if successful. None if failed.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tokens/rediscluster.py#L125-L140
[ "def _redis_client(opts):\n '''\n Connect to the redis host and return a StrictRedisCluster client object.\n If connection fails then return None.\n '''\n redis_host = opts.get(\"eauth_redis_host\", \"localhost\")\n redis_port = opts.get(\"eauth_redis_port\", 6379)\n try:\n return rediscluster.StrictRedisCluster(host=redis_host, port=redis_port, decode_responses=True)\n except rediscluster.exceptions.RedisClusterException as err:\n log.warning(\n 'Failed to connect to redis at %s:%s - %s',\n redis_host, redis_port, err\n )\n return None\n" ]
# -*- coding: utf-8 -*- ''' Provide token storage in Redis cluster. To get started simply start a redis cluster and assign all hashslots to the connected nodes. Add the redis hostname and port to master configs as eauth_redis_host and eauth_redis_port. Default values for these configs are as follow: .. code-block:: yaml eauth_redis_host: localhost eauth_redis_port: 6379 :depends: - redis-py-cluster Python package ''' from __future__ import absolute_import, print_function, unicode_literals try: import rediscluster HAS_REDIS = True except ImportError: HAS_REDIS = False import os import logging import hashlib import salt.payload from salt.ext import six log = logging.getLogger(__name__) __virtualname__ = 'rediscluster' def __virtual__(): if not HAS_REDIS: return False, 'Could not use redis for tokens; '\ 'rediscluster python client is not installed.' return __virtualname__ def _redis_client(opts): ''' Connect to the redis host and return a StrictRedisCluster client object. If connection fails then return None. ''' redis_host = opts.get("eauth_redis_host", "localhost") redis_port = opts.get("eauth_redis_port", 6379) try: return rediscluster.StrictRedisCluster(host=redis_host, port=redis_port, decode_responses=True) except rediscluster.exceptions.RedisClusterException as err: log.warning( 'Failed to connect to redis at %s:%s - %s', redis_host, redis_port, err ) return None def mk_token(opts, tdata): ''' Mint a new token using the config option hash_type and store tdata with 'token' attribute set to the token. This module uses the hash of random 512 bytes as a token. :param opts: Salt master config options :param tdata: Token data to be stored with 'token' attirbute of this dict set to the token. :returns: tdata with token if successful. Empty dict if failed. ''' redis_client = _redis_client(opts) if not redis_client: return {} hash_type = getattr(hashlib, opts.get('hash_type', 'md5')) tok = six.text_type(hash_type(os.urandom(512)).hexdigest()) try: while redis_client.get(tok) is not None: tok = six.text_type(hash_type(os.urandom(512)).hexdigest()) except Exception as err: log.warning( 'Authentication failure: cannot get token %s from redis: %s', tok, err ) return {} tdata['token'] = tok serial = salt.payload.Serial(opts) try: redis_client.set(tok, serial.dumps(tdata)) except Exception as err: log.warning( 'Authentication failure: cannot save token %s to redis: %s', tok, err ) return {} return tdata def get_token(opts, tok): ''' Fetch the token data from the store. :param opts: Salt master config options :param tok: Token value to get :returns: Token data if successful. Empty dict if failed. ''' redis_client = _redis_client(opts) if not redis_client: return {} serial = salt.payload.Serial(opts) try: tdata = serial.loads(redis_client.get(tok)) return tdata except Exception as err: log.warning( 'Authentication failure: cannot get token %s from redis: %s', tok, err ) return {} def list_tokens(opts): ''' List all tokens in the store. :param opts: Salt master config options :returns: List of dicts (token_data) ''' ret = [] redis_client = _redis_client(opts) if not redis_client: return [] serial = salt.payload.Serial(opts) try: return [k.decode('utf8') for k in redis_client.keys()] except Exception as err: log.warning('Failed to list keys: %s', err) return []
saltstack/salt
salt/tokens/rediscluster.py
list_tokens
python
def list_tokens(opts): ''' List all tokens in the store. :param opts: Salt master config options :returns: List of dicts (token_data) ''' ret = [] redis_client = _redis_client(opts) if not redis_client: return [] serial = salt.payload.Serial(opts) try: return [k.decode('utf8') for k in redis_client.keys()] except Exception as err: log.warning('Failed to list keys: %s', err) return []
List all tokens in the store. :param opts: Salt master config options :returns: List of dicts (token_data)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tokens/rediscluster.py#L143-L159
[ "def _redis_client(opts):\n '''\n Connect to the redis host and return a StrictRedisCluster client object.\n If connection fails then return None.\n '''\n redis_host = opts.get(\"eauth_redis_host\", \"localhost\")\n redis_port = opts.get(\"eauth_redis_port\", 6379)\n try:\n return rediscluster.StrictRedisCluster(host=redis_host, port=redis_port, decode_responses=True)\n except rediscluster.exceptions.RedisClusterException as err:\n log.warning(\n 'Failed to connect to redis at %s:%s - %s',\n redis_host, redis_port, err\n )\n return None\n" ]
# -*- coding: utf-8 -*- ''' Provide token storage in Redis cluster. To get started simply start a redis cluster and assign all hashslots to the connected nodes. Add the redis hostname and port to master configs as eauth_redis_host and eauth_redis_port. Default values for these configs are as follow: .. code-block:: yaml eauth_redis_host: localhost eauth_redis_port: 6379 :depends: - redis-py-cluster Python package ''' from __future__ import absolute_import, print_function, unicode_literals try: import rediscluster HAS_REDIS = True except ImportError: HAS_REDIS = False import os import logging import hashlib import salt.payload from salt.ext import six log = logging.getLogger(__name__) __virtualname__ = 'rediscluster' def __virtual__(): if not HAS_REDIS: return False, 'Could not use redis for tokens; '\ 'rediscluster python client is not installed.' return __virtualname__ def _redis_client(opts): ''' Connect to the redis host and return a StrictRedisCluster client object. If connection fails then return None. ''' redis_host = opts.get("eauth_redis_host", "localhost") redis_port = opts.get("eauth_redis_port", 6379) try: return rediscluster.StrictRedisCluster(host=redis_host, port=redis_port, decode_responses=True) except rediscluster.exceptions.RedisClusterException as err: log.warning( 'Failed to connect to redis at %s:%s - %s', redis_host, redis_port, err ) return None def mk_token(opts, tdata): ''' Mint a new token using the config option hash_type and store tdata with 'token' attribute set to the token. This module uses the hash of random 512 bytes as a token. :param opts: Salt master config options :param tdata: Token data to be stored with 'token' attirbute of this dict set to the token. :returns: tdata with token if successful. Empty dict if failed. ''' redis_client = _redis_client(opts) if not redis_client: return {} hash_type = getattr(hashlib, opts.get('hash_type', 'md5')) tok = six.text_type(hash_type(os.urandom(512)).hexdigest()) try: while redis_client.get(tok) is not None: tok = six.text_type(hash_type(os.urandom(512)).hexdigest()) except Exception as err: log.warning( 'Authentication failure: cannot get token %s from redis: %s', tok, err ) return {} tdata['token'] = tok serial = salt.payload.Serial(opts) try: redis_client.set(tok, serial.dumps(tdata)) except Exception as err: log.warning( 'Authentication failure: cannot save token %s to redis: %s', tok, err ) return {} return tdata def get_token(opts, tok): ''' Fetch the token data from the store. :param opts: Salt master config options :param tok: Token value to get :returns: Token data if successful. Empty dict if failed. ''' redis_client = _redis_client(opts) if not redis_client: return {} serial = salt.payload.Serial(opts) try: tdata = serial.loads(redis_client.get(tok)) return tdata except Exception as err: log.warning( 'Authentication failure: cannot get token %s from redis: %s', tok, err ) return {} def rm_token(opts, tok): ''' Remove token from the store. :param opts: Salt master config options :param tok: Token to remove :returns: Empty dict if successful. None if failed. ''' redis_client = _redis_client(opts) if not redis_client: return try: redis_client.delete(tok) return {} except Exception as err: log.warning('Could not remove token %s: %s', tok, err)
saltstack/salt
salt/states/wordpress.py
installed
python
def installed(name, user, admin_user, admin_password, admin_email, title, url): ''' Run the initial setup of wordpress name path to the wordpress installation user user that owns the files for the wordpress installation admin_user username for wordpress website administrator user admin_password password for wordpress website administrator user admin_email email for wordpress website administrator user title title for the wordpress website url url for the wordpress website .. code-block:: yaml /var/www/html: wordpress.installed: - title: Daniel's Awesome Blog - user: apache - admin_user: dwallace - admin_email: dwallace@example.com - admin_password: password123 - url: https://blog.dwallace.com ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} check = __salt__['wordpress.is_installed'](name, user) if check: ret['result'] = True ret['comment'] = 'Wordpress is already installed: {0}'.format(name) return ret elif __opts__['test']: ret['result'] = None ret['comment'] = 'Wordpress will be installed: {0}'.format(name) return ret resp = __salt__['wordpress.install'](name, user, admin_user, admin_password, admin_email, title, url) if resp: ret['result'] = True ret['comment'] = 'Wordpress Installed: {0}'.format(name) ret['changes'] = { 'new': resp } else: ret['comment'] = 'Failed to install wordpress: {0}'.format(name) return ret
Run the initial setup of wordpress name path to the wordpress installation user user that owns the files for the wordpress installation admin_user username for wordpress website administrator user admin_password password for wordpress website administrator user admin_email email for wordpress website administrator user title title for the wordpress website url url for the wordpress website .. code-block:: yaml /var/www/html: wordpress.installed: - title: Daniel's Awesome Blog - user: apache - admin_user: dwallace - admin_email: dwallace@example.com - admin_password: password123 - url: https://blog.dwallace.com
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/wordpress.py#L16-L78
null
# -*- coding: utf-8 -*- ''' This state module is used to manage Wordpress installations :depends: wp binary from http://wp-cli.org/ ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): return 'wordpress.show_plugin' in __salt__ def activated(name, path, user): ''' Activate wordpress plugins name name of plugin to activate path path to wordpress installation user user who should own the files in the wordpress installation .. code-block:: yaml HyperDB: wordpress.activated: - path: /var/www/html - user: apache ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} check = __salt__['wordpress.show_plugin'](name, path, user) if check['status'] == 'active': ret['result'] = True ret['comment'] = 'Plugin already activated: {0}'.format(name) return ret elif __opts__['test']: ret['result'] = None ret['comment'] = 'Plugin will be activated: {0}'.format(name) return ret resp = __salt__['wordpress.activate'](name, path, user) if resp is True: ret['result'] = True ret['comment'] = 'Plugin activated: {0}'.format(name) ret['changes'] = { 'old': check, 'new': __salt__['wordpress.show_plugin'](name, path, user) } elif resp is None: ret['result'] = True ret['comment'] = 'Plugin already activated: {0}'.format(name) ret['changes'] = { 'old': check, 'new': __salt__['wordpress.show_plugin'](name, path, user) } else: ret['comment'] = 'Plugin failed to activate: {0}'.format(name) return ret def deactivated(name, path, user): ''' Deactivate wordpress plugins name name of plugin to deactivate path path to wordpress installation user user who should own the files in the wordpress installation .. code-block:: yaml HyperDB: wordpress.deactivated: - path: /var/www/html - user: apache ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} check = __salt__['wordpress.show_plugin'](name, path, user) if check['status'] == 'inactive': ret['result'] = True ret['comment'] = 'Plugin already deactivated: {0}'.format(name) return ret elif __opts__['test']: ret['result'] = None ret['comment'] = 'Plugin will be deactivated: {0}'.format(name) return ret resp = __salt__['wordpress.deactivate'](name, path, user) if resp is True: ret['result'] = True ret['comment'] = 'Plugin deactivated: {0}'.format(name) ret['changes'] = { 'old': check, 'new': __salt__['wordpress.show_plugin'](name, path, user) } elif resp is None: ret['result'] = True ret['comment'] = 'Plugin already deactivated: {0}'.format(name) ret['changes'] = { 'old': check, 'new': __salt__['wordpress.show_plugin'](name, path, user) } else: ret['comment'] = 'Plugin failed to deactivate: {0}'.format(name) return ret
saltstack/salt
salt/states/wordpress.py
activated
python
def activated(name, path, user): ''' Activate wordpress plugins name name of plugin to activate path path to wordpress installation user user who should own the files in the wordpress installation .. code-block:: yaml HyperDB: wordpress.activated: - path: /var/www/html - user: apache ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} check = __salt__['wordpress.show_plugin'](name, path, user) if check['status'] == 'active': ret['result'] = True ret['comment'] = 'Plugin already activated: {0}'.format(name) return ret elif __opts__['test']: ret['result'] = None ret['comment'] = 'Plugin will be activated: {0}'.format(name) return ret resp = __salt__['wordpress.activate'](name, path, user) if resp is True: ret['result'] = True ret['comment'] = 'Plugin activated: {0}'.format(name) ret['changes'] = { 'old': check, 'new': __salt__['wordpress.show_plugin'](name, path, user) } elif resp is None: ret['result'] = True ret['comment'] = 'Plugin already activated: {0}'.format(name) ret['changes'] = { 'old': check, 'new': __salt__['wordpress.show_plugin'](name, path, user) } else: ret['comment'] = 'Plugin failed to activate: {0}'.format(name) return ret
Activate wordpress plugins name name of plugin to activate path path to wordpress installation user user who should own the files in the wordpress installation .. code-block:: yaml HyperDB: wordpress.activated: - path: /var/www/html - user: apache
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/wordpress.py#L81-L135
null
# -*- coding: utf-8 -*- ''' This state module is used to manage Wordpress installations :depends: wp binary from http://wp-cli.org/ ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): return 'wordpress.show_plugin' in __salt__ def installed(name, user, admin_user, admin_password, admin_email, title, url): ''' Run the initial setup of wordpress name path to the wordpress installation user user that owns the files for the wordpress installation admin_user username for wordpress website administrator user admin_password password for wordpress website administrator user admin_email email for wordpress website administrator user title title for the wordpress website url url for the wordpress website .. code-block:: yaml /var/www/html: wordpress.installed: - title: Daniel's Awesome Blog - user: apache - admin_user: dwallace - admin_email: dwallace@example.com - admin_password: password123 - url: https://blog.dwallace.com ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} check = __salt__['wordpress.is_installed'](name, user) if check: ret['result'] = True ret['comment'] = 'Wordpress is already installed: {0}'.format(name) return ret elif __opts__['test']: ret['result'] = None ret['comment'] = 'Wordpress will be installed: {0}'.format(name) return ret resp = __salt__['wordpress.install'](name, user, admin_user, admin_password, admin_email, title, url) if resp: ret['result'] = True ret['comment'] = 'Wordpress Installed: {0}'.format(name) ret['changes'] = { 'new': resp } else: ret['comment'] = 'Failed to install wordpress: {0}'.format(name) return ret def deactivated(name, path, user): ''' Deactivate wordpress plugins name name of plugin to deactivate path path to wordpress installation user user who should own the files in the wordpress installation .. code-block:: yaml HyperDB: wordpress.deactivated: - path: /var/www/html - user: apache ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} check = __salt__['wordpress.show_plugin'](name, path, user) if check['status'] == 'inactive': ret['result'] = True ret['comment'] = 'Plugin already deactivated: {0}'.format(name) return ret elif __opts__['test']: ret['result'] = None ret['comment'] = 'Plugin will be deactivated: {0}'.format(name) return ret resp = __salt__['wordpress.deactivate'](name, path, user) if resp is True: ret['result'] = True ret['comment'] = 'Plugin deactivated: {0}'.format(name) ret['changes'] = { 'old': check, 'new': __salt__['wordpress.show_plugin'](name, path, user) } elif resp is None: ret['result'] = True ret['comment'] = 'Plugin already deactivated: {0}'.format(name) ret['changes'] = { 'old': check, 'new': __salt__['wordpress.show_plugin'](name, path, user) } else: ret['comment'] = 'Plugin failed to deactivate: {0}'.format(name) return ret
saltstack/salt
salt/modules/scp_mod.py
_prepare_connection
python
def _prepare_connection(**kwargs): ''' Prepare the underlying SSH connection with the remote target. ''' paramiko_kwargs, scp_kwargs = _select_kwargs(**kwargs) ssh = paramiko.SSHClient() if paramiko_kwargs.pop('auto_add_policy', False): ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(**paramiko_kwargs) scp_client = scp.SCPClient(ssh.get_transport(), **scp_kwargs) return scp_client
Prepare the underlying SSH connection with the remote target.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/scp_mod.py#L55-L66
[ "def _select_kwargs(**kwargs):\n paramiko_kwargs = {}\n scp_kwargs = {}\n PARAMIKO_KWARGS, _, _, _ = inspect.getargspec(paramiko.SSHClient.connect)\n PARAMIKO_KWARGS.pop(0) # strip self\n PARAMIKO_KWARGS.append('auto_add_policy')\n SCP_KWARGS, _, _, _ = inspect.getargspec(scp.SCPClient.__init__)\n SCP_KWARGS.pop(0) # strip self\n SCP_KWARGS.pop(0) # strip transport arg (it is passed in _prepare_connection)\n for karg, warg in six.iteritems(kwargs):\n if karg in PARAMIKO_KWARGS and warg is not None:\n paramiko_kwargs[karg] = warg\n if karg in SCP_KWARGS and warg is not None:\n scp_kwargs[karg] = warg\n return paramiko_kwargs, scp_kwargs\n" ]
# -*- coding: utf-8 -*- ''' SCP Module ========== .. versionadded:: 2019.2.0 Module to copy files via `SCP <https://man.openbsd.org/scp>`_ ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import inspect # Import salt modules from salt.ext import six try: import scp import paramiko HAS_SCP = True except ImportError: HAS_SCP = False __proxyenabled__ = ['*'] __virtualname__ = 'scp' log = logging.getLogger(__name__) def __virtual__(): if not HAS_SCP: return False, 'Please install SCP for this modules: pip install scp' return __virtualname__ def _select_kwargs(**kwargs): paramiko_kwargs = {} scp_kwargs = {} PARAMIKO_KWARGS, _, _, _ = inspect.getargspec(paramiko.SSHClient.connect) PARAMIKO_KWARGS.pop(0) # strip self PARAMIKO_KWARGS.append('auto_add_policy') SCP_KWARGS, _, _, _ = inspect.getargspec(scp.SCPClient.__init__) SCP_KWARGS.pop(0) # strip self SCP_KWARGS.pop(0) # strip transport arg (it is passed in _prepare_connection) for karg, warg in six.iteritems(kwargs): if karg in PARAMIKO_KWARGS and warg is not None: paramiko_kwargs[karg] = warg if karg in SCP_KWARGS and warg is not None: scp_kwargs[karg] = warg return paramiko_kwargs, scp_kwargs def get(remote_path, local_path='', recursive=False, preserve_times=False, **kwargs): ''' Transfer files and directories from remote host to the localhost of the Minion. remote_path Path to retrieve from remote host. Since this is evaluated by scp on the remote host, shell wildcards and environment variables may be used. recursive: ``False`` Transfer files and directories recursively. preserve_times: ``False`` Preserve ``mtime`` and ``atime`` of transferred files and directories. hostname The hostname of the remote device. port: ``22`` The port of the remote device. username The username required for SSH authentication on the device. password Used for password authentication. It is also used for private key decryption if ``passphrase`` is not given. passphrase Used for decrypting private keys. pkey An optional private key to use for authentication. key_filename The filename, or list of filenames, of optional private key(s) and/or certificates to try for authentication. timeout An optional timeout (in seconds) for the TCP connect. socket_timeout: ``10`` The channel socket timeout in seconds. buff_size: ``16384`` The size of the SCP send buffer. allow_agent: ``True`` Set to ``False`` to disable connecting to the SSH agent. look_for_keys: ``True`` Set to ``False`` to disable searching for discoverable private key files in ``~/.ssh/`` banner_timeout An optional timeout (in seconds) to wait for the SSH banner to be presented. auth_timeout An optional timeout (in seconds) to wait for an authentication response. auto_add_policy: ``False`` Automatically add the host to the ``known_hosts``. CLI Example: .. code-block:: bash salt '*' scp.get /var/tmp/file /tmp/file hostname=10.10.10.1 auto_add_policy=True ''' scp_client = _prepare_connection(**kwargs) get_kwargs = { 'recursive': recursive, 'preserve_times': preserve_times } if local_path: get_kwargs['local_path'] = local_path return scp_client.get(remote_path, **get_kwargs) def put(files, remote_path=None, recursive=False, preserve_times=False, saltenv='base', **kwargs): ''' Transfer files and directories to remote host. files A single path or a list of paths to be transferred. remote_path The path on the remote device where to store the files. recursive: ``True`` Transfer files and directories recursively. preserve_times: ``False`` Preserve ``mtime`` and ``atime`` of transferred files and directories. hostname The hostname of the remote device. port: ``22`` The port of the remote device. username The username required for SSH authentication on the device. password Used for password authentication. It is also used for private key decryption if ``passphrase`` is not given. passphrase Used for decrypting private keys. pkey An optional private key to use for authentication. key_filename The filename, or list of filenames, of optional private key(s) and/or certificates to try for authentication. timeout An optional timeout (in seconds) for the TCP connect. socket_timeout: ``10`` The channel socket timeout in seconds. buff_size: ``16384`` The size of the SCP send buffer. allow_agent: ``True`` Set to ``False`` to disable connecting to the SSH agent. look_for_keys: ``True`` Set to ``False`` to disable searching for discoverable private key files in ``~/.ssh/`` banner_timeout An optional timeout (in seconds) to wait for the SSH banner to be presented. auth_timeout An optional timeout (in seconds) to wait for an authentication response. auto_add_policy: ``False`` Automatically add the host to the ``known_hosts``. CLI Example: .. code-block:: bash salt '*' scp.put /path/to/file /var/tmp/file hostname=server1 auto_add_policy=True ''' scp_client = _prepare_connection(**kwargs) put_kwargs = { 'recursive': recursive, 'preserve_times': preserve_times } if remote_path: put_kwargs['remote_path'] = remote_path cached_files = [] if not isinstance(files, (list, tuple)): files = [files] for file_ in files: cached_file = __salt__['cp.cache_file'](file_, saltenv=saltenv) cached_files.append(cached_file) return scp_client.put(cached_files, **put_kwargs)
saltstack/salt
salt/modules/scp_mod.py
get
python
def get(remote_path, local_path='', recursive=False, preserve_times=False, **kwargs): ''' Transfer files and directories from remote host to the localhost of the Minion. remote_path Path to retrieve from remote host. Since this is evaluated by scp on the remote host, shell wildcards and environment variables may be used. recursive: ``False`` Transfer files and directories recursively. preserve_times: ``False`` Preserve ``mtime`` and ``atime`` of transferred files and directories. hostname The hostname of the remote device. port: ``22`` The port of the remote device. username The username required for SSH authentication on the device. password Used for password authentication. It is also used for private key decryption if ``passphrase`` is not given. passphrase Used for decrypting private keys. pkey An optional private key to use for authentication. key_filename The filename, or list of filenames, of optional private key(s) and/or certificates to try for authentication. timeout An optional timeout (in seconds) for the TCP connect. socket_timeout: ``10`` The channel socket timeout in seconds. buff_size: ``16384`` The size of the SCP send buffer. allow_agent: ``True`` Set to ``False`` to disable connecting to the SSH agent. look_for_keys: ``True`` Set to ``False`` to disable searching for discoverable private key files in ``~/.ssh/`` banner_timeout An optional timeout (in seconds) to wait for the SSH banner to be presented. auth_timeout An optional timeout (in seconds) to wait for an authentication response. auto_add_policy: ``False`` Automatically add the host to the ``known_hosts``. CLI Example: .. code-block:: bash salt '*' scp.get /var/tmp/file /tmp/file hostname=10.10.10.1 auto_add_policy=True ''' scp_client = _prepare_connection(**kwargs) get_kwargs = { 'recursive': recursive, 'preserve_times': preserve_times } if local_path: get_kwargs['local_path'] = local_path return scp_client.get(remote_path, **get_kwargs)
Transfer files and directories from remote host to the localhost of the Minion. remote_path Path to retrieve from remote host. Since this is evaluated by scp on the remote host, shell wildcards and environment variables may be used. recursive: ``False`` Transfer files and directories recursively. preserve_times: ``False`` Preserve ``mtime`` and ``atime`` of transferred files and directories. hostname The hostname of the remote device. port: ``22`` The port of the remote device. username The username required for SSH authentication on the device. password Used for password authentication. It is also used for private key decryption if ``passphrase`` is not given. passphrase Used for decrypting private keys. pkey An optional private key to use for authentication. key_filename The filename, or list of filenames, of optional private key(s) and/or certificates to try for authentication. timeout An optional timeout (in seconds) for the TCP connect. socket_timeout: ``10`` The channel socket timeout in seconds. buff_size: ``16384`` The size of the SCP send buffer. allow_agent: ``True`` Set to ``False`` to disable connecting to the SSH agent. look_for_keys: ``True`` Set to ``False`` to disable searching for discoverable private key files in ``~/.ssh/`` banner_timeout An optional timeout (in seconds) to wait for the SSH banner to be presented. auth_timeout An optional timeout (in seconds) to wait for an authentication response. auto_add_policy: ``False`` Automatically add the host to the ``known_hosts``. CLI Example: .. code-block:: bash salt '*' scp.get /var/tmp/file /tmp/file hostname=10.10.10.1 auto_add_policy=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/scp_mod.py#L69-L151
[ "def _prepare_connection(**kwargs):\n '''\n Prepare the underlying SSH connection with the remote target.\n '''\n paramiko_kwargs, scp_kwargs = _select_kwargs(**kwargs)\n ssh = paramiko.SSHClient()\n if paramiko_kwargs.pop('auto_add_policy', False):\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n ssh.connect(**paramiko_kwargs)\n scp_client = scp.SCPClient(ssh.get_transport(),\n **scp_kwargs)\n return scp_client\n" ]
# -*- coding: utf-8 -*- ''' SCP Module ========== .. versionadded:: 2019.2.0 Module to copy files via `SCP <https://man.openbsd.org/scp>`_ ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import inspect # Import salt modules from salt.ext import six try: import scp import paramiko HAS_SCP = True except ImportError: HAS_SCP = False __proxyenabled__ = ['*'] __virtualname__ = 'scp' log = logging.getLogger(__name__) def __virtual__(): if not HAS_SCP: return False, 'Please install SCP for this modules: pip install scp' return __virtualname__ def _select_kwargs(**kwargs): paramiko_kwargs = {} scp_kwargs = {} PARAMIKO_KWARGS, _, _, _ = inspect.getargspec(paramiko.SSHClient.connect) PARAMIKO_KWARGS.pop(0) # strip self PARAMIKO_KWARGS.append('auto_add_policy') SCP_KWARGS, _, _, _ = inspect.getargspec(scp.SCPClient.__init__) SCP_KWARGS.pop(0) # strip self SCP_KWARGS.pop(0) # strip transport arg (it is passed in _prepare_connection) for karg, warg in six.iteritems(kwargs): if karg in PARAMIKO_KWARGS and warg is not None: paramiko_kwargs[karg] = warg if karg in SCP_KWARGS and warg is not None: scp_kwargs[karg] = warg return paramiko_kwargs, scp_kwargs def _prepare_connection(**kwargs): ''' Prepare the underlying SSH connection with the remote target. ''' paramiko_kwargs, scp_kwargs = _select_kwargs(**kwargs) ssh = paramiko.SSHClient() if paramiko_kwargs.pop('auto_add_policy', False): ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(**paramiko_kwargs) scp_client = scp.SCPClient(ssh.get_transport(), **scp_kwargs) return scp_client def put(files, remote_path=None, recursive=False, preserve_times=False, saltenv='base', **kwargs): ''' Transfer files and directories to remote host. files A single path or a list of paths to be transferred. remote_path The path on the remote device where to store the files. recursive: ``True`` Transfer files and directories recursively. preserve_times: ``False`` Preserve ``mtime`` and ``atime`` of transferred files and directories. hostname The hostname of the remote device. port: ``22`` The port of the remote device. username The username required for SSH authentication on the device. password Used for password authentication. It is also used for private key decryption if ``passphrase`` is not given. passphrase Used for decrypting private keys. pkey An optional private key to use for authentication. key_filename The filename, or list of filenames, of optional private key(s) and/or certificates to try for authentication. timeout An optional timeout (in seconds) for the TCP connect. socket_timeout: ``10`` The channel socket timeout in seconds. buff_size: ``16384`` The size of the SCP send buffer. allow_agent: ``True`` Set to ``False`` to disable connecting to the SSH agent. look_for_keys: ``True`` Set to ``False`` to disable searching for discoverable private key files in ``~/.ssh/`` banner_timeout An optional timeout (in seconds) to wait for the SSH banner to be presented. auth_timeout An optional timeout (in seconds) to wait for an authentication response. auto_add_policy: ``False`` Automatically add the host to the ``known_hosts``. CLI Example: .. code-block:: bash salt '*' scp.put /path/to/file /var/tmp/file hostname=server1 auto_add_policy=True ''' scp_client = _prepare_connection(**kwargs) put_kwargs = { 'recursive': recursive, 'preserve_times': preserve_times } if remote_path: put_kwargs['remote_path'] = remote_path cached_files = [] if not isinstance(files, (list, tuple)): files = [files] for file_ in files: cached_file = __salt__['cp.cache_file'](file_, saltenv=saltenv) cached_files.append(cached_file) return scp_client.put(cached_files, **put_kwargs)
saltstack/salt
salt/modules/scp_mod.py
put
python
def put(files, remote_path=None, recursive=False, preserve_times=False, saltenv='base', **kwargs): ''' Transfer files and directories to remote host. files A single path or a list of paths to be transferred. remote_path The path on the remote device where to store the files. recursive: ``True`` Transfer files and directories recursively. preserve_times: ``False`` Preserve ``mtime`` and ``atime`` of transferred files and directories. hostname The hostname of the remote device. port: ``22`` The port of the remote device. username The username required for SSH authentication on the device. password Used for password authentication. It is also used for private key decryption if ``passphrase`` is not given. passphrase Used for decrypting private keys. pkey An optional private key to use for authentication. key_filename The filename, or list of filenames, of optional private key(s) and/or certificates to try for authentication. timeout An optional timeout (in seconds) for the TCP connect. socket_timeout: ``10`` The channel socket timeout in seconds. buff_size: ``16384`` The size of the SCP send buffer. allow_agent: ``True`` Set to ``False`` to disable connecting to the SSH agent. look_for_keys: ``True`` Set to ``False`` to disable searching for discoverable private key files in ``~/.ssh/`` banner_timeout An optional timeout (in seconds) to wait for the SSH banner to be presented. auth_timeout An optional timeout (in seconds) to wait for an authentication response. auto_add_policy: ``False`` Automatically add the host to the ``known_hosts``. CLI Example: .. code-block:: bash salt '*' scp.put /path/to/file /var/tmp/file hostname=server1 auto_add_policy=True ''' scp_client = _prepare_connection(**kwargs) put_kwargs = { 'recursive': recursive, 'preserve_times': preserve_times } if remote_path: put_kwargs['remote_path'] = remote_path cached_files = [] if not isinstance(files, (list, tuple)): files = [files] for file_ in files: cached_file = __salt__['cp.cache_file'](file_, saltenv=saltenv) cached_files.append(cached_file) return scp_client.put(cached_files, **put_kwargs)
Transfer files and directories to remote host. files A single path or a list of paths to be transferred. remote_path The path on the remote device where to store the files. recursive: ``True`` Transfer files and directories recursively. preserve_times: ``False`` Preserve ``mtime`` and ``atime`` of transferred files and directories. hostname The hostname of the remote device. port: ``22`` The port of the remote device. username The username required for SSH authentication on the device. password Used for password authentication. It is also used for private key decryption if ``passphrase`` is not given. passphrase Used for decrypting private keys. pkey An optional private key to use for authentication. key_filename The filename, or list of filenames, of optional private key(s) and/or certificates to try for authentication. timeout An optional timeout (in seconds) for the TCP connect. socket_timeout: ``10`` The channel socket timeout in seconds. buff_size: ``16384`` The size of the SCP send buffer. allow_agent: ``True`` Set to ``False`` to disable connecting to the SSH agent. look_for_keys: ``True`` Set to ``False`` to disable searching for discoverable private key files in ``~/.ssh/`` banner_timeout An optional timeout (in seconds) to wait for the SSH banner to be presented. auth_timeout An optional timeout (in seconds) to wait for an authentication response. auto_add_policy: ``False`` Automatically add the host to the ``known_hosts``. CLI Example: .. code-block:: bash salt '*' scp.put /path/to/file /var/tmp/file hostname=server1 auto_add_policy=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/scp_mod.py#L154-L244
[ "def _prepare_connection(**kwargs):\n '''\n Prepare the underlying SSH connection with the remote target.\n '''\n paramiko_kwargs, scp_kwargs = _select_kwargs(**kwargs)\n ssh = paramiko.SSHClient()\n if paramiko_kwargs.pop('auto_add_policy', False):\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n ssh.connect(**paramiko_kwargs)\n scp_client = scp.SCPClient(ssh.get_transport(),\n **scp_kwargs)\n return scp_client\n" ]
# -*- coding: utf-8 -*- ''' SCP Module ========== .. versionadded:: 2019.2.0 Module to copy files via `SCP <https://man.openbsd.org/scp>`_ ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import inspect # Import salt modules from salt.ext import six try: import scp import paramiko HAS_SCP = True except ImportError: HAS_SCP = False __proxyenabled__ = ['*'] __virtualname__ = 'scp' log = logging.getLogger(__name__) def __virtual__(): if not HAS_SCP: return False, 'Please install SCP for this modules: pip install scp' return __virtualname__ def _select_kwargs(**kwargs): paramiko_kwargs = {} scp_kwargs = {} PARAMIKO_KWARGS, _, _, _ = inspect.getargspec(paramiko.SSHClient.connect) PARAMIKO_KWARGS.pop(0) # strip self PARAMIKO_KWARGS.append('auto_add_policy') SCP_KWARGS, _, _, _ = inspect.getargspec(scp.SCPClient.__init__) SCP_KWARGS.pop(0) # strip self SCP_KWARGS.pop(0) # strip transport arg (it is passed in _prepare_connection) for karg, warg in six.iteritems(kwargs): if karg in PARAMIKO_KWARGS and warg is not None: paramiko_kwargs[karg] = warg if karg in SCP_KWARGS and warg is not None: scp_kwargs[karg] = warg return paramiko_kwargs, scp_kwargs def _prepare_connection(**kwargs): ''' Prepare the underlying SSH connection with the remote target. ''' paramiko_kwargs, scp_kwargs = _select_kwargs(**kwargs) ssh = paramiko.SSHClient() if paramiko_kwargs.pop('auto_add_policy', False): ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(**paramiko_kwargs) scp_client = scp.SCPClient(ssh.get_transport(), **scp_kwargs) return scp_client def get(remote_path, local_path='', recursive=False, preserve_times=False, **kwargs): ''' Transfer files and directories from remote host to the localhost of the Minion. remote_path Path to retrieve from remote host. Since this is evaluated by scp on the remote host, shell wildcards and environment variables may be used. recursive: ``False`` Transfer files and directories recursively. preserve_times: ``False`` Preserve ``mtime`` and ``atime`` of transferred files and directories. hostname The hostname of the remote device. port: ``22`` The port of the remote device. username The username required for SSH authentication on the device. password Used for password authentication. It is also used for private key decryption if ``passphrase`` is not given. passphrase Used for decrypting private keys. pkey An optional private key to use for authentication. key_filename The filename, or list of filenames, of optional private key(s) and/or certificates to try for authentication. timeout An optional timeout (in seconds) for the TCP connect. socket_timeout: ``10`` The channel socket timeout in seconds. buff_size: ``16384`` The size of the SCP send buffer. allow_agent: ``True`` Set to ``False`` to disable connecting to the SSH agent. look_for_keys: ``True`` Set to ``False`` to disable searching for discoverable private key files in ``~/.ssh/`` banner_timeout An optional timeout (in seconds) to wait for the SSH banner to be presented. auth_timeout An optional timeout (in seconds) to wait for an authentication response. auto_add_policy: ``False`` Automatically add the host to the ``known_hosts``. CLI Example: .. code-block:: bash salt '*' scp.get /var/tmp/file /tmp/file hostname=10.10.10.1 auto_add_policy=True ''' scp_client = _prepare_connection(**kwargs) get_kwargs = { 'recursive': recursive, 'preserve_times': preserve_times } if local_path: get_kwargs['local_path'] = local_path return scp_client.get(remote_path, **get_kwargs)
saltstack/salt
salt/modules/bigip.py
_build_session
python
def _build_session(username, password, trans_label=None): ''' Create a session to be used when connecting to iControl REST. ''' bigip = requests.session() bigip.auth = (username, password) bigip.verify = False bigip.headers.update({'Content-Type': 'application/json'}) if trans_label: #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label)) if trans_id: bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id}) else: bigip.headers.update({'X-F5-REST-Coordination-Id': None}) return bigip
Create a session to be used when connecting to iControl REST.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L43-L62
null
# -*- coding: utf-8 -*- ''' An execution module which can manipulate an f5 bigip via iControl REST :maturity: develop :platform: f5_bigip_11.6 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.utils.json # Import third party libs try: import requests import requests.exceptions HAS_LIBS = True except ImportError: HAS_LIBS = False # Import 3rd-party libs from salt.ext import six # Import salt libs import salt.exceptions # Define the module's virtual name __virtualname__ = 'bigip' def __virtual__(): ''' Only return if requests is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The bigip execution module cannot be loaded: ' 'python requests library not available.') BIG_IP_URL_BASE = 'https://{host}/mgmt/tm' def _load_response(response): ''' Load the response from json data, return the dictionary or raw text ''' try: data = salt.utils.json.loads(response.text) except ValueError: data = response.text ret = {'code': response.status_code, 'content': data} return ret def _load_connection_error(hostname, error): ''' Format and Return a connection error ''' ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\n{error}'.format(host=hostname, error=error)} return ret def _loop_payload(params): ''' Pass in a dictionary of parameters, loop through them and build a payload containing, parameters who's values are not None. ''' #construct the payload payload = {} #set the payload for param, value in six.iteritems(params): if value is not None: payload[param] = value return payload def _build_list(option_value, item_kind): ''' pass in an option to check for a list of items, create a list of dictionary of items to set for this option ''' #specify profiles if provided if option_value is not None: items = [] #if user specified none, return an empty list if option_value == 'none': return items #was a list already passed in? if not isinstance(option_value, list): values = option_value.split(',') else: values = option_value for value in values: # sometimes the bigip just likes a plain ol list of items if item_kind is None: items.append(value) # other times it's picky and likes key value pairs... else: items.append({'kind': item_kind, 'name': value}) return items return None def _determine_toggles(payload, toggles): ''' BigIP can't make up its mind if it likes yes / no or true or false. Figure out what it likes to hear without confusing the user. ''' for toggle, definition in six.iteritems(toggles): #did the user specify anything? if definition['value'] is not None: #test for yes_no toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no': payload[toggle] = 'yes' elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no': payload[toggle] = 'no' #test for true_false toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false': payload[toggle] = True elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false': payload[toggle] = False return payload def _set_value(value): ''' A function to detect if user is trying to pass a dictionary or list. parse it and return a dictionary list or a string ''' #don't continue if already an acceptable data-type if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list): return value #check if json if value.startswith('j{') and value.endswith('}j'): value = value.replace('j{', '{') value = value.replace('}j', '}') try: return salt.utils.json.loads(value) except Exception: raise salt.exceptions.CommandExecutionError #detect list of dictionaries if '|' in value and r'\|' not in value: values = value.split('|') items = [] for value in values: items.append(_set_value(value)) return items #parse out dictionary if detected if ':' in value and r'\:' not in value: options = {} #split out pairs key_pairs = value.split(',') for key_pair in key_pairs: k = key_pair.split(':')[0] v = key_pair.split(':')[1] options[k] = v return options #try making a list elif ',' in value and r'\,' not in value: value_items = value.split(',') return value_items #just return a string else: #remove escape chars if added if r'\|' in value: value = value.replace(r'\|', '|') if r'\:' in value: value = value.replace(r'\:', ':') if r'\,' in value: value = value.replace(r'\,', ',') return value def start_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and start a new transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The name / alias for this transaction. The actual transaction id will be stored within a grain called ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.start_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) payload = {} #post to REST to get trans id try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/transaction', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) #extract the trans_id data = _load_response(response) if data['code'] == 200: trans_id = data['content']['transId'] __salt__['grains.setval']('bigip_f5_trans', {label: trans_id}) return 'Transaction: {trans_id} - has successfully been stored in the grain: bigip_f5_trans:{label}'.format(trans_id=trans_id, label=label) else: return data def list_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and list an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #post to REST to get trans id try: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}/commands'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def commit_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and commit an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.commit_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: payload = {} payload['state'] = 'VALIDATING' #patch to REST to get trans id try: response = bigip_session.patch( BIG_IP_URL_BASE.format(host=hostname) + '/transaction/{trans_id}'.format(trans_id=trans_id), data=salt.utils.json.dumps(payload) ) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def delete_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and delete an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #patch to REST to get trans id try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def list_node(hostname, username, password, name=None, trans_label=None): ''' A function to connect to a bigip device and list all nodes or a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to list. If no name is specified than all nodes will be listed. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_node bigip admin admin my-node ''' #build sessions bigip_session = _build_session(username, password, trans_label) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_node(hostname, username, password, name, address, trans_label=None): ''' A function to connect to a bigip device and create a node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node address The address of the node trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.create_node bigip admin admin 10.1.1.2 ''' #build session bigip_session = _build_session(username, password, trans_label) #construct the payload payload = {} payload['name'] = name payload['address'] = address #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node', data=salt.utils.json.dumps(payload)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_node(hostname, username, password, name, connection_limit=None, description=None, dynamic_ratio=None, logging=None, monitor=None, rate_limit=None, ratio=None, session=None, state=None, trans_label=None): ''' A function to connect to a bigip device and modify an existing node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to modify connection_limit [integer] description [string] dynamic_ratio [integer] logging [enabled | disabled] monitor [[name] | none | default] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [user-down | user-up ] trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.modify_node bigip admin admin 10.1.1.2 ratio=2 logging=enabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'logging': logging, 'monitor': monitor, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state, } #build session bigip_session = _build_session(username, password, trans_label) #build payload payload = _loop_payload(params) payload['name'] = name #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_node(hostname, username, password, name, trans_label=None): ''' A function to connect to a bigip device and delete a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node which will be deleted. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_node bigip admin admin my-node ''' #build session bigip_session = _build_session(username, password, trans_label) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_pool(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all pools or a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to list. If no name is specified then all pools will be listed. CLI Example:: salt '*' bigip.list_pool bigip admin admin my-pool ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_pool(hostname, username, password, name, members=None, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and create a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to create. members List of comma delimited pool members to add to the pool. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [enabled | disabled] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_depth_limit [integer] queue_on_connection_limit [enabled | disabled] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.create_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 monitor=http ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up-members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify members if provided if members is not None: payload['members'] = _build_list(members, 'ltm:pool:members') #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool(hostname, username, password, name, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and modify an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify. allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [yes | no] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_on_connection_limit [enabled | disabled] queue_depth_limit [integer] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.modify_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 min_active_members=1 ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up_members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool which will be deleted CLI Example:: salt '*' bigip.delete_node bigip admin admin my-pool ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def replace_pool_members(hostname, username, password, name, members): ''' A function to connect to a bigip device and replace members of an existing pool with new members. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify members List of comma delimited pool members to replace existing members with. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 CLI Example:: salt '*' bigip.replace_pool_members bigip admin admin my-pool 10.2.2.1:80,10.2.2.2:80,10.2.2.3:80 ''' payload = {} payload['name'] = name #specify members if provided if members is not None: if isinstance(members, six.string_types): members = members.split(',') pool_members = [] for member in members: #check to see if already a dictionary ( for states) if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) pool_members.append(member) #parse string passed via execution command (for executions) else: pool_members.append({'name': member, 'address': member.split(':')[0]}) payload['members'] = pool_members #build session bigip_session = _build_session(username, password) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def add_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and add a new member to an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to add i.e. 10.1.1.2:80 CLI Example: .. code-block:: bash salt '*' bigip.add_pool_members bigip admin admin my-pool 10.2.2.1:80 ''' # for states if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) payload = member # for execution else: payload = {'name': member, 'address': member.split(':')[0]} #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool_member(hostname, username, password, name, member, connection_limit=None, description=None, dynamic_ratio=None, inherit_profile=None, logging=None, monitor=None, priority_group=None, profiles=None, rate_limit=None, ratio=None, session=None, state=None): ''' A function to connect to a bigip device and modify an existing member of a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to modify i.e. 10.1.1.2:80 connection_limit [integer] description [string] dynamic_ratio [integer] inherit_profile [enabled | disabled] logging [enabled | disabled] monitor [name] priority_group [integer] profiles [none | profile_name] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [ user-up | user-down ] CLI Example:: salt '*' bigip.modify_pool_member bigip admin admin my-pool 10.2.2.1:80 state=use-down session=user-disabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'inherit-profile': inherit_profile, 'logging': logging, 'monitor': monitor, 'priority-group': priority_group, 'profiles': profiles, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members/{member}'.format(name=name, member=member), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the pool member to delete CLI Example:: salt '*' bigip.delete_pool_member bigip admin admin my-pool 10.2.2.2:80 ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/members/{member}'.format(name=name, member=member)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_virtual(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all virtuals or a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to list. If no name is specified than all virtuals will be listed. CLI Example:: salt '*' bigip.list_virtual bigip admin admin my-virtual ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_virtual(hostname, username, password, name, destination, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): r''' A function to connect to a bigip device and create a virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to create destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no] connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limit_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limitçsrc [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disabled] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Examples:: salt '*' bigip.create_virtual bigip admin admin my-virtual-3 26.2.2.5:80 \ pool=my-http-pool-http profiles=http,tcp salt '*' bigip.create_virtual bigip admin admin my-virtual-3 43.2.2.5:80 \ pool=test-http-pool-http profiles=http,websecurity persist=cookie,hash \ policies=asm_auto_l7_policy__http-virtual \ rules=_sys_APM_ExchangeSupport_helper,_sys_https_redirect \ related_rules=_sys_APM_activesync,_sys_APM_ExchangeSupport_helper \ source_address_translation=snat:my-snat-pool \ translate_address=enabled translate_port=enabled \ traffic_classes=my-class,other-class \ vlans=enabled:external,internal ''' params = { 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name payload['destination'] = destination #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: #check to see if this is already a dictionary first if isinstance(source_address_translation, dict): payload['source-address-translation'] = source_address_translation elif source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif isinstance(vlans, six.string_types) and (vlans.startswith('enabled') or vlans.startswith('disabled')): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) else: return 'Error: vlans must be a dictionary or string.' #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_virtual(hostname, username, password, name, destination=None, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): ''' A function to connect to a bigip device and modify an existing virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to modify destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no} connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limitr_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limit_src [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disable] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Example:: salt '*' bigip.modify_virtual bigip admin admin my-virtual source_address_translation=none salt '*' bigip.modify_virtual bigip admin admin my-virtual rules=my-rule,my-other-rule ''' params = { 'destination': destination, 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: if source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif vlans.startswith('enabled') or vlans.startswith('disabled'): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_virtual(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to delete CLI Example:: salt '*' bigip.delete_virtual bigip admin admin my-virtual ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_monitor(hostname, username, password, monitor_type, name=None, ): ''' A function to connect to a bigip device and list an existing monitor. If no name is provided than all monitors of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor(s) to list name The name of the monitor to list CLI Example:: salt '*' bigip.list_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}?expandSubcollections=true'.format(type=monitor_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}'.format(type=monitor_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and create a monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to create name The name of the monitor to create kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.create_monitor bigip admin admin http my-http-monitor timeout=10 interval=5 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type']: key = key.replace('_', '-') payload[key] = value #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}'.format(type=monitor_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and modify an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to modify name The name of the monitor to modify kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.modify_monitor bigip admin admin http my-http-monitor timout=16 interval=6 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type', 'name']: key = key.replace('_', '-') payload[key] = value #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_monitor(hostname, username, password, monitor_type, name): ''' A function to connect to a bigip device and delete an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to delete name The name of the monitor to delete CLI Example:: salt '*' bigip.delete_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_profile(hostname, username, password, profile_type, name=None, ): ''' A function to connect to a bigip device and list an existing profile. If no name is provided than all profiles of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile(s) to list name The name of the profile to list CLI Example:: salt '*' bigip.list_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}?expandSubcollections=true'.format(type=profile_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}'.format(type=profile_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}'.format(type=profile_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 salt '*' bigip.modify_profile bigip admin admin client-ssl my-client-ssl-1 retainCertificate=false \ ciphers='DEFAULT\:!SSLv3' cert_key_chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j' ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}/{name}'.format(type=profile_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_profile(hostname, username, password, profile_type, name): ''' A function to connect to a bigip device and delete an existing profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to delete name The name of the profile to delete CLI Example:: salt '*' bigip.delete_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}'.format(type=profile_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response)
saltstack/salt
salt/modules/bigip.py
_load_response
python
def _load_response(response): ''' Load the response from json data, return the dictionary or raw text ''' try: data = salt.utils.json.loads(response.text) except ValueError: data = response.text ret = {'code': response.status_code, 'content': data} return ret
Load the response from json data, return the dictionary or raw text
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L65-L77
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n" ]
# -*- coding: utf-8 -*- ''' An execution module which can manipulate an f5 bigip via iControl REST :maturity: develop :platform: f5_bigip_11.6 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.utils.json # Import third party libs try: import requests import requests.exceptions HAS_LIBS = True except ImportError: HAS_LIBS = False # Import 3rd-party libs from salt.ext import six # Import salt libs import salt.exceptions # Define the module's virtual name __virtualname__ = 'bigip' def __virtual__(): ''' Only return if requests is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The bigip execution module cannot be loaded: ' 'python requests library not available.') BIG_IP_URL_BASE = 'https://{host}/mgmt/tm' def _build_session(username, password, trans_label=None): ''' Create a session to be used when connecting to iControl REST. ''' bigip = requests.session() bigip.auth = (username, password) bigip.verify = False bigip.headers.update({'Content-Type': 'application/json'}) if trans_label: #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label)) if trans_id: bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id}) else: bigip.headers.update({'X-F5-REST-Coordination-Id': None}) return bigip def _load_connection_error(hostname, error): ''' Format and Return a connection error ''' ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\n{error}'.format(host=hostname, error=error)} return ret def _loop_payload(params): ''' Pass in a dictionary of parameters, loop through them and build a payload containing, parameters who's values are not None. ''' #construct the payload payload = {} #set the payload for param, value in six.iteritems(params): if value is not None: payload[param] = value return payload def _build_list(option_value, item_kind): ''' pass in an option to check for a list of items, create a list of dictionary of items to set for this option ''' #specify profiles if provided if option_value is not None: items = [] #if user specified none, return an empty list if option_value == 'none': return items #was a list already passed in? if not isinstance(option_value, list): values = option_value.split(',') else: values = option_value for value in values: # sometimes the bigip just likes a plain ol list of items if item_kind is None: items.append(value) # other times it's picky and likes key value pairs... else: items.append({'kind': item_kind, 'name': value}) return items return None def _determine_toggles(payload, toggles): ''' BigIP can't make up its mind if it likes yes / no or true or false. Figure out what it likes to hear without confusing the user. ''' for toggle, definition in six.iteritems(toggles): #did the user specify anything? if definition['value'] is not None: #test for yes_no toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no': payload[toggle] = 'yes' elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no': payload[toggle] = 'no' #test for true_false toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false': payload[toggle] = True elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false': payload[toggle] = False return payload def _set_value(value): ''' A function to detect if user is trying to pass a dictionary or list. parse it and return a dictionary list or a string ''' #don't continue if already an acceptable data-type if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list): return value #check if json if value.startswith('j{') and value.endswith('}j'): value = value.replace('j{', '{') value = value.replace('}j', '}') try: return salt.utils.json.loads(value) except Exception: raise salt.exceptions.CommandExecutionError #detect list of dictionaries if '|' in value and r'\|' not in value: values = value.split('|') items = [] for value in values: items.append(_set_value(value)) return items #parse out dictionary if detected if ':' in value and r'\:' not in value: options = {} #split out pairs key_pairs = value.split(',') for key_pair in key_pairs: k = key_pair.split(':')[0] v = key_pair.split(':')[1] options[k] = v return options #try making a list elif ',' in value and r'\,' not in value: value_items = value.split(',') return value_items #just return a string else: #remove escape chars if added if r'\|' in value: value = value.replace(r'\|', '|') if r'\:' in value: value = value.replace(r'\:', ':') if r'\,' in value: value = value.replace(r'\,', ',') return value def start_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and start a new transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The name / alias for this transaction. The actual transaction id will be stored within a grain called ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.start_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) payload = {} #post to REST to get trans id try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/transaction', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) #extract the trans_id data = _load_response(response) if data['code'] == 200: trans_id = data['content']['transId'] __salt__['grains.setval']('bigip_f5_trans', {label: trans_id}) return 'Transaction: {trans_id} - has successfully been stored in the grain: bigip_f5_trans:{label}'.format(trans_id=trans_id, label=label) else: return data def list_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and list an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #post to REST to get trans id try: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}/commands'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def commit_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and commit an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.commit_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: payload = {} payload['state'] = 'VALIDATING' #patch to REST to get trans id try: response = bigip_session.patch( BIG_IP_URL_BASE.format(host=hostname) + '/transaction/{trans_id}'.format(trans_id=trans_id), data=salt.utils.json.dumps(payload) ) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def delete_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and delete an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #patch to REST to get trans id try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def list_node(hostname, username, password, name=None, trans_label=None): ''' A function to connect to a bigip device and list all nodes or a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to list. If no name is specified than all nodes will be listed. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_node bigip admin admin my-node ''' #build sessions bigip_session = _build_session(username, password, trans_label) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_node(hostname, username, password, name, address, trans_label=None): ''' A function to connect to a bigip device and create a node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node address The address of the node trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.create_node bigip admin admin 10.1.1.2 ''' #build session bigip_session = _build_session(username, password, trans_label) #construct the payload payload = {} payload['name'] = name payload['address'] = address #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node', data=salt.utils.json.dumps(payload)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_node(hostname, username, password, name, connection_limit=None, description=None, dynamic_ratio=None, logging=None, monitor=None, rate_limit=None, ratio=None, session=None, state=None, trans_label=None): ''' A function to connect to a bigip device and modify an existing node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to modify connection_limit [integer] description [string] dynamic_ratio [integer] logging [enabled | disabled] monitor [[name] | none | default] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [user-down | user-up ] trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.modify_node bigip admin admin 10.1.1.2 ratio=2 logging=enabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'logging': logging, 'monitor': monitor, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state, } #build session bigip_session = _build_session(username, password, trans_label) #build payload payload = _loop_payload(params) payload['name'] = name #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_node(hostname, username, password, name, trans_label=None): ''' A function to connect to a bigip device and delete a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node which will be deleted. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_node bigip admin admin my-node ''' #build session bigip_session = _build_session(username, password, trans_label) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_pool(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all pools or a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to list. If no name is specified then all pools will be listed. CLI Example:: salt '*' bigip.list_pool bigip admin admin my-pool ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_pool(hostname, username, password, name, members=None, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and create a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to create. members List of comma delimited pool members to add to the pool. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [enabled | disabled] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_depth_limit [integer] queue_on_connection_limit [enabled | disabled] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.create_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 monitor=http ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up-members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify members if provided if members is not None: payload['members'] = _build_list(members, 'ltm:pool:members') #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool(hostname, username, password, name, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and modify an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify. allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [yes | no] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_on_connection_limit [enabled | disabled] queue_depth_limit [integer] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.modify_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 min_active_members=1 ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up_members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool which will be deleted CLI Example:: salt '*' bigip.delete_node bigip admin admin my-pool ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def replace_pool_members(hostname, username, password, name, members): ''' A function to connect to a bigip device and replace members of an existing pool with new members. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify members List of comma delimited pool members to replace existing members with. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 CLI Example:: salt '*' bigip.replace_pool_members bigip admin admin my-pool 10.2.2.1:80,10.2.2.2:80,10.2.2.3:80 ''' payload = {} payload['name'] = name #specify members if provided if members is not None: if isinstance(members, six.string_types): members = members.split(',') pool_members = [] for member in members: #check to see if already a dictionary ( for states) if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) pool_members.append(member) #parse string passed via execution command (for executions) else: pool_members.append({'name': member, 'address': member.split(':')[0]}) payload['members'] = pool_members #build session bigip_session = _build_session(username, password) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def add_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and add a new member to an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to add i.e. 10.1.1.2:80 CLI Example: .. code-block:: bash salt '*' bigip.add_pool_members bigip admin admin my-pool 10.2.2.1:80 ''' # for states if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) payload = member # for execution else: payload = {'name': member, 'address': member.split(':')[0]} #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool_member(hostname, username, password, name, member, connection_limit=None, description=None, dynamic_ratio=None, inherit_profile=None, logging=None, monitor=None, priority_group=None, profiles=None, rate_limit=None, ratio=None, session=None, state=None): ''' A function to connect to a bigip device and modify an existing member of a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to modify i.e. 10.1.1.2:80 connection_limit [integer] description [string] dynamic_ratio [integer] inherit_profile [enabled | disabled] logging [enabled | disabled] monitor [name] priority_group [integer] profiles [none | profile_name] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [ user-up | user-down ] CLI Example:: salt '*' bigip.modify_pool_member bigip admin admin my-pool 10.2.2.1:80 state=use-down session=user-disabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'inherit-profile': inherit_profile, 'logging': logging, 'monitor': monitor, 'priority-group': priority_group, 'profiles': profiles, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members/{member}'.format(name=name, member=member), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the pool member to delete CLI Example:: salt '*' bigip.delete_pool_member bigip admin admin my-pool 10.2.2.2:80 ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/members/{member}'.format(name=name, member=member)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_virtual(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all virtuals or a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to list. If no name is specified than all virtuals will be listed. CLI Example:: salt '*' bigip.list_virtual bigip admin admin my-virtual ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_virtual(hostname, username, password, name, destination, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): r''' A function to connect to a bigip device and create a virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to create destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no] connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limit_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limitçsrc [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disabled] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Examples:: salt '*' bigip.create_virtual bigip admin admin my-virtual-3 26.2.2.5:80 \ pool=my-http-pool-http profiles=http,tcp salt '*' bigip.create_virtual bigip admin admin my-virtual-3 43.2.2.5:80 \ pool=test-http-pool-http profiles=http,websecurity persist=cookie,hash \ policies=asm_auto_l7_policy__http-virtual \ rules=_sys_APM_ExchangeSupport_helper,_sys_https_redirect \ related_rules=_sys_APM_activesync,_sys_APM_ExchangeSupport_helper \ source_address_translation=snat:my-snat-pool \ translate_address=enabled translate_port=enabled \ traffic_classes=my-class,other-class \ vlans=enabled:external,internal ''' params = { 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name payload['destination'] = destination #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: #check to see if this is already a dictionary first if isinstance(source_address_translation, dict): payload['source-address-translation'] = source_address_translation elif source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif isinstance(vlans, six.string_types) and (vlans.startswith('enabled') or vlans.startswith('disabled')): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) else: return 'Error: vlans must be a dictionary or string.' #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_virtual(hostname, username, password, name, destination=None, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): ''' A function to connect to a bigip device and modify an existing virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to modify destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no} connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limitr_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limit_src [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disable] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Example:: salt '*' bigip.modify_virtual bigip admin admin my-virtual source_address_translation=none salt '*' bigip.modify_virtual bigip admin admin my-virtual rules=my-rule,my-other-rule ''' params = { 'destination': destination, 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: if source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif vlans.startswith('enabled') or vlans.startswith('disabled'): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_virtual(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to delete CLI Example:: salt '*' bigip.delete_virtual bigip admin admin my-virtual ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_monitor(hostname, username, password, monitor_type, name=None, ): ''' A function to connect to a bigip device and list an existing monitor. If no name is provided than all monitors of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor(s) to list name The name of the monitor to list CLI Example:: salt '*' bigip.list_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}?expandSubcollections=true'.format(type=monitor_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}'.format(type=monitor_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and create a monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to create name The name of the monitor to create kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.create_monitor bigip admin admin http my-http-monitor timeout=10 interval=5 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type']: key = key.replace('_', '-') payload[key] = value #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}'.format(type=monitor_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and modify an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to modify name The name of the monitor to modify kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.modify_monitor bigip admin admin http my-http-monitor timout=16 interval=6 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type', 'name']: key = key.replace('_', '-') payload[key] = value #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_monitor(hostname, username, password, monitor_type, name): ''' A function to connect to a bigip device and delete an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to delete name The name of the monitor to delete CLI Example:: salt '*' bigip.delete_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_profile(hostname, username, password, profile_type, name=None, ): ''' A function to connect to a bigip device and list an existing profile. If no name is provided than all profiles of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile(s) to list name The name of the profile to list CLI Example:: salt '*' bigip.list_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}?expandSubcollections=true'.format(type=profile_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}'.format(type=profile_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}'.format(type=profile_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 salt '*' bigip.modify_profile bigip admin admin client-ssl my-client-ssl-1 retainCertificate=false \ ciphers='DEFAULT\:!SSLv3' cert_key_chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j' ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}/{name}'.format(type=profile_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_profile(hostname, username, password, profile_type, name): ''' A function to connect to a bigip device and delete an existing profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to delete name The name of the profile to delete CLI Example:: salt '*' bigip.delete_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}'.format(type=profile_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response)
saltstack/salt
salt/modules/bigip.py
_load_connection_error
python
def _load_connection_error(hostname, error): ''' Format and Return a connection error ''' ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\n{error}'.format(host=hostname, error=error)} return ret
Format and Return a connection error
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L80-L87
null
# -*- coding: utf-8 -*- ''' An execution module which can manipulate an f5 bigip via iControl REST :maturity: develop :platform: f5_bigip_11.6 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.utils.json # Import third party libs try: import requests import requests.exceptions HAS_LIBS = True except ImportError: HAS_LIBS = False # Import 3rd-party libs from salt.ext import six # Import salt libs import salt.exceptions # Define the module's virtual name __virtualname__ = 'bigip' def __virtual__(): ''' Only return if requests is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The bigip execution module cannot be loaded: ' 'python requests library not available.') BIG_IP_URL_BASE = 'https://{host}/mgmt/tm' def _build_session(username, password, trans_label=None): ''' Create a session to be used when connecting to iControl REST. ''' bigip = requests.session() bigip.auth = (username, password) bigip.verify = False bigip.headers.update({'Content-Type': 'application/json'}) if trans_label: #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label)) if trans_id: bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id}) else: bigip.headers.update({'X-F5-REST-Coordination-Id': None}) return bigip def _load_response(response): ''' Load the response from json data, return the dictionary or raw text ''' try: data = salt.utils.json.loads(response.text) except ValueError: data = response.text ret = {'code': response.status_code, 'content': data} return ret def _loop_payload(params): ''' Pass in a dictionary of parameters, loop through them and build a payload containing, parameters who's values are not None. ''' #construct the payload payload = {} #set the payload for param, value in six.iteritems(params): if value is not None: payload[param] = value return payload def _build_list(option_value, item_kind): ''' pass in an option to check for a list of items, create a list of dictionary of items to set for this option ''' #specify profiles if provided if option_value is not None: items = [] #if user specified none, return an empty list if option_value == 'none': return items #was a list already passed in? if not isinstance(option_value, list): values = option_value.split(',') else: values = option_value for value in values: # sometimes the bigip just likes a plain ol list of items if item_kind is None: items.append(value) # other times it's picky and likes key value pairs... else: items.append({'kind': item_kind, 'name': value}) return items return None def _determine_toggles(payload, toggles): ''' BigIP can't make up its mind if it likes yes / no or true or false. Figure out what it likes to hear without confusing the user. ''' for toggle, definition in six.iteritems(toggles): #did the user specify anything? if definition['value'] is not None: #test for yes_no toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no': payload[toggle] = 'yes' elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no': payload[toggle] = 'no' #test for true_false toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false': payload[toggle] = True elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false': payload[toggle] = False return payload def _set_value(value): ''' A function to detect if user is trying to pass a dictionary or list. parse it and return a dictionary list or a string ''' #don't continue if already an acceptable data-type if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list): return value #check if json if value.startswith('j{') and value.endswith('}j'): value = value.replace('j{', '{') value = value.replace('}j', '}') try: return salt.utils.json.loads(value) except Exception: raise salt.exceptions.CommandExecutionError #detect list of dictionaries if '|' in value and r'\|' not in value: values = value.split('|') items = [] for value in values: items.append(_set_value(value)) return items #parse out dictionary if detected if ':' in value and r'\:' not in value: options = {} #split out pairs key_pairs = value.split(',') for key_pair in key_pairs: k = key_pair.split(':')[0] v = key_pair.split(':')[1] options[k] = v return options #try making a list elif ',' in value and r'\,' not in value: value_items = value.split(',') return value_items #just return a string else: #remove escape chars if added if r'\|' in value: value = value.replace(r'\|', '|') if r'\:' in value: value = value.replace(r'\:', ':') if r'\,' in value: value = value.replace(r'\,', ',') return value def start_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and start a new transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The name / alias for this transaction. The actual transaction id will be stored within a grain called ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.start_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) payload = {} #post to REST to get trans id try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/transaction', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) #extract the trans_id data = _load_response(response) if data['code'] == 200: trans_id = data['content']['transId'] __salt__['grains.setval']('bigip_f5_trans', {label: trans_id}) return 'Transaction: {trans_id} - has successfully been stored in the grain: bigip_f5_trans:{label}'.format(trans_id=trans_id, label=label) else: return data def list_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and list an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #post to REST to get trans id try: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}/commands'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def commit_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and commit an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.commit_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: payload = {} payload['state'] = 'VALIDATING' #patch to REST to get trans id try: response = bigip_session.patch( BIG_IP_URL_BASE.format(host=hostname) + '/transaction/{trans_id}'.format(trans_id=trans_id), data=salt.utils.json.dumps(payload) ) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def delete_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and delete an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #patch to REST to get trans id try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def list_node(hostname, username, password, name=None, trans_label=None): ''' A function to connect to a bigip device and list all nodes or a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to list. If no name is specified than all nodes will be listed. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_node bigip admin admin my-node ''' #build sessions bigip_session = _build_session(username, password, trans_label) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_node(hostname, username, password, name, address, trans_label=None): ''' A function to connect to a bigip device and create a node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node address The address of the node trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.create_node bigip admin admin 10.1.1.2 ''' #build session bigip_session = _build_session(username, password, trans_label) #construct the payload payload = {} payload['name'] = name payload['address'] = address #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node', data=salt.utils.json.dumps(payload)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_node(hostname, username, password, name, connection_limit=None, description=None, dynamic_ratio=None, logging=None, monitor=None, rate_limit=None, ratio=None, session=None, state=None, trans_label=None): ''' A function to connect to a bigip device and modify an existing node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to modify connection_limit [integer] description [string] dynamic_ratio [integer] logging [enabled | disabled] monitor [[name] | none | default] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [user-down | user-up ] trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.modify_node bigip admin admin 10.1.1.2 ratio=2 logging=enabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'logging': logging, 'monitor': monitor, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state, } #build session bigip_session = _build_session(username, password, trans_label) #build payload payload = _loop_payload(params) payload['name'] = name #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_node(hostname, username, password, name, trans_label=None): ''' A function to connect to a bigip device and delete a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node which will be deleted. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_node bigip admin admin my-node ''' #build session bigip_session = _build_session(username, password, trans_label) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_pool(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all pools or a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to list. If no name is specified then all pools will be listed. CLI Example:: salt '*' bigip.list_pool bigip admin admin my-pool ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_pool(hostname, username, password, name, members=None, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and create a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to create. members List of comma delimited pool members to add to the pool. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [enabled | disabled] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_depth_limit [integer] queue_on_connection_limit [enabled | disabled] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.create_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 monitor=http ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up-members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify members if provided if members is not None: payload['members'] = _build_list(members, 'ltm:pool:members') #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool(hostname, username, password, name, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and modify an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify. allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [yes | no] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_on_connection_limit [enabled | disabled] queue_depth_limit [integer] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.modify_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 min_active_members=1 ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up_members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool which will be deleted CLI Example:: salt '*' bigip.delete_node bigip admin admin my-pool ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def replace_pool_members(hostname, username, password, name, members): ''' A function to connect to a bigip device and replace members of an existing pool with new members. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify members List of comma delimited pool members to replace existing members with. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 CLI Example:: salt '*' bigip.replace_pool_members bigip admin admin my-pool 10.2.2.1:80,10.2.2.2:80,10.2.2.3:80 ''' payload = {} payload['name'] = name #specify members if provided if members is not None: if isinstance(members, six.string_types): members = members.split(',') pool_members = [] for member in members: #check to see if already a dictionary ( for states) if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) pool_members.append(member) #parse string passed via execution command (for executions) else: pool_members.append({'name': member, 'address': member.split(':')[0]}) payload['members'] = pool_members #build session bigip_session = _build_session(username, password) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def add_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and add a new member to an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to add i.e. 10.1.1.2:80 CLI Example: .. code-block:: bash salt '*' bigip.add_pool_members bigip admin admin my-pool 10.2.2.1:80 ''' # for states if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) payload = member # for execution else: payload = {'name': member, 'address': member.split(':')[0]} #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool_member(hostname, username, password, name, member, connection_limit=None, description=None, dynamic_ratio=None, inherit_profile=None, logging=None, monitor=None, priority_group=None, profiles=None, rate_limit=None, ratio=None, session=None, state=None): ''' A function to connect to a bigip device and modify an existing member of a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to modify i.e. 10.1.1.2:80 connection_limit [integer] description [string] dynamic_ratio [integer] inherit_profile [enabled | disabled] logging [enabled | disabled] monitor [name] priority_group [integer] profiles [none | profile_name] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [ user-up | user-down ] CLI Example:: salt '*' bigip.modify_pool_member bigip admin admin my-pool 10.2.2.1:80 state=use-down session=user-disabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'inherit-profile': inherit_profile, 'logging': logging, 'monitor': monitor, 'priority-group': priority_group, 'profiles': profiles, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members/{member}'.format(name=name, member=member), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the pool member to delete CLI Example:: salt '*' bigip.delete_pool_member bigip admin admin my-pool 10.2.2.2:80 ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/members/{member}'.format(name=name, member=member)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_virtual(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all virtuals or a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to list. If no name is specified than all virtuals will be listed. CLI Example:: salt '*' bigip.list_virtual bigip admin admin my-virtual ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_virtual(hostname, username, password, name, destination, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): r''' A function to connect to a bigip device and create a virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to create destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no] connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limit_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limitçsrc [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disabled] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Examples:: salt '*' bigip.create_virtual bigip admin admin my-virtual-3 26.2.2.5:80 \ pool=my-http-pool-http profiles=http,tcp salt '*' bigip.create_virtual bigip admin admin my-virtual-3 43.2.2.5:80 \ pool=test-http-pool-http profiles=http,websecurity persist=cookie,hash \ policies=asm_auto_l7_policy__http-virtual \ rules=_sys_APM_ExchangeSupport_helper,_sys_https_redirect \ related_rules=_sys_APM_activesync,_sys_APM_ExchangeSupport_helper \ source_address_translation=snat:my-snat-pool \ translate_address=enabled translate_port=enabled \ traffic_classes=my-class,other-class \ vlans=enabled:external,internal ''' params = { 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name payload['destination'] = destination #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: #check to see if this is already a dictionary first if isinstance(source_address_translation, dict): payload['source-address-translation'] = source_address_translation elif source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif isinstance(vlans, six.string_types) and (vlans.startswith('enabled') or vlans.startswith('disabled')): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) else: return 'Error: vlans must be a dictionary or string.' #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_virtual(hostname, username, password, name, destination=None, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): ''' A function to connect to a bigip device and modify an existing virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to modify destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no} connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limitr_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limit_src [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disable] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Example:: salt '*' bigip.modify_virtual bigip admin admin my-virtual source_address_translation=none salt '*' bigip.modify_virtual bigip admin admin my-virtual rules=my-rule,my-other-rule ''' params = { 'destination': destination, 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: if source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif vlans.startswith('enabled') or vlans.startswith('disabled'): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_virtual(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to delete CLI Example:: salt '*' bigip.delete_virtual bigip admin admin my-virtual ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_monitor(hostname, username, password, monitor_type, name=None, ): ''' A function to connect to a bigip device and list an existing monitor. If no name is provided than all monitors of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor(s) to list name The name of the monitor to list CLI Example:: salt '*' bigip.list_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}?expandSubcollections=true'.format(type=monitor_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}'.format(type=monitor_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and create a monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to create name The name of the monitor to create kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.create_monitor bigip admin admin http my-http-monitor timeout=10 interval=5 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type']: key = key.replace('_', '-') payload[key] = value #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}'.format(type=monitor_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and modify an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to modify name The name of the monitor to modify kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.modify_monitor bigip admin admin http my-http-monitor timout=16 interval=6 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type', 'name']: key = key.replace('_', '-') payload[key] = value #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_monitor(hostname, username, password, monitor_type, name): ''' A function to connect to a bigip device and delete an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to delete name The name of the monitor to delete CLI Example:: salt '*' bigip.delete_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_profile(hostname, username, password, profile_type, name=None, ): ''' A function to connect to a bigip device and list an existing profile. If no name is provided than all profiles of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile(s) to list name The name of the profile to list CLI Example:: salt '*' bigip.list_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}?expandSubcollections=true'.format(type=profile_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}'.format(type=profile_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}'.format(type=profile_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 salt '*' bigip.modify_profile bigip admin admin client-ssl my-client-ssl-1 retainCertificate=false \ ciphers='DEFAULT\:!SSLv3' cert_key_chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j' ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}/{name}'.format(type=profile_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_profile(hostname, username, password, profile_type, name): ''' A function to connect to a bigip device and delete an existing profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to delete name The name of the profile to delete CLI Example:: salt '*' bigip.delete_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}'.format(type=profile_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response)
saltstack/salt
salt/modules/bigip.py
_loop_payload
python
def _loop_payload(params): ''' Pass in a dictionary of parameters, loop through them and build a payload containing, parameters who's values are not None. ''' #construct the payload payload = {} #set the payload for param, value in six.iteritems(params): if value is not None: payload[param] = value return payload
Pass in a dictionary of parameters, loop through them and build a payload containing, parameters who's values are not None.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L90-L104
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
# -*- coding: utf-8 -*- ''' An execution module which can manipulate an f5 bigip via iControl REST :maturity: develop :platform: f5_bigip_11.6 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.utils.json # Import third party libs try: import requests import requests.exceptions HAS_LIBS = True except ImportError: HAS_LIBS = False # Import 3rd-party libs from salt.ext import six # Import salt libs import salt.exceptions # Define the module's virtual name __virtualname__ = 'bigip' def __virtual__(): ''' Only return if requests is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The bigip execution module cannot be loaded: ' 'python requests library not available.') BIG_IP_URL_BASE = 'https://{host}/mgmt/tm' def _build_session(username, password, trans_label=None): ''' Create a session to be used when connecting to iControl REST. ''' bigip = requests.session() bigip.auth = (username, password) bigip.verify = False bigip.headers.update({'Content-Type': 'application/json'}) if trans_label: #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label)) if trans_id: bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id}) else: bigip.headers.update({'X-F5-REST-Coordination-Id': None}) return bigip def _load_response(response): ''' Load the response from json data, return the dictionary or raw text ''' try: data = salt.utils.json.loads(response.text) except ValueError: data = response.text ret = {'code': response.status_code, 'content': data} return ret def _load_connection_error(hostname, error): ''' Format and Return a connection error ''' ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\n{error}'.format(host=hostname, error=error)} return ret def _build_list(option_value, item_kind): ''' pass in an option to check for a list of items, create a list of dictionary of items to set for this option ''' #specify profiles if provided if option_value is not None: items = [] #if user specified none, return an empty list if option_value == 'none': return items #was a list already passed in? if not isinstance(option_value, list): values = option_value.split(',') else: values = option_value for value in values: # sometimes the bigip just likes a plain ol list of items if item_kind is None: items.append(value) # other times it's picky and likes key value pairs... else: items.append({'kind': item_kind, 'name': value}) return items return None def _determine_toggles(payload, toggles): ''' BigIP can't make up its mind if it likes yes / no or true or false. Figure out what it likes to hear without confusing the user. ''' for toggle, definition in six.iteritems(toggles): #did the user specify anything? if definition['value'] is not None: #test for yes_no toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no': payload[toggle] = 'yes' elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no': payload[toggle] = 'no' #test for true_false toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false': payload[toggle] = True elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false': payload[toggle] = False return payload def _set_value(value): ''' A function to detect if user is trying to pass a dictionary or list. parse it and return a dictionary list or a string ''' #don't continue if already an acceptable data-type if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list): return value #check if json if value.startswith('j{') and value.endswith('}j'): value = value.replace('j{', '{') value = value.replace('}j', '}') try: return salt.utils.json.loads(value) except Exception: raise salt.exceptions.CommandExecutionError #detect list of dictionaries if '|' in value and r'\|' not in value: values = value.split('|') items = [] for value in values: items.append(_set_value(value)) return items #parse out dictionary if detected if ':' in value and r'\:' not in value: options = {} #split out pairs key_pairs = value.split(',') for key_pair in key_pairs: k = key_pair.split(':')[0] v = key_pair.split(':')[1] options[k] = v return options #try making a list elif ',' in value and r'\,' not in value: value_items = value.split(',') return value_items #just return a string else: #remove escape chars if added if r'\|' in value: value = value.replace(r'\|', '|') if r'\:' in value: value = value.replace(r'\:', ':') if r'\,' in value: value = value.replace(r'\,', ',') return value def start_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and start a new transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The name / alias for this transaction. The actual transaction id will be stored within a grain called ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.start_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) payload = {} #post to REST to get trans id try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/transaction', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) #extract the trans_id data = _load_response(response) if data['code'] == 200: trans_id = data['content']['transId'] __salt__['grains.setval']('bigip_f5_trans', {label: trans_id}) return 'Transaction: {trans_id} - has successfully been stored in the grain: bigip_f5_trans:{label}'.format(trans_id=trans_id, label=label) else: return data def list_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and list an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #post to REST to get trans id try: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}/commands'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def commit_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and commit an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.commit_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: payload = {} payload['state'] = 'VALIDATING' #patch to REST to get trans id try: response = bigip_session.patch( BIG_IP_URL_BASE.format(host=hostname) + '/transaction/{trans_id}'.format(trans_id=trans_id), data=salt.utils.json.dumps(payload) ) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def delete_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and delete an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #patch to REST to get trans id try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def list_node(hostname, username, password, name=None, trans_label=None): ''' A function to connect to a bigip device and list all nodes or a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to list. If no name is specified than all nodes will be listed. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_node bigip admin admin my-node ''' #build sessions bigip_session = _build_session(username, password, trans_label) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_node(hostname, username, password, name, address, trans_label=None): ''' A function to connect to a bigip device and create a node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node address The address of the node trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.create_node bigip admin admin 10.1.1.2 ''' #build session bigip_session = _build_session(username, password, trans_label) #construct the payload payload = {} payload['name'] = name payload['address'] = address #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node', data=salt.utils.json.dumps(payload)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_node(hostname, username, password, name, connection_limit=None, description=None, dynamic_ratio=None, logging=None, monitor=None, rate_limit=None, ratio=None, session=None, state=None, trans_label=None): ''' A function to connect to a bigip device and modify an existing node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to modify connection_limit [integer] description [string] dynamic_ratio [integer] logging [enabled | disabled] monitor [[name] | none | default] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [user-down | user-up ] trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.modify_node bigip admin admin 10.1.1.2 ratio=2 logging=enabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'logging': logging, 'monitor': monitor, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state, } #build session bigip_session = _build_session(username, password, trans_label) #build payload payload = _loop_payload(params) payload['name'] = name #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_node(hostname, username, password, name, trans_label=None): ''' A function to connect to a bigip device and delete a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node which will be deleted. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_node bigip admin admin my-node ''' #build session bigip_session = _build_session(username, password, trans_label) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_pool(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all pools or a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to list. If no name is specified then all pools will be listed. CLI Example:: salt '*' bigip.list_pool bigip admin admin my-pool ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_pool(hostname, username, password, name, members=None, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and create a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to create. members List of comma delimited pool members to add to the pool. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [enabled | disabled] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_depth_limit [integer] queue_on_connection_limit [enabled | disabled] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.create_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 monitor=http ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up-members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify members if provided if members is not None: payload['members'] = _build_list(members, 'ltm:pool:members') #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool(hostname, username, password, name, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and modify an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify. allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [yes | no] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_on_connection_limit [enabled | disabled] queue_depth_limit [integer] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.modify_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 min_active_members=1 ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up_members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool which will be deleted CLI Example:: salt '*' bigip.delete_node bigip admin admin my-pool ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def replace_pool_members(hostname, username, password, name, members): ''' A function to connect to a bigip device and replace members of an existing pool with new members. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify members List of comma delimited pool members to replace existing members with. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 CLI Example:: salt '*' bigip.replace_pool_members bigip admin admin my-pool 10.2.2.1:80,10.2.2.2:80,10.2.2.3:80 ''' payload = {} payload['name'] = name #specify members if provided if members is not None: if isinstance(members, six.string_types): members = members.split(',') pool_members = [] for member in members: #check to see if already a dictionary ( for states) if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) pool_members.append(member) #parse string passed via execution command (for executions) else: pool_members.append({'name': member, 'address': member.split(':')[0]}) payload['members'] = pool_members #build session bigip_session = _build_session(username, password) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def add_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and add a new member to an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to add i.e. 10.1.1.2:80 CLI Example: .. code-block:: bash salt '*' bigip.add_pool_members bigip admin admin my-pool 10.2.2.1:80 ''' # for states if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) payload = member # for execution else: payload = {'name': member, 'address': member.split(':')[0]} #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool_member(hostname, username, password, name, member, connection_limit=None, description=None, dynamic_ratio=None, inherit_profile=None, logging=None, monitor=None, priority_group=None, profiles=None, rate_limit=None, ratio=None, session=None, state=None): ''' A function to connect to a bigip device and modify an existing member of a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to modify i.e. 10.1.1.2:80 connection_limit [integer] description [string] dynamic_ratio [integer] inherit_profile [enabled | disabled] logging [enabled | disabled] monitor [name] priority_group [integer] profiles [none | profile_name] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [ user-up | user-down ] CLI Example:: salt '*' bigip.modify_pool_member bigip admin admin my-pool 10.2.2.1:80 state=use-down session=user-disabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'inherit-profile': inherit_profile, 'logging': logging, 'monitor': monitor, 'priority-group': priority_group, 'profiles': profiles, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members/{member}'.format(name=name, member=member), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the pool member to delete CLI Example:: salt '*' bigip.delete_pool_member bigip admin admin my-pool 10.2.2.2:80 ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/members/{member}'.format(name=name, member=member)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_virtual(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all virtuals or a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to list. If no name is specified than all virtuals will be listed. CLI Example:: salt '*' bigip.list_virtual bigip admin admin my-virtual ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_virtual(hostname, username, password, name, destination, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): r''' A function to connect to a bigip device and create a virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to create destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no] connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limit_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limitçsrc [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disabled] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Examples:: salt '*' bigip.create_virtual bigip admin admin my-virtual-3 26.2.2.5:80 \ pool=my-http-pool-http profiles=http,tcp salt '*' bigip.create_virtual bigip admin admin my-virtual-3 43.2.2.5:80 \ pool=test-http-pool-http profiles=http,websecurity persist=cookie,hash \ policies=asm_auto_l7_policy__http-virtual \ rules=_sys_APM_ExchangeSupport_helper,_sys_https_redirect \ related_rules=_sys_APM_activesync,_sys_APM_ExchangeSupport_helper \ source_address_translation=snat:my-snat-pool \ translate_address=enabled translate_port=enabled \ traffic_classes=my-class,other-class \ vlans=enabled:external,internal ''' params = { 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name payload['destination'] = destination #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: #check to see if this is already a dictionary first if isinstance(source_address_translation, dict): payload['source-address-translation'] = source_address_translation elif source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif isinstance(vlans, six.string_types) and (vlans.startswith('enabled') or vlans.startswith('disabled')): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) else: return 'Error: vlans must be a dictionary or string.' #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_virtual(hostname, username, password, name, destination=None, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): ''' A function to connect to a bigip device and modify an existing virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to modify destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no} connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limitr_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limit_src [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disable] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Example:: salt '*' bigip.modify_virtual bigip admin admin my-virtual source_address_translation=none salt '*' bigip.modify_virtual bigip admin admin my-virtual rules=my-rule,my-other-rule ''' params = { 'destination': destination, 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: if source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif vlans.startswith('enabled') or vlans.startswith('disabled'): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_virtual(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to delete CLI Example:: salt '*' bigip.delete_virtual bigip admin admin my-virtual ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_monitor(hostname, username, password, monitor_type, name=None, ): ''' A function to connect to a bigip device and list an existing monitor. If no name is provided than all monitors of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor(s) to list name The name of the monitor to list CLI Example:: salt '*' bigip.list_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}?expandSubcollections=true'.format(type=monitor_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}'.format(type=monitor_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and create a monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to create name The name of the monitor to create kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.create_monitor bigip admin admin http my-http-monitor timeout=10 interval=5 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type']: key = key.replace('_', '-') payload[key] = value #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}'.format(type=monitor_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and modify an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to modify name The name of the monitor to modify kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.modify_monitor bigip admin admin http my-http-monitor timout=16 interval=6 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type', 'name']: key = key.replace('_', '-') payload[key] = value #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_monitor(hostname, username, password, monitor_type, name): ''' A function to connect to a bigip device and delete an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to delete name The name of the monitor to delete CLI Example:: salt '*' bigip.delete_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_profile(hostname, username, password, profile_type, name=None, ): ''' A function to connect to a bigip device and list an existing profile. If no name is provided than all profiles of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile(s) to list name The name of the profile to list CLI Example:: salt '*' bigip.list_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}?expandSubcollections=true'.format(type=profile_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}'.format(type=profile_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}'.format(type=profile_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 salt '*' bigip.modify_profile bigip admin admin client-ssl my-client-ssl-1 retainCertificate=false \ ciphers='DEFAULT\:!SSLv3' cert_key_chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j' ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}/{name}'.format(type=profile_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_profile(hostname, username, password, profile_type, name): ''' A function to connect to a bigip device and delete an existing profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to delete name The name of the profile to delete CLI Example:: salt '*' bigip.delete_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}'.format(type=profile_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response)
saltstack/salt
salt/modules/bigip.py
_build_list
python
def _build_list(option_value, item_kind): ''' pass in an option to check for a list of items, create a list of dictionary of items to set for this option ''' #specify profiles if provided if option_value is not None: items = [] #if user specified none, return an empty list if option_value == 'none': return items #was a list already passed in? if not isinstance(option_value, list): values = option_value.split(',') else: values = option_value for value in values: # sometimes the bigip just likes a plain ol list of items if item_kind is None: items.append(value) # other times it's picky and likes key value pairs... else: items.append({'kind': item_kind, 'name': value}) return items return None
pass in an option to check for a list of items, create a list of dictionary of items to set for this option
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L107-L135
null
# -*- coding: utf-8 -*- ''' An execution module which can manipulate an f5 bigip via iControl REST :maturity: develop :platform: f5_bigip_11.6 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.utils.json # Import third party libs try: import requests import requests.exceptions HAS_LIBS = True except ImportError: HAS_LIBS = False # Import 3rd-party libs from salt.ext import six # Import salt libs import salt.exceptions # Define the module's virtual name __virtualname__ = 'bigip' def __virtual__(): ''' Only return if requests is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The bigip execution module cannot be loaded: ' 'python requests library not available.') BIG_IP_URL_BASE = 'https://{host}/mgmt/tm' def _build_session(username, password, trans_label=None): ''' Create a session to be used when connecting to iControl REST. ''' bigip = requests.session() bigip.auth = (username, password) bigip.verify = False bigip.headers.update({'Content-Type': 'application/json'}) if trans_label: #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label)) if trans_id: bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id}) else: bigip.headers.update({'X-F5-REST-Coordination-Id': None}) return bigip def _load_response(response): ''' Load the response from json data, return the dictionary or raw text ''' try: data = salt.utils.json.loads(response.text) except ValueError: data = response.text ret = {'code': response.status_code, 'content': data} return ret def _load_connection_error(hostname, error): ''' Format and Return a connection error ''' ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\n{error}'.format(host=hostname, error=error)} return ret def _loop_payload(params): ''' Pass in a dictionary of parameters, loop through them and build a payload containing, parameters who's values are not None. ''' #construct the payload payload = {} #set the payload for param, value in six.iteritems(params): if value is not None: payload[param] = value return payload def _determine_toggles(payload, toggles): ''' BigIP can't make up its mind if it likes yes / no or true or false. Figure out what it likes to hear without confusing the user. ''' for toggle, definition in six.iteritems(toggles): #did the user specify anything? if definition['value'] is not None: #test for yes_no toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no': payload[toggle] = 'yes' elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no': payload[toggle] = 'no' #test for true_false toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false': payload[toggle] = True elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false': payload[toggle] = False return payload def _set_value(value): ''' A function to detect if user is trying to pass a dictionary or list. parse it and return a dictionary list or a string ''' #don't continue if already an acceptable data-type if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list): return value #check if json if value.startswith('j{') and value.endswith('}j'): value = value.replace('j{', '{') value = value.replace('}j', '}') try: return salt.utils.json.loads(value) except Exception: raise salt.exceptions.CommandExecutionError #detect list of dictionaries if '|' in value and r'\|' not in value: values = value.split('|') items = [] for value in values: items.append(_set_value(value)) return items #parse out dictionary if detected if ':' in value and r'\:' not in value: options = {} #split out pairs key_pairs = value.split(',') for key_pair in key_pairs: k = key_pair.split(':')[0] v = key_pair.split(':')[1] options[k] = v return options #try making a list elif ',' in value and r'\,' not in value: value_items = value.split(',') return value_items #just return a string else: #remove escape chars if added if r'\|' in value: value = value.replace(r'\|', '|') if r'\:' in value: value = value.replace(r'\:', ':') if r'\,' in value: value = value.replace(r'\,', ',') return value def start_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and start a new transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The name / alias for this transaction. The actual transaction id will be stored within a grain called ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.start_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) payload = {} #post to REST to get trans id try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/transaction', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) #extract the trans_id data = _load_response(response) if data['code'] == 200: trans_id = data['content']['transId'] __salt__['grains.setval']('bigip_f5_trans', {label: trans_id}) return 'Transaction: {trans_id} - has successfully been stored in the grain: bigip_f5_trans:{label}'.format(trans_id=trans_id, label=label) else: return data def list_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and list an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #post to REST to get trans id try: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}/commands'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def commit_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and commit an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.commit_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: payload = {} payload['state'] = 'VALIDATING' #patch to REST to get trans id try: response = bigip_session.patch( BIG_IP_URL_BASE.format(host=hostname) + '/transaction/{trans_id}'.format(trans_id=trans_id), data=salt.utils.json.dumps(payload) ) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def delete_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and delete an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #patch to REST to get trans id try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def list_node(hostname, username, password, name=None, trans_label=None): ''' A function to connect to a bigip device and list all nodes or a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to list. If no name is specified than all nodes will be listed. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_node bigip admin admin my-node ''' #build sessions bigip_session = _build_session(username, password, trans_label) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_node(hostname, username, password, name, address, trans_label=None): ''' A function to connect to a bigip device and create a node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node address The address of the node trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.create_node bigip admin admin 10.1.1.2 ''' #build session bigip_session = _build_session(username, password, trans_label) #construct the payload payload = {} payload['name'] = name payload['address'] = address #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node', data=salt.utils.json.dumps(payload)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_node(hostname, username, password, name, connection_limit=None, description=None, dynamic_ratio=None, logging=None, monitor=None, rate_limit=None, ratio=None, session=None, state=None, trans_label=None): ''' A function to connect to a bigip device and modify an existing node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to modify connection_limit [integer] description [string] dynamic_ratio [integer] logging [enabled | disabled] monitor [[name] | none | default] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [user-down | user-up ] trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.modify_node bigip admin admin 10.1.1.2 ratio=2 logging=enabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'logging': logging, 'monitor': monitor, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state, } #build session bigip_session = _build_session(username, password, trans_label) #build payload payload = _loop_payload(params) payload['name'] = name #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_node(hostname, username, password, name, trans_label=None): ''' A function to connect to a bigip device and delete a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node which will be deleted. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_node bigip admin admin my-node ''' #build session bigip_session = _build_session(username, password, trans_label) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_pool(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all pools or a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to list. If no name is specified then all pools will be listed. CLI Example:: salt '*' bigip.list_pool bigip admin admin my-pool ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_pool(hostname, username, password, name, members=None, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and create a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to create. members List of comma delimited pool members to add to the pool. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [enabled | disabled] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_depth_limit [integer] queue_on_connection_limit [enabled | disabled] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.create_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 monitor=http ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up-members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify members if provided if members is not None: payload['members'] = _build_list(members, 'ltm:pool:members') #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool(hostname, username, password, name, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and modify an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify. allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [yes | no] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_on_connection_limit [enabled | disabled] queue_depth_limit [integer] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.modify_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 min_active_members=1 ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up_members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool which will be deleted CLI Example:: salt '*' bigip.delete_node bigip admin admin my-pool ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def replace_pool_members(hostname, username, password, name, members): ''' A function to connect to a bigip device and replace members of an existing pool with new members. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify members List of comma delimited pool members to replace existing members with. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 CLI Example:: salt '*' bigip.replace_pool_members bigip admin admin my-pool 10.2.2.1:80,10.2.2.2:80,10.2.2.3:80 ''' payload = {} payload['name'] = name #specify members if provided if members is not None: if isinstance(members, six.string_types): members = members.split(',') pool_members = [] for member in members: #check to see if already a dictionary ( for states) if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) pool_members.append(member) #parse string passed via execution command (for executions) else: pool_members.append({'name': member, 'address': member.split(':')[0]}) payload['members'] = pool_members #build session bigip_session = _build_session(username, password) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def add_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and add a new member to an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to add i.e. 10.1.1.2:80 CLI Example: .. code-block:: bash salt '*' bigip.add_pool_members bigip admin admin my-pool 10.2.2.1:80 ''' # for states if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) payload = member # for execution else: payload = {'name': member, 'address': member.split(':')[0]} #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool_member(hostname, username, password, name, member, connection_limit=None, description=None, dynamic_ratio=None, inherit_profile=None, logging=None, monitor=None, priority_group=None, profiles=None, rate_limit=None, ratio=None, session=None, state=None): ''' A function to connect to a bigip device and modify an existing member of a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to modify i.e. 10.1.1.2:80 connection_limit [integer] description [string] dynamic_ratio [integer] inherit_profile [enabled | disabled] logging [enabled | disabled] monitor [name] priority_group [integer] profiles [none | profile_name] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [ user-up | user-down ] CLI Example:: salt '*' bigip.modify_pool_member bigip admin admin my-pool 10.2.2.1:80 state=use-down session=user-disabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'inherit-profile': inherit_profile, 'logging': logging, 'monitor': monitor, 'priority-group': priority_group, 'profiles': profiles, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members/{member}'.format(name=name, member=member), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the pool member to delete CLI Example:: salt '*' bigip.delete_pool_member bigip admin admin my-pool 10.2.2.2:80 ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/members/{member}'.format(name=name, member=member)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_virtual(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all virtuals or a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to list. If no name is specified than all virtuals will be listed. CLI Example:: salt '*' bigip.list_virtual bigip admin admin my-virtual ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_virtual(hostname, username, password, name, destination, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): r''' A function to connect to a bigip device and create a virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to create destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no] connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limit_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limitçsrc [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disabled] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Examples:: salt '*' bigip.create_virtual bigip admin admin my-virtual-3 26.2.2.5:80 \ pool=my-http-pool-http profiles=http,tcp salt '*' bigip.create_virtual bigip admin admin my-virtual-3 43.2.2.5:80 \ pool=test-http-pool-http profiles=http,websecurity persist=cookie,hash \ policies=asm_auto_l7_policy__http-virtual \ rules=_sys_APM_ExchangeSupport_helper,_sys_https_redirect \ related_rules=_sys_APM_activesync,_sys_APM_ExchangeSupport_helper \ source_address_translation=snat:my-snat-pool \ translate_address=enabled translate_port=enabled \ traffic_classes=my-class,other-class \ vlans=enabled:external,internal ''' params = { 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name payload['destination'] = destination #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: #check to see if this is already a dictionary first if isinstance(source_address_translation, dict): payload['source-address-translation'] = source_address_translation elif source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif isinstance(vlans, six.string_types) and (vlans.startswith('enabled') or vlans.startswith('disabled')): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) else: return 'Error: vlans must be a dictionary or string.' #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_virtual(hostname, username, password, name, destination=None, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): ''' A function to connect to a bigip device and modify an existing virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to modify destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no} connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limitr_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limit_src [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disable] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Example:: salt '*' bigip.modify_virtual bigip admin admin my-virtual source_address_translation=none salt '*' bigip.modify_virtual bigip admin admin my-virtual rules=my-rule,my-other-rule ''' params = { 'destination': destination, 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: if source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif vlans.startswith('enabled') or vlans.startswith('disabled'): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_virtual(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to delete CLI Example:: salt '*' bigip.delete_virtual bigip admin admin my-virtual ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_monitor(hostname, username, password, monitor_type, name=None, ): ''' A function to connect to a bigip device and list an existing monitor. If no name is provided than all monitors of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor(s) to list name The name of the monitor to list CLI Example:: salt '*' bigip.list_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}?expandSubcollections=true'.format(type=monitor_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}'.format(type=monitor_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and create a monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to create name The name of the monitor to create kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.create_monitor bigip admin admin http my-http-monitor timeout=10 interval=5 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type']: key = key.replace('_', '-') payload[key] = value #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}'.format(type=monitor_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and modify an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to modify name The name of the monitor to modify kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.modify_monitor bigip admin admin http my-http-monitor timout=16 interval=6 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type', 'name']: key = key.replace('_', '-') payload[key] = value #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_monitor(hostname, username, password, monitor_type, name): ''' A function to connect to a bigip device and delete an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to delete name The name of the monitor to delete CLI Example:: salt '*' bigip.delete_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_profile(hostname, username, password, profile_type, name=None, ): ''' A function to connect to a bigip device and list an existing profile. If no name is provided than all profiles of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile(s) to list name The name of the profile to list CLI Example:: salt '*' bigip.list_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}?expandSubcollections=true'.format(type=profile_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}'.format(type=profile_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}'.format(type=profile_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 salt '*' bigip.modify_profile bigip admin admin client-ssl my-client-ssl-1 retainCertificate=false \ ciphers='DEFAULT\:!SSLv3' cert_key_chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j' ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}/{name}'.format(type=profile_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_profile(hostname, username, password, profile_type, name): ''' A function to connect to a bigip device and delete an existing profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to delete name The name of the profile to delete CLI Example:: salt '*' bigip.delete_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}'.format(type=profile_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response)
saltstack/salt
salt/modules/bigip.py
_determine_toggles
python
def _determine_toggles(payload, toggles): ''' BigIP can't make up its mind if it likes yes / no or true or false. Figure out what it likes to hear without confusing the user. ''' for toggle, definition in six.iteritems(toggles): #did the user specify anything? if definition['value'] is not None: #test for yes_no toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no': payload[toggle] = 'yes' elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no': payload[toggle] = 'no' #test for true_false toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false': payload[toggle] = True elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false': payload[toggle] = False return payload
BigIP can't make up its mind if it likes yes / no or true or false. Figure out what it likes to hear without confusing the user.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L138-L159
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
# -*- coding: utf-8 -*- ''' An execution module which can manipulate an f5 bigip via iControl REST :maturity: develop :platform: f5_bigip_11.6 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.utils.json # Import third party libs try: import requests import requests.exceptions HAS_LIBS = True except ImportError: HAS_LIBS = False # Import 3rd-party libs from salt.ext import six # Import salt libs import salt.exceptions # Define the module's virtual name __virtualname__ = 'bigip' def __virtual__(): ''' Only return if requests is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The bigip execution module cannot be loaded: ' 'python requests library not available.') BIG_IP_URL_BASE = 'https://{host}/mgmt/tm' def _build_session(username, password, trans_label=None): ''' Create a session to be used when connecting to iControl REST. ''' bigip = requests.session() bigip.auth = (username, password) bigip.verify = False bigip.headers.update({'Content-Type': 'application/json'}) if trans_label: #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label)) if trans_id: bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id}) else: bigip.headers.update({'X-F5-REST-Coordination-Id': None}) return bigip def _load_response(response): ''' Load the response from json data, return the dictionary or raw text ''' try: data = salt.utils.json.loads(response.text) except ValueError: data = response.text ret = {'code': response.status_code, 'content': data} return ret def _load_connection_error(hostname, error): ''' Format and Return a connection error ''' ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\n{error}'.format(host=hostname, error=error)} return ret def _loop_payload(params): ''' Pass in a dictionary of parameters, loop through them and build a payload containing, parameters who's values are not None. ''' #construct the payload payload = {} #set the payload for param, value in six.iteritems(params): if value is not None: payload[param] = value return payload def _build_list(option_value, item_kind): ''' pass in an option to check for a list of items, create a list of dictionary of items to set for this option ''' #specify profiles if provided if option_value is not None: items = [] #if user specified none, return an empty list if option_value == 'none': return items #was a list already passed in? if not isinstance(option_value, list): values = option_value.split(',') else: values = option_value for value in values: # sometimes the bigip just likes a plain ol list of items if item_kind is None: items.append(value) # other times it's picky and likes key value pairs... else: items.append({'kind': item_kind, 'name': value}) return items return None def _set_value(value): ''' A function to detect if user is trying to pass a dictionary or list. parse it and return a dictionary list or a string ''' #don't continue if already an acceptable data-type if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list): return value #check if json if value.startswith('j{') and value.endswith('}j'): value = value.replace('j{', '{') value = value.replace('}j', '}') try: return salt.utils.json.loads(value) except Exception: raise salt.exceptions.CommandExecutionError #detect list of dictionaries if '|' in value and r'\|' not in value: values = value.split('|') items = [] for value in values: items.append(_set_value(value)) return items #parse out dictionary if detected if ':' in value and r'\:' not in value: options = {} #split out pairs key_pairs = value.split(',') for key_pair in key_pairs: k = key_pair.split(':')[0] v = key_pair.split(':')[1] options[k] = v return options #try making a list elif ',' in value and r'\,' not in value: value_items = value.split(',') return value_items #just return a string else: #remove escape chars if added if r'\|' in value: value = value.replace(r'\|', '|') if r'\:' in value: value = value.replace(r'\:', ':') if r'\,' in value: value = value.replace(r'\,', ',') return value def start_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and start a new transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The name / alias for this transaction. The actual transaction id will be stored within a grain called ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.start_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) payload = {} #post to REST to get trans id try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/transaction', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) #extract the trans_id data = _load_response(response) if data['code'] == 200: trans_id = data['content']['transId'] __salt__['grains.setval']('bigip_f5_trans', {label: trans_id}) return 'Transaction: {trans_id} - has successfully been stored in the grain: bigip_f5_trans:{label}'.format(trans_id=trans_id, label=label) else: return data def list_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and list an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #post to REST to get trans id try: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}/commands'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def commit_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and commit an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.commit_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: payload = {} payload['state'] = 'VALIDATING' #patch to REST to get trans id try: response = bigip_session.patch( BIG_IP_URL_BASE.format(host=hostname) + '/transaction/{trans_id}'.format(trans_id=trans_id), data=salt.utils.json.dumps(payload) ) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def delete_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and delete an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #patch to REST to get trans id try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def list_node(hostname, username, password, name=None, trans_label=None): ''' A function to connect to a bigip device and list all nodes or a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to list. If no name is specified than all nodes will be listed. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_node bigip admin admin my-node ''' #build sessions bigip_session = _build_session(username, password, trans_label) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_node(hostname, username, password, name, address, trans_label=None): ''' A function to connect to a bigip device and create a node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node address The address of the node trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.create_node bigip admin admin 10.1.1.2 ''' #build session bigip_session = _build_session(username, password, trans_label) #construct the payload payload = {} payload['name'] = name payload['address'] = address #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node', data=salt.utils.json.dumps(payload)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_node(hostname, username, password, name, connection_limit=None, description=None, dynamic_ratio=None, logging=None, monitor=None, rate_limit=None, ratio=None, session=None, state=None, trans_label=None): ''' A function to connect to a bigip device and modify an existing node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to modify connection_limit [integer] description [string] dynamic_ratio [integer] logging [enabled | disabled] monitor [[name] | none | default] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [user-down | user-up ] trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.modify_node bigip admin admin 10.1.1.2 ratio=2 logging=enabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'logging': logging, 'monitor': monitor, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state, } #build session bigip_session = _build_session(username, password, trans_label) #build payload payload = _loop_payload(params) payload['name'] = name #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_node(hostname, username, password, name, trans_label=None): ''' A function to connect to a bigip device and delete a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node which will be deleted. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_node bigip admin admin my-node ''' #build session bigip_session = _build_session(username, password, trans_label) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_pool(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all pools or a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to list. If no name is specified then all pools will be listed. CLI Example:: salt '*' bigip.list_pool bigip admin admin my-pool ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_pool(hostname, username, password, name, members=None, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and create a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to create. members List of comma delimited pool members to add to the pool. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [enabled | disabled] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_depth_limit [integer] queue_on_connection_limit [enabled | disabled] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.create_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 monitor=http ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up-members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify members if provided if members is not None: payload['members'] = _build_list(members, 'ltm:pool:members') #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool(hostname, username, password, name, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and modify an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify. allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [yes | no] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_on_connection_limit [enabled | disabled] queue_depth_limit [integer] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.modify_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 min_active_members=1 ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up_members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool which will be deleted CLI Example:: salt '*' bigip.delete_node bigip admin admin my-pool ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def replace_pool_members(hostname, username, password, name, members): ''' A function to connect to a bigip device and replace members of an existing pool with new members. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify members List of comma delimited pool members to replace existing members with. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 CLI Example:: salt '*' bigip.replace_pool_members bigip admin admin my-pool 10.2.2.1:80,10.2.2.2:80,10.2.2.3:80 ''' payload = {} payload['name'] = name #specify members if provided if members is not None: if isinstance(members, six.string_types): members = members.split(',') pool_members = [] for member in members: #check to see if already a dictionary ( for states) if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) pool_members.append(member) #parse string passed via execution command (for executions) else: pool_members.append({'name': member, 'address': member.split(':')[0]}) payload['members'] = pool_members #build session bigip_session = _build_session(username, password) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def add_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and add a new member to an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to add i.e. 10.1.1.2:80 CLI Example: .. code-block:: bash salt '*' bigip.add_pool_members bigip admin admin my-pool 10.2.2.1:80 ''' # for states if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) payload = member # for execution else: payload = {'name': member, 'address': member.split(':')[0]} #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool_member(hostname, username, password, name, member, connection_limit=None, description=None, dynamic_ratio=None, inherit_profile=None, logging=None, monitor=None, priority_group=None, profiles=None, rate_limit=None, ratio=None, session=None, state=None): ''' A function to connect to a bigip device and modify an existing member of a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to modify i.e. 10.1.1.2:80 connection_limit [integer] description [string] dynamic_ratio [integer] inherit_profile [enabled | disabled] logging [enabled | disabled] monitor [name] priority_group [integer] profiles [none | profile_name] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [ user-up | user-down ] CLI Example:: salt '*' bigip.modify_pool_member bigip admin admin my-pool 10.2.2.1:80 state=use-down session=user-disabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'inherit-profile': inherit_profile, 'logging': logging, 'monitor': monitor, 'priority-group': priority_group, 'profiles': profiles, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members/{member}'.format(name=name, member=member), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the pool member to delete CLI Example:: salt '*' bigip.delete_pool_member bigip admin admin my-pool 10.2.2.2:80 ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/members/{member}'.format(name=name, member=member)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_virtual(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all virtuals or a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to list. If no name is specified than all virtuals will be listed. CLI Example:: salt '*' bigip.list_virtual bigip admin admin my-virtual ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_virtual(hostname, username, password, name, destination, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): r''' A function to connect to a bigip device and create a virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to create destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no] connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limit_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limitçsrc [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disabled] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Examples:: salt '*' bigip.create_virtual bigip admin admin my-virtual-3 26.2.2.5:80 \ pool=my-http-pool-http profiles=http,tcp salt '*' bigip.create_virtual bigip admin admin my-virtual-3 43.2.2.5:80 \ pool=test-http-pool-http profiles=http,websecurity persist=cookie,hash \ policies=asm_auto_l7_policy__http-virtual \ rules=_sys_APM_ExchangeSupport_helper,_sys_https_redirect \ related_rules=_sys_APM_activesync,_sys_APM_ExchangeSupport_helper \ source_address_translation=snat:my-snat-pool \ translate_address=enabled translate_port=enabled \ traffic_classes=my-class,other-class \ vlans=enabled:external,internal ''' params = { 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name payload['destination'] = destination #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: #check to see if this is already a dictionary first if isinstance(source_address_translation, dict): payload['source-address-translation'] = source_address_translation elif source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif isinstance(vlans, six.string_types) and (vlans.startswith('enabled') or vlans.startswith('disabled')): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) else: return 'Error: vlans must be a dictionary or string.' #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_virtual(hostname, username, password, name, destination=None, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): ''' A function to connect to a bigip device and modify an existing virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to modify destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no} connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limitr_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limit_src [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disable] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Example:: salt '*' bigip.modify_virtual bigip admin admin my-virtual source_address_translation=none salt '*' bigip.modify_virtual bigip admin admin my-virtual rules=my-rule,my-other-rule ''' params = { 'destination': destination, 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: if source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif vlans.startswith('enabled') or vlans.startswith('disabled'): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_virtual(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to delete CLI Example:: salt '*' bigip.delete_virtual bigip admin admin my-virtual ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_monitor(hostname, username, password, monitor_type, name=None, ): ''' A function to connect to a bigip device and list an existing monitor. If no name is provided than all monitors of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor(s) to list name The name of the monitor to list CLI Example:: salt '*' bigip.list_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}?expandSubcollections=true'.format(type=monitor_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}'.format(type=monitor_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and create a monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to create name The name of the monitor to create kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.create_monitor bigip admin admin http my-http-monitor timeout=10 interval=5 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type']: key = key.replace('_', '-') payload[key] = value #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}'.format(type=monitor_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and modify an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to modify name The name of the monitor to modify kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.modify_monitor bigip admin admin http my-http-monitor timout=16 interval=6 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type', 'name']: key = key.replace('_', '-') payload[key] = value #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_monitor(hostname, username, password, monitor_type, name): ''' A function to connect to a bigip device and delete an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to delete name The name of the monitor to delete CLI Example:: salt '*' bigip.delete_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_profile(hostname, username, password, profile_type, name=None, ): ''' A function to connect to a bigip device and list an existing profile. If no name is provided than all profiles of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile(s) to list name The name of the profile to list CLI Example:: salt '*' bigip.list_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}?expandSubcollections=true'.format(type=profile_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}'.format(type=profile_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}'.format(type=profile_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 salt '*' bigip.modify_profile bigip admin admin client-ssl my-client-ssl-1 retainCertificate=false \ ciphers='DEFAULT\:!SSLv3' cert_key_chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j' ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}/{name}'.format(type=profile_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_profile(hostname, username, password, profile_type, name): ''' A function to connect to a bigip device and delete an existing profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to delete name The name of the profile to delete CLI Example:: salt '*' bigip.delete_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}'.format(type=profile_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response)
saltstack/salt
salt/modules/bigip.py
_set_value
python
def _set_value(value): ''' A function to detect if user is trying to pass a dictionary or list. parse it and return a dictionary list or a string ''' #don't continue if already an acceptable data-type if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list): return value #check if json if value.startswith('j{') and value.endswith('}j'): value = value.replace('j{', '{') value = value.replace('}j', '}') try: return salt.utils.json.loads(value) except Exception: raise salt.exceptions.CommandExecutionError #detect list of dictionaries if '|' in value and r'\|' not in value: values = value.split('|') items = [] for value in values: items.append(_set_value(value)) return items #parse out dictionary if detected if ':' in value and r'\:' not in value: options = {} #split out pairs key_pairs = value.split(',') for key_pair in key_pairs: k = key_pair.split(':')[0] v = key_pair.split(':')[1] options[k] = v return options #try making a list elif ',' in value and r'\,' not in value: value_items = value.split(',') return value_items #just return a string else: #remove escape chars if added if r'\|' in value: value = value.replace(r'\|', '|') if r'\:' in value: value = value.replace(r'\:', ':') if r'\,' in value: value = value.replace(r'\,', ',') return value
A function to detect if user is trying to pass a dictionary or list. parse it and return a dictionary list or a string
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L162-L219
[ "def _set_value(value):\n '''\n A function to detect if user is trying to pass a dictionary or list. parse it and return a\n dictionary list or a string\n '''\n #don't continue if already an acceptable data-type\n if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list):\n return value\n\n #check if json\n if value.startswith('j{') and value.endswith('}j'):\n\n value = value.replace('j{', '{')\n value = value.replace('}j', '}')\n\n try:\n return salt.utils.json.loads(value)\n except Exception:\n raise salt.exceptions.CommandExecutionError\n\n #detect list of dictionaries\n if '|' in value and r'\\|' not in value:\n values = value.split('|')\n items = []\n for value in values:\n items.append(_set_value(value))\n return items\n\n #parse out dictionary if detected\n if ':' in value and r'\\:' not in value:\n options = {}\n #split out pairs\n key_pairs = value.split(',')\n for key_pair in key_pairs:\n k = key_pair.split(':')[0]\n v = key_pair.split(':')[1]\n options[k] = v\n return options\n\n #try making a list\n elif ',' in value and r'\\,' not in value:\n value_items = value.split(',')\n return value_items\n\n #just return a string\n else:\n\n #remove escape chars if added\n if r'\\|' in value:\n value = value.replace(r'\\|', '|')\n\n if r'\\:' in value:\n value = value.replace(r'\\:', ':')\n\n if r'\\,' in value:\n value = value.replace(r'\\,', ',')\n\n return value\n" ]
# -*- coding: utf-8 -*- ''' An execution module which can manipulate an f5 bigip via iControl REST :maturity: develop :platform: f5_bigip_11.6 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.utils.json # Import third party libs try: import requests import requests.exceptions HAS_LIBS = True except ImportError: HAS_LIBS = False # Import 3rd-party libs from salt.ext import six # Import salt libs import salt.exceptions # Define the module's virtual name __virtualname__ = 'bigip' def __virtual__(): ''' Only return if requests is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The bigip execution module cannot be loaded: ' 'python requests library not available.') BIG_IP_URL_BASE = 'https://{host}/mgmt/tm' def _build_session(username, password, trans_label=None): ''' Create a session to be used when connecting to iControl REST. ''' bigip = requests.session() bigip.auth = (username, password) bigip.verify = False bigip.headers.update({'Content-Type': 'application/json'}) if trans_label: #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label)) if trans_id: bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id}) else: bigip.headers.update({'X-F5-REST-Coordination-Id': None}) return bigip def _load_response(response): ''' Load the response from json data, return the dictionary or raw text ''' try: data = salt.utils.json.loads(response.text) except ValueError: data = response.text ret = {'code': response.status_code, 'content': data} return ret def _load_connection_error(hostname, error): ''' Format and Return a connection error ''' ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\n{error}'.format(host=hostname, error=error)} return ret def _loop_payload(params): ''' Pass in a dictionary of parameters, loop through them and build a payload containing, parameters who's values are not None. ''' #construct the payload payload = {} #set the payload for param, value in six.iteritems(params): if value is not None: payload[param] = value return payload def _build_list(option_value, item_kind): ''' pass in an option to check for a list of items, create a list of dictionary of items to set for this option ''' #specify profiles if provided if option_value is not None: items = [] #if user specified none, return an empty list if option_value == 'none': return items #was a list already passed in? if not isinstance(option_value, list): values = option_value.split(',') else: values = option_value for value in values: # sometimes the bigip just likes a plain ol list of items if item_kind is None: items.append(value) # other times it's picky and likes key value pairs... else: items.append({'kind': item_kind, 'name': value}) return items return None def _determine_toggles(payload, toggles): ''' BigIP can't make up its mind if it likes yes / no or true or false. Figure out what it likes to hear without confusing the user. ''' for toggle, definition in six.iteritems(toggles): #did the user specify anything? if definition['value'] is not None: #test for yes_no toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no': payload[toggle] = 'yes' elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no': payload[toggle] = 'no' #test for true_false toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false': payload[toggle] = True elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false': payload[toggle] = False return payload def start_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and start a new transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The name / alias for this transaction. The actual transaction id will be stored within a grain called ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.start_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) payload = {} #post to REST to get trans id try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/transaction', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) #extract the trans_id data = _load_response(response) if data['code'] == 200: trans_id = data['content']['transId'] __salt__['grains.setval']('bigip_f5_trans', {label: trans_id}) return 'Transaction: {trans_id} - has successfully been stored in the grain: bigip_f5_trans:{label}'.format(trans_id=trans_id, label=label) else: return data def list_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and list an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #post to REST to get trans id try: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}/commands'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def commit_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and commit an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.commit_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: payload = {} payload['state'] = 'VALIDATING' #patch to REST to get trans id try: response = bigip_session.patch( BIG_IP_URL_BASE.format(host=hostname) + '/transaction/{trans_id}'.format(trans_id=trans_id), data=salt.utils.json.dumps(payload) ) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def delete_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and delete an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #patch to REST to get trans id try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def list_node(hostname, username, password, name=None, trans_label=None): ''' A function to connect to a bigip device and list all nodes or a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to list. If no name is specified than all nodes will be listed. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_node bigip admin admin my-node ''' #build sessions bigip_session = _build_session(username, password, trans_label) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_node(hostname, username, password, name, address, trans_label=None): ''' A function to connect to a bigip device and create a node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node address The address of the node trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.create_node bigip admin admin 10.1.1.2 ''' #build session bigip_session = _build_session(username, password, trans_label) #construct the payload payload = {} payload['name'] = name payload['address'] = address #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node', data=salt.utils.json.dumps(payload)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_node(hostname, username, password, name, connection_limit=None, description=None, dynamic_ratio=None, logging=None, monitor=None, rate_limit=None, ratio=None, session=None, state=None, trans_label=None): ''' A function to connect to a bigip device and modify an existing node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to modify connection_limit [integer] description [string] dynamic_ratio [integer] logging [enabled | disabled] monitor [[name] | none | default] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [user-down | user-up ] trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.modify_node bigip admin admin 10.1.1.2 ratio=2 logging=enabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'logging': logging, 'monitor': monitor, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state, } #build session bigip_session = _build_session(username, password, trans_label) #build payload payload = _loop_payload(params) payload['name'] = name #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_node(hostname, username, password, name, trans_label=None): ''' A function to connect to a bigip device and delete a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node which will be deleted. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_node bigip admin admin my-node ''' #build session bigip_session = _build_session(username, password, trans_label) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_pool(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all pools or a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to list. If no name is specified then all pools will be listed. CLI Example:: salt '*' bigip.list_pool bigip admin admin my-pool ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_pool(hostname, username, password, name, members=None, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and create a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to create. members List of comma delimited pool members to add to the pool. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [enabled | disabled] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_depth_limit [integer] queue_on_connection_limit [enabled | disabled] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.create_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 monitor=http ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up-members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify members if provided if members is not None: payload['members'] = _build_list(members, 'ltm:pool:members') #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool(hostname, username, password, name, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and modify an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify. allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [yes | no] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_on_connection_limit [enabled | disabled] queue_depth_limit [integer] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.modify_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 min_active_members=1 ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up_members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool which will be deleted CLI Example:: salt '*' bigip.delete_node bigip admin admin my-pool ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def replace_pool_members(hostname, username, password, name, members): ''' A function to connect to a bigip device and replace members of an existing pool with new members. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify members List of comma delimited pool members to replace existing members with. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 CLI Example:: salt '*' bigip.replace_pool_members bigip admin admin my-pool 10.2.2.1:80,10.2.2.2:80,10.2.2.3:80 ''' payload = {} payload['name'] = name #specify members if provided if members is not None: if isinstance(members, six.string_types): members = members.split(',') pool_members = [] for member in members: #check to see if already a dictionary ( for states) if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) pool_members.append(member) #parse string passed via execution command (for executions) else: pool_members.append({'name': member, 'address': member.split(':')[0]}) payload['members'] = pool_members #build session bigip_session = _build_session(username, password) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def add_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and add a new member to an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to add i.e. 10.1.1.2:80 CLI Example: .. code-block:: bash salt '*' bigip.add_pool_members bigip admin admin my-pool 10.2.2.1:80 ''' # for states if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) payload = member # for execution else: payload = {'name': member, 'address': member.split(':')[0]} #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool_member(hostname, username, password, name, member, connection_limit=None, description=None, dynamic_ratio=None, inherit_profile=None, logging=None, monitor=None, priority_group=None, profiles=None, rate_limit=None, ratio=None, session=None, state=None): ''' A function to connect to a bigip device and modify an existing member of a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to modify i.e. 10.1.1.2:80 connection_limit [integer] description [string] dynamic_ratio [integer] inherit_profile [enabled | disabled] logging [enabled | disabled] monitor [name] priority_group [integer] profiles [none | profile_name] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [ user-up | user-down ] CLI Example:: salt '*' bigip.modify_pool_member bigip admin admin my-pool 10.2.2.1:80 state=use-down session=user-disabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'inherit-profile': inherit_profile, 'logging': logging, 'monitor': monitor, 'priority-group': priority_group, 'profiles': profiles, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members/{member}'.format(name=name, member=member), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the pool member to delete CLI Example:: salt '*' bigip.delete_pool_member bigip admin admin my-pool 10.2.2.2:80 ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/members/{member}'.format(name=name, member=member)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_virtual(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all virtuals or a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to list. If no name is specified than all virtuals will be listed. CLI Example:: salt '*' bigip.list_virtual bigip admin admin my-virtual ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_virtual(hostname, username, password, name, destination, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): r''' A function to connect to a bigip device and create a virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to create destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no] connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limit_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limitçsrc [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disabled] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Examples:: salt '*' bigip.create_virtual bigip admin admin my-virtual-3 26.2.2.5:80 \ pool=my-http-pool-http profiles=http,tcp salt '*' bigip.create_virtual bigip admin admin my-virtual-3 43.2.2.5:80 \ pool=test-http-pool-http profiles=http,websecurity persist=cookie,hash \ policies=asm_auto_l7_policy__http-virtual \ rules=_sys_APM_ExchangeSupport_helper,_sys_https_redirect \ related_rules=_sys_APM_activesync,_sys_APM_ExchangeSupport_helper \ source_address_translation=snat:my-snat-pool \ translate_address=enabled translate_port=enabled \ traffic_classes=my-class,other-class \ vlans=enabled:external,internal ''' params = { 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name payload['destination'] = destination #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: #check to see if this is already a dictionary first if isinstance(source_address_translation, dict): payload['source-address-translation'] = source_address_translation elif source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif isinstance(vlans, six.string_types) and (vlans.startswith('enabled') or vlans.startswith('disabled')): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) else: return 'Error: vlans must be a dictionary or string.' #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_virtual(hostname, username, password, name, destination=None, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): ''' A function to connect to a bigip device and modify an existing virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to modify destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no} connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limitr_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limit_src [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disable] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Example:: salt '*' bigip.modify_virtual bigip admin admin my-virtual source_address_translation=none salt '*' bigip.modify_virtual bigip admin admin my-virtual rules=my-rule,my-other-rule ''' params = { 'destination': destination, 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: if source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif vlans.startswith('enabled') or vlans.startswith('disabled'): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_virtual(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to delete CLI Example:: salt '*' bigip.delete_virtual bigip admin admin my-virtual ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_monitor(hostname, username, password, monitor_type, name=None, ): ''' A function to connect to a bigip device and list an existing monitor. If no name is provided than all monitors of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor(s) to list name The name of the monitor to list CLI Example:: salt '*' bigip.list_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}?expandSubcollections=true'.format(type=monitor_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}'.format(type=monitor_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and create a monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to create name The name of the monitor to create kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.create_monitor bigip admin admin http my-http-monitor timeout=10 interval=5 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type']: key = key.replace('_', '-') payload[key] = value #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}'.format(type=monitor_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and modify an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to modify name The name of the monitor to modify kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.modify_monitor bigip admin admin http my-http-monitor timout=16 interval=6 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type', 'name']: key = key.replace('_', '-') payload[key] = value #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_monitor(hostname, username, password, monitor_type, name): ''' A function to connect to a bigip device and delete an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to delete name The name of the monitor to delete CLI Example:: salt '*' bigip.delete_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_profile(hostname, username, password, profile_type, name=None, ): ''' A function to connect to a bigip device and list an existing profile. If no name is provided than all profiles of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile(s) to list name The name of the profile to list CLI Example:: salt '*' bigip.list_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}?expandSubcollections=true'.format(type=profile_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}'.format(type=profile_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}'.format(type=profile_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 salt '*' bigip.modify_profile bigip admin admin client-ssl my-client-ssl-1 retainCertificate=false \ ciphers='DEFAULT\:!SSLv3' cert_key_chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j' ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}/{name}'.format(type=profile_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_profile(hostname, username, password, profile_type, name): ''' A function to connect to a bigip device and delete an existing profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to delete name The name of the profile to delete CLI Example:: salt '*' bigip.delete_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}'.format(type=profile_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response)
saltstack/salt
salt/modules/bigip.py
start_transaction
python
def start_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and start a new transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The name / alias for this transaction. The actual transaction id will be stored within a grain called ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.start_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) payload = {} #post to REST to get trans id try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/transaction', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) #extract the trans_id data = _load_response(response) if data['code'] == 200: trans_id = data['content']['transId'] __salt__['grains.setval']('bigip_f5_trans', {label: trans_id}) return 'Transaction: {trans_id} - has successfully been stored in the grain: bigip_f5_trans:{label}'.format(trans_id=trans_id, label=label) else: return data
A function to connect to a bigip device and start a new transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The name / alias for this transaction. The actual transaction id will be stored within a grain called ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.start_transaction bigip admin admin my_transaction
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L222-L268
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def _build_session(username, password, trans_label=None):\n '''\n Create a session to be used when connecting to iControl REST.\n '''\n\n bigip = requests.session()\n bigip.auth = (username, password)\n bigip.verify = False\n bigip.headers.update({'Content-Type': 'application/json'})\n\n if trans_label:\n #pull the trans id from the grain\n trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label))\n\n if trans_id:\n bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id})\n else:\n bigip.headers.update({'X-F5-REST-Coordination-Id': None})\n\n return bigip\n", "def _load_response(response):\n '''\n Load the response from json data, return the dictionary or raw text\n '''\n\n try:\n data = salt.utils.json.loads(response.text)\n except ValueError:\n data = response.text\n\n ret = {'code': response.status_code, 'content': data}\n\n return ret\n", "def _load_connection_error(hostname, error):\n '''\n Format and Return a connection error\n '''\n\n ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\\n{error}'.format(host=hostname, error=error)}\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' An execution module which can manipulate an f5 bigip via iControl REST :maturity: develop :platform: f5_bigip_11.6 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.utils.json # Import third party libs try: import requests import requests.exceptions HAS_LIBS = True except ImportError: HAS_LIBS = False # Import 3rd-party libs from salt.ext import six # Import salt libs import salt.exceptions # Define the module's virtual name __virtualname__ = 'bigip' def __virtual__(): ''' Only return if requests is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The bigip execution module cannot be loaded: ' 'python requests library not available.') BIG_IP_URL_BASE = 'https://{host}/mgmt/tm' def _build_session(username, password, trans_label=None): ''' Create a session to be used when connecting to iControl REST. ''' bigip = requests.session() bigip.auth = (username, password) bigip.verify = False bigip.headers.update({'Content-Type': 'application/json'}) if trans_label: #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label)) if trans_id: bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id}) else: bigip.headers.update({'X-F5-REST-Coordination-Id': None}) return bigip def _load_response(response): ''' Load the response from json data, return the dictionary or raw text ''' try: data = salt.utils.json.loads(response.text) except ValueError: data = response.text ret = {'code': response.status_code, 'content': data} return ret def _load_connection_error(hostname, error): ''' Format and Return a connection error ''' ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\n{error}'.format(host=hostname, error=error)} return ret def _loop_payload(params): ''' Pass in a dictionary of parameters, loop through them and build a payload containing, parameters who's values are not None. ''' #construct the payload payload = {} #set the payload for param, value in six.iteritems(params): if value is not None: payload[param] = value return payload def _build_list(option_value, item_kind): ''' pass in an option to check for a list of items, create a list of dictionary of items to set for this option ''' #specify profiles if provided if option_value is not None: items = [] #if user specified none, return an empty list if option_value == 'none': return items #was a list already passed in? if not isinstance(option_value, list): values = option_value.split(',') else: values = option_value for value in values: # sometimes the bigip just likes a plain ol list of items if item_kind is None: items.append(value) # other times it's picky and likes key value pairs... else: items.append({'kind': item_kind, 'name': value}) return items return None def _determine_toggles(payload, toggles): ''' BigIP can't make up its mind if it likes yes / no or true or false. Figure out what it likes to hear without confusing the user. ''' for toggle, definition in six.iteritems(toggles): #did the user specify anything? if definition['value'] is not None: #test for yes_no toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no': payload[toggle] = 'yes' elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no': payload[toggle] = 'no' #test for true_false toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false': payload[toggle] = True elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false': payload[toggle] = False return payload def _set_value(value): ''' A function to detect if user is trying to pass a dictionary or list. parse it and return a dictionary list or a string ''' #don't continue if already an acceptable data-type if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list): return value #check if json if value.startswith('j{') and value.endswith('}j'): value = value.replace('j{', '{') value = value.replace('}j', '}') try: return salt.utils.json.loads(value) except Exception: raise salt.exceptions.CommandExecutionError #detect list of dictionaries if '|' in value and r'\|' not in value: values = value.split('|') items = [] for value in values: items.append(_set_value(value)) return items #parse out dictionary if detected if ':' in value and r'\:' not in value: options = {} #split out pairs key_pairs = value.split(',') for key_pair in key_pairs: k = key_pair.split(':')[0] v = key_pair.split(':')[1] options[k] = v return options #try making a list elif ',' in value and r'\,' not in value: value_items = value.split(',') return value_items #just return a string else: #remove escape chars if added if r'\|' in value: value = value.replace(r'\|', '|') if r'\:' in value: value = value.replace(r'\:', ':') if r'\,' in value: value = value.replace(r'\,', ',') return value def list_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and list an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #post to REST to get trans id try: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}/commands'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def commit_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and commit an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.commit_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: payload = {} payload['state'] = 'VALIDATING' #patch to REST to get trans id try: response = bigip_session.patch( BIG_IP_URL_BASE.format(host=hostname) + '/transaction/{trans_id}'.format(trans_id=trans_id), data=salt.utils.json.dumps(payload) ) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def delete_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and delete an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #patch to REST to get trans id try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def list_node(hostname, username, password, name=None, trans_label=None): ''' A function to connect to a bigip device and list all nodes or a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to list. If no name is specified than all nodes will be listed. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_node bigip admin admin my-node ''' #build sessions bigip_session = _build_session(username, password, trans_label) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_node(hostname, username, password, name, address, trans_label=None): ''' A function to connect to a bigip device and create a node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node address The address of the node trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.create_node bigip admin admin 10.1.1.2 ''' #build session bigip_session = _build_session(username, password, trans_label) #construct the payload payload = {} payload['name'] = name payload['address'] = address #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node', data=salt.utils.json.dumps(payload)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_node(hostname, username, password, name, connection_limit=None, description=None, dynamic_ratio=None, logging=None, monitor=None, rate_limit=None, ratio=None, session=None, state=None, trans_label=None): ''' A function to connect to a bigip device and modify an existing node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to modify connection_limit [integer] description [string] dynamic_ratio [integer] logging [enabled | disabled] monitor [[name] | none | default] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [user-down | user-up ] trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.modify_node bigip admin admin 10.1.1.2 ratio=2 logging=enabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'logging': logging, 'monitor': monitor, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state, } #build session bigip_session = _build_session(username, password, trans_label) #build payload payload = _loop_payload(params) payload['name'] = name #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_node(hostname, username, password, name, trans_label=None): ''' A function to connect to a bigip device and delete a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node which will be deleted. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_node bigip admin admin my-node ''' #build session bigip_session = _build_session(username, password, trans_label) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_pool(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all pools or a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to list. If no name is specified then all pools will be listed. CLI Example:: salt '*' bigip.list_pool bigip admin admin my-pool ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_pool(hostname, username, password, name, members=None, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and create a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to create. members List of comma delimited pool members to add to the pool. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [enabled | disabled] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_depth_limit [integer] queue_on_connection_limit [enabled | disabled] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.create_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 monitor=http ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up-members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify members if provided if members is not None: payload['members'] = _build_list(members, 'ltm:pool:members') #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool(hostname, username, password, name, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and modify an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify. allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [yes | no] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_on_connection_limit [enabled | disabled] queue_depth_limit [integer] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.modify_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 min_active_members=1 ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up_members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool which will be deleted CLI Example:: salt '*' bigip.delete_node bigip admin admin my-pool ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def replace_pool_members(hostname, username, password, name, members): ''' A function to connect to a bigip device and replace members of an existing pool with new members. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify members List of comma delimited pool members to replace existing members with. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 CLI Example:: salt '*' bigip.replace_pool_members bigip admin admin my-pool 10.2.2.1:80,10.2.2.2:80,10.2.2.3:80 ''' payload = {} payload['name'] = name #specify members if provided if members is not None: if isinstance(members, six.string_types): members = members.split(',') pool_members = [] for member in members: #check to see if already a dictionary ( for states) if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) pool_members.append(member) #parse string passed via execution command (for executions) else: pool_members.append({'name': member, 'address': member.split(':')[0]}) payload['members'] = pool_members #build session bigip_session = _build_session(username, password) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def add_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and add a new member to an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to add i.e. 10.1.1.2:80 CLI Example: .. code-block:: bash salt '*' bigip.add_pool_members bigip admin admin my-pool 10.2.2.1:80 ''' # for states if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) payload = member # for execution else: payload = {'name': member, 'address': member.split(':')[0]} #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool_member(hostname, username, password, name, member, connection_limit=None, description=None, dynamic_ratio=None, inherit_profile=None, logging=None, monitor=None, priority_group=None, profiles=None, rate_limit=None, ratio=None, session=None, state=None): ''' A function to connect to a bigip device and modify an existing member of a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to modify i.e. 10.1.1.2:80 connection_limit [integer] description [string] dynamic_ratio [integer] inherit_profile [enabled | disabled] logging [enabled | disabled] monitor [name] priority_group [integer] profiles [none | profile_name] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [ user-up | user-down ] CLI Example:: salt '*' bigip.modify_pool_member bigip admin admin my-pool 10.2.2.1:80 state=use-down session=user-disabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'inherit-profile': inherit_profile, 'logging': logging, 'monitor': monitor, 'priority-group': priority_group, 'profiles': profiles, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members/{member}'.format(name=name, member=member), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the pool member to delete CLI Example:: salt '*' bigip.delete_pool_member bigip admin admin my-pool 10.2.2.2:80 ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/members/{member}'.format(name=name, member=member)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_virtual(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all virtuals or a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to list. If no name is specified than all virtuals will be listed. CLI Example:: salt '*' bigip.list_virtual bigip admin admin my-virtual ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_virtual(hostname, username, password, name, destination, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): r''' A function to connect to a bigip device and create a virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to create destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no] connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limit_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limitçsrc [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disabled] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Examples:: salt '*' bigip.create_virtual bigip admin admin my-virtual-3 26.2.2.5:80 \ pool=my-http-pool-http profiles=http,tcp salt '*' bigip.create_virtual bigip admin admin my-virtual-3 43.2.2.5:80 \ pool=test-http-pool-http profiles=http,websecurity persist=cookie,hash \ policies=asm_auto_l7_policy__http-virtual \ rules=_sys_APM_ExchangeSupport_helper,_sys_https_redirect \ related_rules=_sys_APM_activesync,_sys_APM_ExchangeSupport_helper \ source_address_translation=snat:my-snat-pool \ translate_address=enabled translate_port=enabled \ traffic_classes=my-class,other-class \ vlans=enabled:external,internal ''' params = { 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name payload['destination'] = destination #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: #check to see if this is already a dictionary first if isinstance(source_address_translation, dict): payload['source-address-translation'] = source_address_translation elif source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif isinstance(vlans, six.string_types) and (vlans.startswith('enabled') or vlans.startswith('disabled')): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) else: return 'Error: vlans must be a dictionary or string.' #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_virtual(hostname, username, password, name, destination=None, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): ''' A function to connect to a bigip device and modify an existing virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to modify destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no} connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limitr_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limit_src [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disable] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Example:: salt '*' bigip.modify_virtual bigip admin admin my-virtual source_address_translation=none salt '*' bigip.modify_virtual bigip admin admin my-virtual rules=my-rule,my-other-rule ''' params = { 'destination': destination, 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: if source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif vlans.startswith('enabled') or vlans.startswith('disabled'): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_virtual(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to delete CLI Example:: salt '*' bigip.delete_virtual bigip admin admin my-virtual ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_monitor(hostname, username, password, monitor_type, name=None, ): ''' A function to connect to a bigip device and list an existing monitor. If no name is provided than all monitors of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor(s) to list name The name of the monitor to list CLI Example:: salt '*' bigip.list_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}?expandSubcollections=true'.format(type=monitor_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}'.format(type=monitor_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and create a monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to create name The name of the monitor to create kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.create_monitor bigip admin admin http my-http-monitor timeout=10 interval=5 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type']: key = key.replace('_', '-') payload[key] = value #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}'.format(type=monitor_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and modify an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to modify name The name of the monitor to modify kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.modify_monitor bigip admin admin http my-http-monitor timout=16 interval=6 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type', 'name']: key = key.replace('_', '-') payload[key] = value #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_monitor(hostname, username, password, monitor_type, name): ''' A function to connect to a bigip device and delete an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to delete name The name of the monitor to delete CLI Example:: salt '*' bigip.delete_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_profile(hostname, username, password, profile_type, name=None, ): ''' A function to connect to a bigip device and list an existing profile. If no name is provided than all profiles of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile(s) to list name The name of the profile to list CLI Example:: salt '*' bigip.list_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}?expandSubcollections=true'.format(type=profile_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}'.format(type=profile_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}'.format(type=profile_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 salt '*' bigip.modify_profile bigip admin admin client-ssl my-client-ssl-1 retainCertificate=false \ ciphers='DEFAULT\:!SSLv3' cert_key_chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j' ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}/{name}'.format(type=profile_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_profile(hostname, username, password, profile_type, name): ''' A function to connect to a bigip device and delete an existing profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to delete name The name of the profile to delete CLI Example:: salt '*' bigip.delete_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}'.format(type=profile_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response)
saltstack/salt
salt/modules/bigip.py
list_transaction
python
def list_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and list an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #post to REST to get trans id try: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}/commands'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function'
A function to connect to a bigip device and list an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_transaction bigip admin admin my_transaction
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L271-L307
[ "def _build_session(username, password, trans_label=None):\n '''\n Create a session to be used when connecting to iControl REST.\n '''\n\n bigip = requests.session()\n bigip.auth = (username, password)\n bigip.verify = False\n bigip.headers.update({'Content-Type': 'application/json'})\n\n if trans_label:\n #pull the trans id from the grain\n trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label))\n\n if trans_id:\n bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id})\n else:\n bigip.headers.update({'X-F5-REST-Coordination-Id': None})\n\n return bigip\n", "def _load_response(response):\n '''\n Load the response from json data, return the dictionary or raw text\n '''\n\n try:\n data = salt.utils.json.loads(response.text)\n except ValueError:\n data = response.text\n\n ret = {'code': response.status_code, 'content': data}\n\n return ret\n", "def _load_connection_error(hostname, error):\n '''\n Format and Return a connection error\n '''\n\n ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\\n{error}'.format(host=hostname, error=error)}\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' An execution module which can manipulate an f5 bigip via iControl REST :maturity: develop :platform: f5_bigip_11.6 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.utils.json # Import third party libs try: import requests import requests.exceptions HAS_LIBS = True except ImportError: HAS_LIBS = False # Import 3rd-party libs from salt.ext import six # Import salt libs import salt.exceptions # Define the module's virtual name __virtualname__ = 'bigip' def __virtual__(): ''' Only return if requests is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The bigip execution module cannot be loaded: ' 'python requests library not available.') BIG_IP_URL_BASE = 'https://{host}/mgmt/tm' def _build_session(username, password, trans_label=None): ''' Create a session to be used when connecting to iControl REST. ''' bigip = requests.session() bigip.auth = (username, password) bigip.verify = False bigip.headers.update({'Content-Type': 'application/json'}) if trans_label: #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label)) if trans_id: bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id}) else: bigip.headers.update({'X-F5-REST-Coordination-Id': None}) return bigip def _load_response(response): ''' Load the response from json data, return the dictionary or raw text ''' try: data = salt.utils.json.loads(response.text) except ValueError: data = response.text ret = {'code': response.status_code, 'content': data} return ret def _load_connection_error(hostname, error): ''' Format and Return a connection error ''' ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\n{error}'.format(host=hostname, error=error)} return ret def _loop_payload(params): ''' Pass in a dictionary of parameters, loop through them and build a payload containing, parameters who's values are not None. ''' #construct the payload payload = {} #set the payload for param, value in six.iteritems(params): if value is not None: payload[param] = value return payload def _build_list(option_value, item_kind): ''' pass in an option to check for a list of items, create a list of dictionary of items to set for this option ''' #specify profiles if provided if option_value is not None: items = [] #if user specified none, return an empty list if option_value == 'none': return items #was a list already passed in? if not isinstance(option_value, list): values = option_value.split(',') else: values = option_value for value in values: # sometimes the bigip just likes a plain ol list of items if item_kind is None: items.append(value) # other times it's picky and likes key value pairs... else: items.append({'kind': item_kind, 'name': value}) return items return None def _determine_toggles(payload, toggles): ''' BigIP can't make up its mind if it likes yes / no or true or false. Figure out what it likes to hear without confusing the user. ''' for toggle, definition in six.iteritems(toggles): #did the user specify anything? if definition['value'] is not None: #test for yes_no toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no': payload[toggle] = 'yes' elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no': payload[toggle] = 'no' #test for true_false toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false': payload[toggle] = True elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false': payload[toggle] = False return payload def _set_value(value): ''' A function to detect if user is trying to pass a dictionary or list. parse it and return a dictionary list or a string ''' #don't continue if already an acceptable data-type if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list): return value #check if json if value.startswith('j{') and value.endswith('}j'): value = value.replace('j{', '{') value = value.replace('}j', '}') try: return salt.utils.json.loads(value) except Exception: raise salt.exceptions.CommandExecutionError #detect list of dictionaries if '|' in value and r'\|' not in value: values = value.split('|') items = [] for value in values: items.append(_set_value(value)) return items #parse out dictionary if detected if ':' in value and r'\:' not in value: options = {} #split out pairs key_pairs = value.split(',') for key_pair in key_pairs: k = key_pair.split(':')[0] v = key_pair.split(':')[1] options[k] = v return options #try making a list elif ',' in value and r'\,' not in value: value_items = value.split(',') return value_items #just return a string else: #remove escape chars if added if r'\|' in value: value = value.replace(r'\|', '|') if r'\:' in value: value = value.replace(r'\:', ':') if r'\,' in value: value = value.replace(r'\,', ',') return value def start_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and start a new transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The name / alias for this transaction. The actual transaction id will be stored within a grain called ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.start_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) payload = {} #post to REST to get trans id try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/transaction', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) #extract the trans_id data = _load_response(response) if data['code'] == 200: trans_id = data['content']['transId'] __salt__['grains.setval']('bigip_f5_trans', {label: trans_id}) return 'Transaction: {trans_id} - has successfully been stored in the grain: bigip_f5_trans:{label}'.format(trans_id=trans_id, label=label) else: return data def commit_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and commit an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.commit_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: payload = {} payload['state'] = 'VALIDATING' #patch to REST to get trans id try: response = bigip_session.patch( BIG_IP_URL_BASE.format(host=hostname) + '/transaction/{trans_id}'.format(trans_id=trans_id), data=salt.utils.json.dumps(payload) ) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def delete_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and delete an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #patch to REST to get trans id try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def list_node(hostname, username, password, name=None, trans_label=None): ''' A function to connect to a bigip device and list all nodes or a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to list. If no name is specified than all nodes will be listed. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_node bigip admin admin my-node ''' #build sessions bigip_session = _build_session(username, password, trans_label) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_node(hostname, username, password, name, address, trans_label=None): ''' A function to connect to a bigip device and create a node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node address The address of the node trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.create_node bigip admin admin 10.1.1.2 ''' #build session bigip_session = _build_session(username, password, trans_label) #construct the payload payload = {} payload['name'] = name payload['address'] = address #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node', data=salt.utils.json.dumps(payload)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_node(hostname, username, password, name, connection_limit=None, description=None, dynamic_ratio=None, logging=None, monitor=None, rate_limit=None, ratio=None, session=None, state=None, trans_label=None): ''' A function to connect to a bigip device and modify an existing node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to modify connection_limit [integer] description [string] dynamic_ratio [integer] logging [enabled | disabled] monitor [[name] | none | default] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [user-down | user-up ] trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.modify_node bigip admin admin 10.1.1.2 ratio=2 logging=enabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'logging': logging, 'monitor': monitor, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state, } #build session bigip_session = _build_session(username, password, trans_label) #build payload payload = _loop_payload(params) payload['name'] = name #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_node(hostname, username, password, name, trans_label=None): ''' A function to connect to a bigip device and delete a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node which will be deleted. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_node bigip admin admin my-node ''' #build session bigip_session = _build_session(username, password, trans_label) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_pool(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all pools or a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to list. If no name is specified then all pools will be listed. CLI Example:: salt '*' bigip.list_pool bigip admin admin my-pool ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_pool(hostname, username, password, name, members=None, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and create a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to create. members List of comma delimited pool members to add to the pool. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [enabled | disabled] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_depth_limit [integer] queue_on_connection_limit [enabled | disabled] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.create_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 monitor=http ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up-members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify members if provided if members is not None: payload['members'] = _build_list(members, 'ltm:pool:members') #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool(hostname, username, password, name, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and modify an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify. allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [yes | no] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_on_connection_limit [enabled | disabled] queue_depth_limit [integer] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.modify_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 min_active_members=1 ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up_members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool which will be deleted CLI Example:: salt '*' bigip.delete_node bigip admin admin my-pool ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def replace_pool_members(hostname, username, password, name, members): ''' A function to connect to a bigip device and replace members of an existing pool with new members. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify members List of comma delimited pool members to replace existing members with. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 CLI Example:: salt '*' bigip.replace_pool_members bigip admin admin my-pool 10.2.2.1:80,10.2.2.2:80,10.2.2.3:80 ''' payload = {} payload['name'] = name #specify members if provided if members is not None: if isinstance(members, six.string_types): members = members.split(',') pool_members = [] for member in members: #check to see if already a dictionary ( for states) if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) pool_members.append(member) #parse string passed via execution command (for executions) else: pool_members.append({'name': member, 'address': member.split(':')[0]}) payload['members'] = pool_members #build session bigip_session = _build_session(username, password) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def add_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and add a new member to an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to add i.e. 10.1.1.2:80 CLI Example: .. code-block:: bash salt '*' bigip.add_pool_members bigip admin admin my-pool 10.2.2.1:80 ''' # for states if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) payload = member # for execution else: payload = {'name': member, 'address': member.split(':')[0]} #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool_member(hostname, username, password, name, member, connection_limit=None, description=None, dynamic_ratio=None, inherit_profile=None, logging=None, monitor=None, priority_group=None, profiles=None, rate_limit=None, ratio=None, session=None, state=None): ''' A function to connect to a bigip device and modify an existing member of a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to modify i.e. 10.1.1.2:80 connection_limit [integer] description [string] dynamic_ratio [integer] inherit_profile [enabled | disabled] logging [enabled | disabled] monitor [name] priority_group [integer] profiles [none | profile_name] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [ user-up | user-down ] CLI Example:: salt '*' bigip.modify_pool_member bigip admin admin my-pool 10.2.2.1:80 state=use-down session=user-disabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'inherit-profile': inherit_profile, 'logging': logging, 'monitor': monitor, 'priority-group': priority_group, 'profiles': profiles, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members/{member}'.format(name=name, member=member), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the pool member to delete CLI Example:: salt '*' bigip.delete_pool_member bigip admin admin my-pool 10.2.2.2:80 ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/members/{member}'.format(name=name, member=member)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_virtual(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all virtuals or a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to list. If no name is specified than all virtuals will be listed. CLI Example:: salt '*' bigip.list_virtual bigip admin admin my-virtual ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_virtual(hostname, username, password, name, destination, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): r''' A function to connect to a bigip device and create a virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to create destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no] connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limit_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limitçsrc [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disabled] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Examples:: salt '*' bigip.create_virtual bigip admin admin my-virtual-3 26.2.2.5:80 \ pool=my-http-pool-http profiles=http,tcp salt '*' bigip.create_virtual bigip admin admin my-virtual-3 43.2.2.5:80 \ pool=test-http-pool-http profiles=http,websecurity persist=cookie,hash \ policies=asm_auto_l7_policy__http-virtual \ rules=_sys_APM_ExchangeSupport_helper,_sys_https_redirect \ related_rules=_sys_APM_activesync,_sys_APM_ExchangeSupport_helper \ source_address_translation=snat:my-snat-pool \ translate_address=enabled translate_port=enabled \ traffic_classes=my-class,other-class \ vlans=enabled:external,internal ''' params = { 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name payload['destination'] = destination #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: #check to see if this is already a dictionary first if isinstance(source_address_translation, dict): payload['source-address-translation'] = source_address_translation elif source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif isinstance(vlans, six.string_types) and (vlans.startswith('enabled') or vlans.startswith('disabled')): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) else: return 'Error: vlans must be a dictionary or string.' #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_virtual(hostname, username, password, name, destination=None, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): ''' A function to connect to a bigip device and modify an existing virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to modify destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no} connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limitr_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limit_src [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disable] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Example:: salt '*' bigip.modify_virtual bigip admin admin my-virtual source_address_translation=none salt '*' bigip.modify_virtual bigip admin admin my-virtual rules=my-rule,my-other-rule ''' params = { 'destination': destination, 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: if source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif vlans.startswith('enabled') or vlans.startswith('disabled'): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_virtual(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to delete CLI Example:: salt '*' bigip.delete_virtual bigip admin admin my-virtual ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_monitor(hostname, username, password, monitor_type, name=None, ): ''' A function to connect to a bigip device and list an existing monitor. If no name is provided than all monitors of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor(s) to list name The name of the monitor to list CLI Example:: salt '*' bigip.list_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}?expandSubcollections=true'.format(type=monitor_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}'.format(type=monitor_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and create a monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to create name The name of the monitor to create kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.create_monitor bigip admin admin http my-http-monitor timeout=10 interval=5 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type']: key = key.replace('_', '-') payload[key] = value #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}'.format(type=monitor_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and modify an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to modify name The name of the monitor to modify kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.modify_monitor bigip admin admin http my-http-monitor timout=16 interval=6 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type', 'name']: key = key.replace('_', '-') payload[key] = value #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_monitor(hostname, username, password, monitor_type, name): ''' A function to connect to a bigip device and delete an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to delete name The name of the monitor to delete CLI Example:: salt '*' bigip.delete_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_profile(hostname, username, password, profile_type, name=None, ): ''' A function to connect to a bigip device and list an existing profile. If no name is provided than all profiles of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile(s) to list name The name of the profile to list CLI Example:: salt '*' bigip.list_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}?expandSubcollections=true'.format(type=profile_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}'.format(type=profile_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}'.format(type=profile_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 salt '*' bigip.modify_profile bigip admin admin client-ssl my-client-ssl-1 retainCertificate=false \ ciphers='DEFAULT\:!SSLv3' cert_key_chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j' ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}/{name}'.format(type=profile_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_profile(hostname, username, password, profile_type, name): ''' A function to connect to a bigip device and delete an existing profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to delete name The name of the profile to delete CLI Example:: salt '*' bigip.delete_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}'.format(type=profile_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response)
saltstack/salt
salt/modules/bigip.py
create_node
python
def create_node(hostname, username, password, name, address, trans_label=None): ''' A function to connect to a bigip device and create a node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node address The address of the node trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.create_node bigip admin admin 10.1.1.2 ''' #build session bigip_session = _build_session(username, password, trans_label) #construct the payload payload = {} payload['name'] = name payload['address'] = address #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node', data=salt.utils.json.dumps(payload)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response)
A function to connect to a bigip device and create a node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node address The address of the node trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.create_node bigip admin admin 10.1.1.2
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L430-L469
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def _build_session(username, password, trans_label=None):\n '''\n Create a session to be used when connecting to iControl REST.\n '''\n\n bigip = requests.session()\n bigip.auth = (username, password)\n bigip.verify = False\n bigip.headers.update({'Content-Type': 'application/json'})\n\n if trans_label:\n #pull the trans id from the grain\n trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label))\n\n if trans_id:\n bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id})\n else:\n bigip.headers.update({'X-F5-REST-Coordination-Id': None})\n\n return bigip\n", "def _load_response(response):\n '''\n Load the response from json data, return the dictionary or raw text\n '''\n\n try:\n data = salt.utils.json.loads(response.text)\n except ValueError:\n data = response.text\n\n ret = {'code': response.status_code, 'content': data}\n\n return ret\n", "def _load_connection_error(hostname, error):\n '''\n Format and Return a connection error\n '''\n\n ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\\n{error}'.format(host=hostname, error=error)}\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' An execution module which can manipulate an f5 bigip via iControl REST :maturity: develop :platform: f5_bigip_11.6 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.utils.json # Import third party libs try: import requests import requests.exceptions HAS_LIBS = True except ImportError: HAS_LIBS = False # Import 3rd-party libs from salt.ext import six # Import salt libs import salt.exceptions # Define the module's virtual name __virtualname__ = 'bigip' def __virtual__(): ''' Only return if requests is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The bigip execution module cannot be loaded: ' 'python requests library not available.') BIG_IP_URL_BASE = 'https://{host}/mgmt/tm' def _build_session(username, password, trans_label=None): ''' Create a session to be used when connecting to iControl REST. ''' bigip = requests.session() bigip.auth = (username, password) bigip.verify = False bigip.headers.update({'Content-Type': 'application/json'}) if trans_label: #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label)) if trans_id: bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id}) else: bigip.headers.update({'X-F5-REST-Coordination-Id': None}) return bigip def _load_response(response): ''' Load the response from json data, return the dictionary or raw text ''' try: data = salt.utils.json.loads(response.text) except ValueError: data = response.text ret = {'code': response.status_code, 'content': data} return ret def _load_connection_error(hostname, error): ''' Format and Return a connection error ''' ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\n{error}'.format(host=hostname, error=error)} return ret def _loop_payload(params): ''' Pass in a dictionary of parameters, loop through them and build a payload containing, parameters who's values are not None. ''' #construct the payload payload = {} #set the payload for param, value in six.iteritems(params): if value is not None: payload[param] = value return payload def _build_list(option_value, item_kind): ''' pass in an option to check for a list of items, create a list of dictionary of items to set for this option ''' #specify profiles if provided if option_value is not None: items = [] #if user specified none, return an empty list if option_value == 'none': return items #was a list already passed in? if not isinstance(option_value, list): values = option_value.split(',') else: values = option_value for value in values: # sometimes the bigip just likes a plain ol list of items if item_kind is None: items.append(value) # other times it's picky and likes key value pairs... else: items.append({'kind': item_kind, 'name': value}) return items return None def _determine_toggles(payload, toggles): ''' BigIP can't make up its mind if it likes yes / no or true or false. Figure out what it likes to hear without confusing the user. ''' for toggle, definition in six.iteritems(toggles): #did the user specify anything? if definition['value'] is not None: #test for yes_no toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no': payload[toggle] = 'yes' elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no': payload[toggle] = 'no' #test for true_false toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false': payload[toggle] = True elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false': payload[toggle] = False return payload def _set_value(value): ''' A function to detect if user is trying to pass a dictionary or list. parse it and return a dictionary list or a string ''' #don't continue if already an acceptable data-type if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list): return value #check if json if value.startswith('j{') and value.endswith('}j'): value = value.replace('j{', '{') value = value.replace('}j', '}') try: return salt.utils.json.loads(value) except Exception: raise salt.exceptions.CommandExecutionError #detect list of dictionaries if '|' in value and r'\|' not in value: values = value.split('|') items = [] for value in values: items.append(_set_value(value)) return items #parse out dictionary if detected if ':' in value and r'\:' not in value: options = {} #split out pairs key_pairs = value.split(',') for key_pair in key_pairs: k = key_pair.split(':')[0] v = key_pair.split(':')[1] options[k] = v return options #try making a list elif ',' in value and r'\,' not in value: value_items = value.split(',') return value_items #just return a string else: #remove escape chars if added if r'\|' in value: value = value.replace(r'\|', '|') if r'\:' in value: value = value.replace(r'\:', ':') if r'\,' in value: value = value.replace(r'\,', ',') return value def start_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and start a new transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The name / alias for this transaction. The actual transaction id will be stored within a grain called ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.start_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) payload = {} #post to REST to get trans id try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/transaction', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) #extract the trans_id data = _load_response(response) if data['code'] == 200: trans_id = data['content']['transId'] __salt__['grains.setval']('bigip_f5_trans', {label: trans_id}) return 'Transaction: {trans_id} - has successfully been stored in the grain: bigip_f5_trans:{label}'.format(trans_id=trans_id, label=label) else: return data def list_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and list an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #post to REST to get trans id try: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}/commands'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def commit_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and commit an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.commit_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: payload = {} payload['state'] = 'VALIDATING' #patch to REST to get trans id try: response = bigip_session.patch( BIG_IP_URL_BASE.format(host=hostname) + '/transaction/{trans_id}'.format(trans_id=trans_id), data=salt.utils.json.dumps(payload) ) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def delete_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and delete an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #patch to REST to get trans id try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def list_node(hostname, username, password, name=None, trans_label=None): ''' A function to connect to a bigip device and list all nodes or a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to list. If no name is specified than all nodes will be listed. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_node bigip admin admin my-node ''' #build sessions bigip_session = _build_session(username, password, trans_label) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_node(hostname, username, password, name, connection_limit=None, description=None, dynamic_ratio=None, logging=None, monitor=None, rate_limit=None, ratio=None, session=None, state=None, trans_label=None): ''' A function to connect to a bigip device and modify an existing node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to modify connection_limit [integer] description [string] dynamic_ratio [integer] logging [enabled | disabled] monitor [[name] | none | default] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [user-down | user-up ] trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.modify_node bigip admin admin 10.1.1.2 ratio=2 logging=enabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'logging': logging, 'monitor': monitor, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state, } #build session bigip_session = _build_session(username, password, trans_label) #build payload payload = _loop_payload(params) payload['name'] = name #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_node(hostname, username, password, name, trans_label=None): ''' A function to connect to a bigip device and delete a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node which will be deleted. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_node bigip admin admin my-node ''' #build session bigip_session = _build_session(username, password, trans_label) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_pool(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all pools or a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to list. If no name is specified then all pools will be listed. CLI Example:: salt '*' bigip.list_pool bigip admin admin my-pool ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_pool(hostname, username, password, name, members=None, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and create a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to create. members List of comma delimited pool members to add to the pool. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [enabled | disabled] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_depth_limit [integer] queue_on_connection_limit [enabled | disabled] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.create_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 monitor=http ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up-members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify members if provided if members is not None: payload['members'] = _build_list(members, 'ltm:pool:members') #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool(hostname, username, password, name, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and modify an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify. allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [yes | no] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_on_connection_limit [enabled | disabled] queue_depth_limit [integer] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.modify_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 min_active_members=1 ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up_members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool which will be deleted CLI Example:: salt '*' bigip.delete_node bigip admin admin my-pool ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def replace_pool_members(hostname, username, password, name, members): ''' A function to connect to a bigip device and replace members of an existing pool with new members. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify members List of comma delimited pool members to replace existing members with. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 CLI Example:: salt '*' bigip.replace_pool_members bigip admin admin my-pool 10.2.2.1:80,10.2.2.2:80,10.2.2.3:80 ''' payload = {} payload['name'] = name #specify members if provided if members is not None: if isinstance(members, six.string_types): members = members.split(',') pool_members = [] for member in members: #check to see if already a dictionary ( for states) if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) pool_members.append(member) #parse string passed via execution command (for executions) else: pool_members.append({'name': member, 'address': member.split(':')[0]}) payload['members'] = pool_members #build session bigip_session = _build_session(username, password) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def add_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and add a new member to an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to add i.e. 10.1.1.2:80 CLI Example: .. code-block:: bash salt '*' bigip.add_pool_members bigip admin admin my-pool 10.2.2.1:80 ''' # for states if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) payload = member # for execution else: payload = {'name': member, 'address': member.split(':')[0]} #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool_member(hostname, username, password, name, member, connection_limit=None, description=None, dynamic_ratio=None, inherit_profile=None, logging=None, monitor=None, priority_group=None, profiles=None, rate_limit=None, ratio=None, session=None, state=None): ''' A function to connect to a bigip device and modify an existing member of a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to modify i.e. 10.1.1.2:80 connection_limit [integer] description [string] dynamic_ratio [integer] inherit_profile [enabled | disabled] logging [enabled | disabled] monitor [name] priority_group [integer] profiles [none | profile_name] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [ user-up | user-down ] CLI Example:: salt '*' bigip.modify_pool_member bigip admin admin my-pool 10.2.2.1:80 state=use-down session=user-disabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'inherit-profile': inherit_profile, 'logging': logging, 'monitor': monitor, 'priority-group': priority_group, 'profiles': profiles, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members/{member}'.format(name=name, member=member), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the pool member to delete CLI Example:: salt '*' bigip.delete_pool_member bigip admin admin my-pool 10.2.2.2:80 ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/members/{member}'.format(name=name, member=member)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_virtual(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all virtuals or a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to list. If no name is specified than all virtuals will be listed. CLI Example:: salt '*' bigip.list_virtual bigip admin admin my-virtual ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_virtual(hostname, username, password, name, destination, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): r''' A function to connect to a bigip device and create a virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to create destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no] connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limit_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limitçsrc [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disabled] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Examples:: salt '*' bigip.create_virtual bigip admin admin my-virtual-3 26.2.2.5:80 \ pool=my-http-pool-http profiles=http,tcp salt '*' bigip.create_virtual bigip admin admin my-virtual-3 43.2.2.5:80 \ pool=test-http-pool-http profiles=http,websecurity persist=cookie,hash \ policies=asm_auto_l7_policy__http-virtual \ rules=_sys_APM_ExchangeSupport_helper,_sys_https_redirect \ related_rules=_sys_APM_activesync,_sys_APM_ExchangeSupport_helper \ source_address_translation=snat:my-snat-pool \ translate_address=enabled translate_port=enabled \ traffic_classes=my-class,other-class \ vlans=enabled:external,internal ''' params = { 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name payload['destination'] = destination #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: #check to see if this is already a dictionary first if isinstance(source_address_translation, dict): payload['source-address-translation'] = source_address_translation elif source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif isinstance(vlans, six.string_types) and (vlans.startswith('enabled') or vlans.startswith('disabled')): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) else: return 'Error: vlans must be a dictionary or string.' #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_virtual(hostname, username, password, name, destination=None, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): ''' A function to connect to a bigip device and modify an existing virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to modify destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no} connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limitr_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limit_src [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disable] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Example:: salt '*' bigip.modify_virtual bigip admin admin my-virtual source_address_translation=none salt '*' bigip.modify_virtual bigip admin admin my-virtual rules=my-rule,my-other-rule ''' params = { 'destination': destination, 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: if source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif vlans.startswith('enabled') or vlans.startswith('disabled'): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_virtual(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to delete CLI Example:: salt '*' bigip.delete_virtual bigip admin admin my-virtual ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_monitor(hostname, username, password, monitor_type, name=None, ): ''' A function to connect to a bigip device and list an existing monitor. If no name is provided than all monitors of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor(s) to list name The name of the monitor to list CLI Example:: salt '*' bigip.list_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}?expandSubcollections=true'.format(type=monitor_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}'.format(type=monitor_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and create a monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to create name The name of the monitor to create kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.create_monitor bigip admin admin http my-http-monitor timeout=10 interval=5 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type']: key = key.replace('_', '-') payload[key] = value #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}'.format(type=monitor_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and modify an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to modify name The name of the monitor to modify kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.modify_monitor bigip admin admin http my-http-monitor timout=16 interval=6 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type', 'name']: key = key.replace('_', '-') payload[key] = value #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_monitor(hostname, username, password, monitor_type, name): ''' A function to connect to a bigip device and delete an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to delete name The name of the monitor to delete CLI Example:: salt '*' bigip.delete_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_profile(hostname, username, password, profile_type, name=None, ): ''' A function to connect to a bigip device and list an existing profile. If no name is provided than all profiles of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile(s) to list name The name of the profile to list CLI Example:: salt '*' bigip.list_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}?expandSubcollections=true'.format(type=profile_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}'.format(type=profile_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}'.format(type=profile_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 salt '*' bigip.modify_profile bigip admin admin client-ssl my-client-ssl-1 retainCertificate=false \ ciphers='DEFAULT\:!SSLv3' cert_key_chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j' ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}/{name}'.format(type=profile_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_profile(hostname, username, password, profile_type, name): ''' A function to connect to a bigip device and delete an existing profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to delete name The name of the profile to delete CLI Example:: salt '*' bigip.delete_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}'.format(type=profile_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response)
saltstack/salt
salt/modules/bigip.py
modify_node
python
def modify_node(hostname, username, password, name, connection_limit=None, description=None, dynamic_ratio=None, logging=None, monitor=None, rate_limit=None, ratio=None, session=None, state=None, trans_label=None): ''' A function to connect to a bigip device and modify an existing node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to modify connection_limit [integer] description [string] dynamic_ratio [integer] logging [enabled | disabled] monitor [[name] | none | default] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [user-down | user-up ] trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.modify_node bigip admin admin 10.1.1.2 ratio=2 logging=enabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'logging': logging, 'monitor': monitor, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state, } #build session bigip_session = _build_session(username, password, trans_label) #build payload payload = _loop_payload(params) payload['name'] = name #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response)
A function to connect to a bigip device and modify an existing node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to modify connection_limit [integer] description [string] dynamic_ratio [integer] logging [enabled | disabled] monitor [[name] | none | default] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [user-down | user-up ] trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.modify_node bigip admin admin 10.1.1.2 ratio=2 logging=enabled
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L472-L549
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def _build_session(username, password, trans_label=None):\n '''\n Create a session to be used when connecting to iControl REST.\n '''\n\n bigip = requests.session()\n bigip.auth = (username, password)\n bigip.verify = False\n bigip.headers.update({'Content-Type': 'application/json'})\n\n if trans_label:\n #pull the trans id from the grain\n trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label))\n\n if trans_id:\n bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id})\n else:\n bigip.headers.update({'X-F5-REST-Coordination-Id': None})\n\n return bigip\n", "def _load_response(response):\n '''\n Load the response from json data, return the dictionary or raw text\n '''\n\n try:\n data = salt.utils.json.loads(response.text)\n except ValueError:\n data = response.text\n\n ret = {'code': response.status_code, 'content': data}\n\n return ret\n", "def _load_connection_error(hostname, error):\n '''\n Format and Return a connection error\n '''\n\n ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\\n{error}'.format(host=hostname, error=error)}\n\n return ret\n", "def _loop_payload(params):\n '''\n Pass in a dictionary of parameters, loop through them and build a payload containing,\n parameters who's values are not None.\n '''\n\n #construct the payload\n payload = {}\n\n #set the payload\n for param, value in six.iteritems(params):\n if value is not None:\n payload[param] = value\n\n return payload\n" ]
# -*- coding: utf-8 -*- ''' An execution module which can manipulate an f5 bigip via iControl REST :maturity: develop :platform: f5_bigip_11.6 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.utils.json # Import third party libs try: import requests import requests.exceptions HAS_LIBS = True except ImportError: HAS_LIBS = False # Import 3rd-party libs from salt.ext import six # Import salt libs import salt.exceptions # Define the module's virtual name __virtualname__ = 'bigip' def __virtual__(): ''' Only return if requests is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The bigip execution module cannot be loaded: ' 'python requests library not available.') BIG_IP_URL_BASE = 'https://{host}/mgmt/tm' def _build_session(username, password, trans_label=None): ''' Create a session to be used when connecting to iControl REST. ''' bigip = requests.session() bigip.auth = (username, password) bigip.verify = False bigip.headers.update({'Content-Type': 'application/json'}) if trans_label: #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label)) if trans_id: bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id}) else: bigip.headers.update({'X-F5-REST-Coordination-Id': None}) return bigip def _load_response(response): ''' Load the response from json data, return the dictionary or raw text ''' try: data = salt.utils.json.loads(response.text) except ValueError: data = response.text ret = {'code': response.status_code, 'content': data} return ret def _load_connection_error(hostname, error): ''' Format and Return a connection error ''' ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\n{error}'.format(host=hostname, error=error)} return ret def _loop_payload(params): ''' Pass in a dictionary of parameters, loop through them and build a payload containing, parameters who's values are not None. ''' #construct the payload payload = {} #set the payload for param, value in six.iteritems(params): if value is not None: payload[param] = value return payload def _build_list(option_value, item_kind): ''' pass in an option to check for a list of items, create a list of dictionary of items to set for this option ''' #specify profiles if provided if option_value is not None: items = [] #if user specified none, return an empty list if option_value == 'none': return items #was a list already passed in? if not isinstance(option_value, list): values = option_value.split(',') else: values = option_value for value in values: # sometimes the bigip just likes a plain ol list of items if item_kind is None: items.append(value) # other times it's picky and likes key value pairs... else: items.append({'kind': item_kind, 'name': value}) return items return None def _determine_toggles(payload, toggles): ''' BigIP can't make up its mind if it likes yes / no or true or false. Figure out what it likes to hear without confusing the user. ''' for toggle, definition in six.iteritems(toggles): #did the user specify anything? if definition['value'] is not None: #test for yes_no toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no': payload[toggle] = 'yes' elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no': payload[toggle] = 'no' #test for true_false toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false': payload[toggle] = True elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false': payload[toggle] = False return payload def _set_value(value): ''' A function to detect if user is trying to pass a dictionary or list. parse it and return a dictionary list or a string ''' #don't continue if already an acceptable data-type if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list): return value #check if json if value.startswith('j{') and value.endswith('}j'): value = value.replace('j{', '{') value = value.replace('}j', '}') try: return salt.utils.json.loads(value) except Exception: raise salt.exceptions.CommandExecutionError #detect list of dictionaries if '|' in value and r'\|' not in value: values = value.split('|') items = [] for value in values: items.append(_set_value(value)) return items #parse out dictionary if detected if ':' in value and r'\:' not in value: options = {} #split out pairs key_pairs = value.split(',') for key_pair in key_pairs: k = key_pair.split(':')[0] v = key_pair.split(':')[1] options[k] = v return options #try making a list elif ',' in value and r'\,' not in value: value_items = value.split(',') return value_items #just return a string else: #remove escape chars if added if r'\|' in value: value = value.replace(r'\|', '|') if r'\:' in value: value = value.replace(r'\:', ':') if r'\,' in value: value = value.replace(r'\,', ',') return value def start_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and start a new transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The name / alias for this transaction. The actual transaction id will be stored within a grain called ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.start_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) payload = {} #post to REST to get trans id try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/transaction', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) #extract the trans_id data = _load_response(response) if data['code'] == 200: trans_id = data['content']['transId'] __salt__['grains.setval']('bigip_f5_trans', {label: trans_id}) return 'Transaction: {trans_id} - has successfully been stored in the grain: bigip_f5_trans:{label}'.format(trans_id=trans_id, label=label) else: return data def list_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and list an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #post to REST to get trans id try: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}/commands'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def commit_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and commit an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.commit_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: payload = {} payload['state'] = 'VALIDATING' #patch to REST to get trans id try: response = bigip_session.patch( BIG_IP_URL_BASE.format(host=hostname) + '/transaction/{trans_id}'.format(trans_id=trans_id), data=salt.utils.json.dumps(payload) ) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def delete_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and delete an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #patch to REST to get trans id try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def list_node(hostname, username, password, name=None, trans_label=None): ''' A function to connect to a bigip device and list all nodes or a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to list. If no name is specified than all nodes will be listed. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_node bigip admin admin my-node ''' #build sessions bigip_session = _build_session(username, password, trans_label) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_node(hostname, username, password, name, address, trans_label=None): ''' A function to connect to a bigip device and create a node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node address The address of the node trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.create_node bigip admin admin 10.1.1.2 ''' #build session bigip_session = _build_session(username, password, trans_label) #construct the payload payload = {} payload['name'] = name payload['address'] = address #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node', data=salt.utils.json.dumps(payload)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_node(hostname, username, password, name, trans_label=None): ''' A function to connect to a bigip device and delete a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node which will be deleted. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_node bigip admin admin my-node ''' #build session bigip_session = _build_session(username, password, trans_label) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_pool(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all pools or a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to list. If no name is specified then all pools will be listed. CLI Example:: salt '*' bigip.list_pool bigip admin admin my-pool ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_pool(hostname, username, password, name, members=None, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and create a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to create. members List of comma delimited pool members to add to the pool. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [enabled | disabled] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_depth_limit [integer] queue_on_connection_limit [enabled | disabled] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.create_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 monitor=http ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up-members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify members if provided if members is not None: payload['members'] = _build_list(members, 'ltm:pool:members') #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool(hostname, username, password, name, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and modify an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify. allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [yes | no] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_on_connection_limit [enabled | disabled] queue_depth_limit [integer] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.modify_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 min_active_members=1 ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up_members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool which will be deleted CLI Example:: salt '*' bigip.delete_node bigip admin admin my-pool ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def replace_pool_members(hostname, username, password, name, members): ''' A function to connect to a bigip device and replace members of an existing pool with new members. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify members List of comma delimited pool members to replace existing members with. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 CLI Example:: salt '*' bigip.replace_pool_members bigip admin admin my-pool 10.2.2.1:80,10.2.2.2:80,10.2.2.3:80 ''' payload = {} payload['name'] = name #specify members if provided if members is not None: if isinstance(members, six.string_types): members = members.split(',') pool_members = [] for member in members: #check to see if already a dictionary ( for states) if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) pool_members.append(member) #parse string passed via execution command (for executions) else: pool_members.append({'name': member, 'address': member.split(':')[0]}) payload['members'] = pool_members #build session bigip_session = _build_session(username, password) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def add_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and add a new member to an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to add i.e. 10.1.1.2:80 CLI Example: .. code-block:: bash salt '*' bigip.add_pool_members bigip admin admin my-pool 10.2.2.1:80 ''' # for states if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) payload = member # for execution else: payload = {'name': member, 'address': member.split(':')[0]} #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool_member(hostname, username, password, name, member, connection_limit=None, description=None, dynamic_ratio=None, inherit_profile=None, logging=None, monitor=None, priority_group=None, profiles=None, rate_limit=None, ratio=None, session=None, state=None): ''' A function to connect to a bigip device and modify an existing member of a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to modify i.e. 10.1.1.2:80 connection_limit [integer] description [string] dynamic_ratio [integer] inherit_profile [enabled | disabled] logging [enabled | disabled] monitor [name] priority_group [integer] profiles [none | profile_name] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [ user-up | user-down ] CLI Example:: salt '*' bigip.modify_pool_member bigip admin admin my-pool 10.2.2.1:80 state=use-down session=user-disabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'inherit-profile': inherit_profile, 'logging': logging, 'monitor': monitor, 'priority-group': priority_group, 'profiles': profiles, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members/{member}'.format(name=name, member=member), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the pool member to delete CLI Example:: salt '*' bigip.delete_pool_member bigip admin admin my-pool 10.2.2.2:80 ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/members/{member}'.format(name=name, member=member)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_virtual(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all virtuals or a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to list. If no name is specified than all virtuals will be listed. CLI Example:: salt '*' bigip.list_virtual bigip admin admin my-virtual ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_virtual(hostname, username, password, name, destination, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): r''' A function to connect to a bigip device and create a virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to create destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no] connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limit_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limitçsrc [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disabled] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Examples:: salt '*' bigip.create_virtual bigip admin admin my-virtual-3 26.2.2.5:80 \ pool=my-http-pool-http profiles=http,tcp salt '*' bigip.create_virtual bigip admin admin my-virtual-3 43.2.2.5:80 \ pool=test-http-pool-http profiles=http,websecurity persist=cookie,hash \ policies=asm_auto_l7_policy__http-virtual \ rules=_sys_APM_ExchangeSupport_helper,_sys_https_redirect \ related_rules=_sys_APM_activesync,_sys_APM_ExchangeSupport_helper \ source_address_translation=snat:my-snat-pool \ translate_address=enabled translate_port=enabled \ traffic_classes=my-class,other-class \ vlans=enabled:external,internal ''' params = { 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name payload['destination'] = destination #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: #check to see if this is already a dictionary first if isinstance(source_address_translation, dict): payload['source-address-translation'] = source_address_translation elif source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif isinstance(vlans, six.string_types) and (vlans.startswith('enabled') or vlans.startswith('disabled')): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) else: return 'Error: vlans must be a dictionary or string.' #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_virtual(hostname, username, password, name, destination=None, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): ''' A function to connect to a bigip device and modify an existing virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to modify destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no} connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limitr_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limit_src [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disable] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Example:: salt '*' bigip.modify_virtual bigip admin admin my-virtual source_address_translation=none salt '*' bigip.modify_virtual bigip admin admin my-virtual rules=my-rule,my-other-rule ''' params = { 'destination': destination, 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: if source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif vlans.startswith('enabled') or vlans.startswith('disabled'): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_virtual(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to delete CLI Example:: salt '*' bigip.delete_virtual bigip admin admin my-virtual ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_monitor(hostname, username, password, monitor_type, name=None, ): ''' A function to connect to a bigip device and list an existing monitor. If no name is provided than all monitors of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor(s) to list name The name of the monitor to list CLI Example:: salt '*' bigip.list_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}?expandSubcollections=true'.format(type=monitor_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}'.format(type=monitor_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and create a monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to create name The name of the monitor to create kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.create_monitor bigip admin admin http my-http-monitor timeout=10 interval=5 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type']: key = key.replace('_', '-') payload[key] = value #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}'.format(type=monitor_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and modify an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to modify name The name of the monitor to modify kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.modify_monitor bigip admin admin http my-http-monitor timout=16 interval=6 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type', 'name']: key = key.replace('_', '-') payload[key] = value #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_monitor(hostname, username, password, monitor_type, name): ''' A function to connect to a bigip device and delete an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to delete name The name of the monitor to delete CLI Example:: salt '*' bigip.delete_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_profile(hostname, username, password, profile_type, name=None, ): ''' A function to connect to a bigip device and list an existing profile. If no name is provided than all profiles of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile(s) to list name The name of the profile to list CLI Example:: salt '*' bigip.list_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}?expandSubcollections=true'.format(type=profile_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}'.format(type=profile_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}'.format(type=profile_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 salt '*' bigip.modify_profile bigip admin admin client-ssl my-client-ssl-1 retainCertificate=false \ ciphers='DEFAULT\:!SSLv3' cert_key_chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j' ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}/{name}'.format(type=profile_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_profile(hostname, username, password, profile_type, name): ''' A function to connect to a bigip device and delete an existing profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to delete name The name of the profile to delete CLI Example:: salt '*' bigip.delete_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}'.format(type=profile_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response)
saltstack/salt
salt/modules/bigip.py
create_pool
python
def create_pool(hostname, username, password, name, members=None, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and create a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to create. members List of comma delimited pool members to add to the pool. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [enabled | disabled] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_depth_limit [integer] queue_on_connection_limit [enabled | disabled] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.create_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 monitor=http ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up-members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify members if provided if members is not None: payload['members'] = _build_list(members, 'ltm:pool:members') #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response)
A function to connect to a bigip device and create a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to create. members List of comma delimited pool members to add to the pool. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [enabled | disabled] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_depth_limit [integer] queue_on_connection_limit [enabled | disabled] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.create_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 monitor=http
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L622-L773
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def _build_session(username, password, trans_label=None):\n '''\n Create a session to be used when connecting to iControl REST.\n '''\n\n bigip = requests.session()\n bigip.auth = (username, password)\n bigip.verify = False\n bigip.headers.update({'Content-Type': 'application/json'})\n\n if trans_label:\n #pull the trans id from the grain\n trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label))\n\n if trans_id:\n bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id})\n else:\n bigip.headers.update({'X-F5-REST-Coordination-Id': None})\n\n return bigip\n", "def _load_response(response):\n '''\n Load the response from json data, return the dictionary or raw text\n '''\n\n try:\n data = salt.utils.json.loads(response.text)\n except ValueError:\n data = response.text\n\n ret = {'code': response.status_code, 'content': data}\n\n return ret\n", "def _load_connection_error(hostname, error):\n '''\n Format and Return a connection error\n '''\n\n ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\\n{error}'.format(host=hostname, error=error)}\n\n return ret\n", "def _loop_payload(params):\n '''\n Pass in a dictionary of parameters, loop through them and build a payload containing,\n parameters who's values are not None.\n '''\n\n #construct the payload\n payload = {}\n\n #set the payload\n for param, value in six.iteritems(params):\n if value is not None:\n payload[param] = value\n\n return payload\n", "def _build_list(option_value, item_kind):\n '''\n pass in an option to check for a list of items, create a list of dictionary of items to set\n for this option\n '''\n #specify profiles if provided\n if option_value is not None:\n\n items = []\n\n #if user specified none, return an empty list\n if option_value == 'none':\n return items\n\n #was a list already passed in?\n if not isinstance(option_value, list):\n values = option_value.split(',')\n else:\n values = option_value\n\n for value in values:\n # sometimes the bigip just likes a plain ol list of items\n if item_kind is None:\n items.append(value)\n # other times it's picky and likes key value pairs...\n else:\n items.append({'kind': item_kind, 'name': value})\n return items\n return None\n", "def _determine_toggles(payload, toggles):\n '''\n BigIP can't make up its mind if it likes yes / no or true or false.\n Figure out what it likes to hear without confusing the user.\n '''\n\n for toggle, definition in six.iteritems(toggles):\n #did the user specify anything?\n if definition['value'] is not None:\n #test for yes_no toggle\n if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no':\n payload[toggle] = 'yes'\n elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no':\n payload[toggle] = 'no'\n\n #test for true_false toggle\n if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false':\n payload[toggle] = True\n elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false':\n payload[toggle] = False\n\n return payload\n" ]
# -*- coding: utf-8 -*- ''' An execution module which can manipulate an f5 bigip via iControl REST :maturity: develop :platform: f5_bigip_11.6 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.utils.json # Import third party libs try: import requests import requests.exceptions HAS_LIBS = True except ImportError: HAS_LIBS = False # Import 3rd-party libs from salt.ext import six # Import salt libs import salt.exceptions # Define the module's virtual name __virtualname__ = 'bigip' def __virtual__(): ''' Only return if requests is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The bigip execution module cannot be loaded: ' 'python requests library not available.') BIG_IP_URL_BASE = 'https://{host}/mgmt/tm' def _build_session(username, password, trans_label=None): ''' Create a session to be used when connecting to iControl REST. ''' bigip = requests.session() bigip.auth = (username, password) bigip.verify = False bigip.headers.update({'Content-Type': 'application/json'}) if trans_label: #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label)) if trans_id: bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id}) else: bigip.headers.update({'X-F5-REST-Coordination-Id': None}) return bigip def _load_response(response): ''' Load the response from json data, return the dictionary or raw text ''' try: data = salt.utils.json.loads(response.text) except ValueError: data = response.text ret = {'code': response.status_code, 'content': data} return ret def _load_connection_error(hostname, error): ''' Format and Return a connection error ''' ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\n{error}'.format(host=hostname, error=error)} return ret def _loop_payload(params): ''' Pass in a dictionary of parameters, loop through them and build a payload containing, parameters who's values are not None. ''' #construct the payload payload = {} #set the payload for param, value in six.iteritems(params): if value is not None: payload[param] = value return payload def _build_list(option_value, item_kind): ''' pass in an option to check for a list of items, create a list of dictionary of items to set for this option ''' #specify profiles if provided if option_value is not None: items = [] #if user specified none, return an empty list if option_value == 'none': return items #was a list already passed in? if not isinstance(option_value, list): values = option_value.split(',') else: values = option_value for value in values: # sometimes the bigip just likes a plain ol list of items if item_kind is None: items.append(value) # other times it's picky and likes key value pairs... else: items.append({'kind': item_kind, 'name': value}) return items return None def _determine_toggles(payload, toggles): ''' BigIP can't make up its mind if it likes yes / no or true or false. Figure out what it likes to hear without confusing the user. ''' for toggle, definition in six.iteritems(toggles): #did the user specify anything? if definition['value'] is not None: #test for yes_no toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no': payload[toggle] = 'yes' elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no': payload[toggle] = 'no' #test for true_false toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false': payload[toggle] = True elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false': payload[toggle] = False return payload def _set_value(value): ''' A function to detect if user is trying to pass a dictionary or list. parse it and return a dictionary list or a string ''' #don't continue if already an acceptable data-type if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list): return value #check if json if value.startswith('j{') and value.endswith('}j'): value = value.replace('j{', '{') value = value.replace('}j', '}') try: return salt.utils.json.loads(value) except Exception: raise salt.exceptions.CommandExecutionError #detect list of dictionaries if '|' in value and r'\|' not in value: values = value.split('|') items = [] for value in values: items.append(_set_value(value)) return items #parse out dictionary if detected if ':' in value and r'\:' not in value: options = {} #split out pairs key_pairs = value.split(',') for key_pair in key_pairs: k = key_pair.split(':')[0] v = key_pair.split(':')[1] options[k] = v return options #try making a list elif ',' in value and r'\,' not in value: value_items = value.split(',') return value_items #just return a string else: #remove escape chars if added if r'\|' in value: value = value.replace(r'\|', '|') if r'\:' in value: value = value.replace(r'\:', ':') if r'\,' in value: value = value.replace(r'\,', ',') return value def start_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and start a new transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The name / alias for this transaction. The actual transaction id will be stored within a grain called ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.start_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) payload = {} #post to REST to get trans id try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/transaction', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) #extract the trans_id data = _load_response(response) if data['code'] == 200: trans_id = data['content']['transId'] __salt__['grains.setval']('bigip_f5_trans', {label: trans_id}) return 'Transaction: {trans_id} - has successfully been stored in the grain: bigip_f5_trans:{label}'.format(trans_id=trans_id, label=label) else: return data def list_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and list an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #post to REST to get trans id try: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}/commands'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def commit_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and commit an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.commit_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: payload = {} payload['state'] = 'VALIDATING' #patch to REST to get trans id try: response = bigip_session.patch( BIG_IP_URL_BASE.format(host=hostname) + '/transaction/{trans_id}'.format(trans_id=trans_id), data=salt.utils.json.dumps(payload) ) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def delete_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and delete an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #patch to REST to get trans id try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def list_node(hostname, username, password, name=None, trans_label=None): ''' A function to connect to a bigip device and list all nodes or a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to list. If no name is specified than all nodes will be listed. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_node bigip admin admin my-node ''' #build sessions bigip_session = _build_session(username, password, trans_label) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_node(hostname, username, password, name, address, trans_label=None): ''' A function to connect to a bigip device and create a node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node address The address of the node trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.create_node bigip admin admin 10.1.1.2 ''' #build session bigip_session = _build_session(username, password, trans_label) #construct the payload payload = {} payload['name'] = name payload['address'] = address #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node', data=salt.utils.json.dumps(payload)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_node(hostname, username, password, name, connection_limit=None, description=None, dynamic_ratio=None, logging=None, monitor=None, rate_limit=None, ratio=None, session=None, state=None, trans_label=None): ''' A function to connect to a bigip device and modify an existing node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to modify connection_limit [integer] description [string] dynamic_ratio [integer] logging [enabled | disabled] monitor [[name] | none | default] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [user-down | user-up ] trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.modify_node bigip admin admin 10.1.1.2 ratio=2 logging=enabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'logging': logging, 'monitor': monitor, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state, } #build session bigip_session = _build_session(username, password, trans_label) #build payload payload = _loop_payload(params) payload['name'] = name #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_node(hostname, username, password, name, trans_label=None): ''' A function to connect to a bigip device and delete a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node which will be deleted. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_node bigip admin admin my-node ''' #build session bigip_session = _build_session(username, password, trans_label) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_pool(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all pools or a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to list. If no name is specified then all pools will be listed. CLI Example:: salt '*' bigip.list_pool bigip admin admin my-pool ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool(hostname, username, password, name, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and modify an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify. allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [yes | no] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_on_connection_limit [enabled | disabled] queue_depth_limit [integer] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.modify_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 min_active_members=1 ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up_members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool which will be deleted CLI Example:: salt '*' bigip.delete_node bigip admin admin my-pool ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def replace_pool_members(hostname, username, password, name, members): ''' A function to connect to a bigip device and replace members of an existing pool with new members. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify members List of comma delimited pool members to replace existing members with. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 CLI Example:: salt '*' bigip.replace_pool_members bigip admin admin my-pool 10.2.2.1:80,10.2.2.2:80,10.2.2.3:80 ''' payload = {} payload['name'] = name #specify members if provided if members is not None: if isinstance(members, six.string_types): members = members.split(',') pool_members = [] for member in members: #check to see if already a dictionary ( for states) if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) pool_members.append(member) #parse string passed via execution command (for executions) else: pool_members.append({'name': member, 'address': member.split(':')[0]}) payload['members'] = pool_members #build session bigip_session = _build_session(username, password) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def add_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and add a new member to an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to add i.e. 10.1.1.2:80 CLI Example: .. code-block:: bash salt '*' bigip.add_pool_members bigip admin admin my-pool 10.2.2.1:80 ''' # for states if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) payload = member # for execution else: payload = {'name': member, 'address': member.split(':')[0]} #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool_member(hostname, username, password, name, member, connection_limit=None, description=None, dynamic_ratio=None, inherit_profile=None, logging=None, monitor=None, priority_group=None, profiles=None, rate_limit=None, ratio=None, session=None, state=None): ''' A function to connect to a bigip device and modify an existing member of a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to modify i.e. 10.1.1.2:80 connection_limit [integer] description [string] dynamic_ratio [integer] inherit_profile [enabled | disabled] logging [enabled | disabled] monitor [name] priority_group [integer] profiles [none | profile_name] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [ user-up | user-down ] CLI Example:: salt '*' bigip.modify_pool_member bigip admin admin my-pool 10.2.2.1:80 state=use-down session=user-disabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'inherit-profile': inherit_profile, 'logging': logging, 'monitor': monitor, 'priority-group': priority_group, 'profiles': profiles, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members/{member}'.format(name=name, member=member), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the pool member to delete CLI Example:: salt '*' bigip.delete_pool_member bigip admin admin my-pool 10.2.2.2:80 ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/members/{member}'.format(name=name, member=member)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_virtual(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all virtuals or a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to list. If no name is specified than all virtuals will be listed. CLI Example:: salt '*' bigip.list_virtual bigip admin admin my-virtual ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_virtual(hostname, username, password, name, destination, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): r''' A function to connect to a bigip device and create a virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to create destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no] connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limit_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limitçsrc [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disabled] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Examples:: salt '*' bigip.create_virtual bigip admin admin my-virtual-3 26.2.2.5:80 \ pool=my-http-pool-http profiles=http,tcp salt '*' bigip.create_virtual bigip admin admin my-virtual-3 43.2.2.5:80 \ pool=test-http-pool-http profiles=http,websecurity persist=cookie,hash \ policies=asm_auto_l7_policy__http-virtual \ rules=_sys_APM_ExchangeSupport_helper,_sys_https_redirect \ related_rules=_sys_APM_activesync,_sys_APM_ExchangeSupport_helper \ source_address_translation=snat:my-snat-pool \ translate_address=enabled translate_port=enabled \ traffic_classes=my-class,other-class \ vlans=enabled:external,internal ''' params = { 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name payload['destination'] = destination #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: #check to see if this is already a dictionary first if isinstance(source_address_translation, dict): payload['source-address-translation'] = source_address_translation elif source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif isinstance(vlans, six.string_types) and (vlans.startswith('enabled') or vlans.startswith('disabled')): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) else: return 'Error: vlans must be a dictionary or string.' #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_virtual(hostname, username, password, name, destination=None, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): ''' A function to connect to a bigip device and modify an existing virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to modify destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no} connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limitr_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limit_src [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disable] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Example:: salt '*' bigip.modify_virtual bigip admin admin my-virtual source_address_translation=none salt '*' bigip.modify_virtual bigip admin admin my-virtual rules=my-rule,my-other-rule ''' params = { 'destination': destination, 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: if source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif vlans.startswith('enabled') or vlans.startswith('disabled'): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_virtual(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to delete CLI Example:: salt '*' bigip.delete_virtual bigip admin admin my-virtual ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_monitor(hostname, username, password, monitor_type, name=None, ): ''' A function to connect to a bigip device and list an existing monitor. If no name is provided than all monitors of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor(s) to list name The name of the monitor to list CLI Example:: salt '*' bigip.list_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}?expandSubcollections=true'.format(type=monitor_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}'.format(type=monitor_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and create a monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to create name The name of the monitor to create kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.create_monitor bigip admin admin http my-http-monitor timeout=10 interval=5 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type']: key = key.replace('_', '-') payload[key] = value #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}'.format(type=monitor_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and modify an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to modify name The name of the monitor to modify kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.modify_monitor bigip admin admin http my-http-monitor timout=16 interval=6 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type', 'name']: key = key.replace('_', '-') payload[key] = value #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_monitor(hostname, username, password, monitor_type, name): ''' A function to connect to a bigip device and delete an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to delete name The name of the monitor to delete CLI Example:: salt '*' bigip.delete_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_profile(hostname, username, password, profile_type, name=None, ): ''' A function to connect to a bigip device and list an existing profile. If no name is provided than all profiles of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile(s) to list name The name of the profile to list CLI Example:: salt '*' bigip.list_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}?expandSubcollections=true'.format(type=profile_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}'.format(type=profile_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}'.format(type=profile_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 salt '*' bigip.modify_profile bigip admin admin client-ssl my-client-ssl-1 retainCertificate=false \ ciphers='DEFAULT\:!SSLv3' cert_key_chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j' ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}/{name}'.format(type=profile_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_profile(hostname, username, password, profile_type, name): ''' A function to connect to a bigip device and delete an existing profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to delete name The name of the profile to delete CLI Example:: salt '*' bigip.delete_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}'.format(type=profile_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response)
saltstack/salt
salt/modules/bigip.py
replace_pool_members
python
def replace_pool_members(hostname, username, password, name, members): ''' A function to connect to a bigip device and replace members of an existing pool with new members. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify members List of comma delimited pool members to replace existing members with. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 CLI Example:: salt '*' bigip.replace_pool_members bigip admin admin my-pool 10.2.2.1:80,10.2.2.2:80,10.2.2.3:80 ''' payload = {} payload['name'] = name #specify members if provided if members is not None: if isinstance(members, six.string_types): members = members.split(',') pool_members = [] for member in members: #check to see if already a dictionary ( for states) if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) pool_members.append(member) #parse string passed via execution command (for executions) else: pool_members.append({'name': member, 'address': member.split(':')[0]}) payload['members'] = pool_members #build session bigip_session = _build_session(username, password) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response)
A function to connect to a bigip device and replace members of an existing pool with new members. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify members List of comma delimited pool members to replace existing members with. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 CLI Example:: salt '*' bigip.replace_pool_members bigip admin admin my-pool 10.2.2.1:80,10.2.2.2:80,10.2.2.3:80
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L956-L1020
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def _build_session(username, password, trans_label=None):\n '''\n Create a session to be used when connecting to iControl REST.\n '''\n\n bigip = requests.session()\n bigip.auth = (username, password)\n bigip.verify = False\n bigip.headers.update({'Content-Type': 'application/json'})\n\n if trans_label:\n #pull the trans id from the grain\n trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label))\n\n if trans_id:\n bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id})\n else:\n bigip.headers.update({'X-F5-REST-Coordination-Id': None})\n\n return bigip\n", "def _load_response(response):\n '''\n Load the response from json data, return the dictionary or raw text\n '''\n\n try:\n data = salt.utils.json.loads(response.text)\n except ValueError:\n data = response.text\n\n ret = {'code': response.status_code, 'content': data}\n\n return ret\n", "def _load_connection_error(hostname, error):\n '''\n Format and Return a connection error\n '''\n\n ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\\n{error}'.format(host=hostname, error=error)}\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' An execution module which can manipulate an f5 bigip via iControl REST :maturity: develop :platform: f5_bigip_11.6 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.utils.json # Import third party libs try: import requests import requests.exceptions HAS_LIBS = True except ImportError: HAS_LIBS = False # Import 3rd-party libs from salt.ext import six # Import salt libs import salt.exceptions # Define the module's virtual name __virtualname__ = 'bigip' def __virtual__(): ''' Only return if requests is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The bigip execution module cannot be loaded: ' 'python requests library not available.') BIG_IP_URL_BASE = 'https://{host}/mgmt/tm' def _build_session(username, password, trans_label=None): ''' Create a session to be used when connecting to iControl REST. ''' bigip = requests.session() bigip.auth = (username, password) bigip.verify = False bigip.headers.update({'Content-Type': 'application/json'}) if trans_label: #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label)) if trans_id: bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id}) else: bigip.headers.update({'X-F5-REST-Coordination-Id': None}) return bigip def _load_response(response): ''' Load the response from json data, return the dictionary or raw text ''' try: data = salt.utils.json.loads(response.text) except ValueError: data = response.text ret = {'code': response.status_code, 'content': data} return ret def _load_connection_error(hostname, error): ''' Format and Return a connection error ''' ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\n{error}'.format(host=hostname, error=error)} return ret def _loop_payload(params): ''' Pass in a dictionary of parameters, loop through them and build a payload containing, parameters who's values are not None. ''' #construct the payload payload = {} #set the payload for param, value in six.iteritems(params): if value is not None: payload[param] = value return payload def _build_list(option_value, item_kind): ''' pass in an option to check for a list of items, create a list of dictionary of items to set for this option ''' #specify profiles if provided if option_value is not None: items = [] #if user specified none, return an empty list if option_value == 'none': return items #was a list already passed in? if not isinstance(option_value, list): values = option_value.split(',') else: values = option_value for value in values: # sometimes the bigip just likes a plain ol list of items if item_kind is None: items.append(value) # other times it's picky and likes key value pairs... else: items.append({'kind': item_kind, 'name': value}) return items return None def _determine_toggles(payload, toggles): ''' BigIP can't make up its mind if it likes yes / no or true or false. Figure out what it likes to hear without confusing the user. ''' for toggle, definition in six.iteritems(toggles): #did the user specify anything? if definition['value'] is not None: #test for yes_no toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no': payload[toggle] = 'yes' elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no': payload[toggle] = 'no' #test for true_false toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false': payload[toggle] = True elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false': payload[toggle] = False return payload def _set_value(value): ''' A function to detect if user is trying to pass a dictionary or list. parse it and return a dictionary list or a string ''' #don't continue if already an acceptable data-type if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list): return value #check if json if value.startswith('j{') and value.endswith('}j'): value = value.replace('j{', '{') value = value.replace('}j', '}') try: return salt.utils.json.loads(value) except Exception: raise salt.exceptions.CommandExecutionError #detect list of dictionaries if '|' in value and r'\|' not in value: values = value.split('|') items = [] for value in values: items.append(_set_value(value)) return items #parse out dictionary if detected if ':' in value and r'\:' not in value: options = {} #split out pairs key_pairs = value.split(',') for key_pair in key_pairs: k = key_pair.split(':')[0] v = key_pair.split(':')[1] options[k] = v return options #try making a list elif ',' in value and r'\,' not in value: value_items = value.split(',') return value_items #just return a string else: #remove escape chars if added if r'\|' in value: value = value.replace(r'\|', '|') if r'\:' in value: value = value.replace(r'\:', ':') if r'\,' in value: value = value.replace(r'\,', ',') return value def start_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and start a new transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The name / alias for this transaction. The actual transaction id will be stored within a grain called ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.start_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) payload = {} #post to REST to get trans id try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/transaction', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) #extract the trans_id data = _load_response(response) if data['code'] == 200: trans_id = data['content']['transId'] __salt__['grains.setval']('bigip_f5_trans', {label: trans_id}) return 'Transaction: {trans_id} - has successfully been stored in the grain: bigip_f5_trans:{label}'.format(trans_id=trans_id, label=label) else: return data def list_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and list an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #post to REST to get trans id try: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}/commands'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def commit_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and commit an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.commit_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: payload = {} payload['state'] = 'VALIDATING' #patch to REST to get trans id try: response = bigip_session.patch( BIG_IP_URL_BASE.format(host=hostname) + '/transaction/{trans_id}'.format(trans_id=trans_id), data=salt.utils.json.dumps(payload) ) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def delete_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and delete an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #patch to REST to get trans id try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def list_node(hostname, username, password, name=None, trans_label=None): ''' A function to connect to a bigip device and list all nodes or a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to list. If no name is specified than all nodes will be listed. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_node bigip admin admin my-node ''' #build sessions bigip_session = _build_session(username, password, trans_label) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_node(hostname, username, password, name, address, trans_label=None): ''' A function to connect to a bigip device and create a node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node address The address of the node trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.create_node bigip admin admin 10.1.1.2 ''' #build session bigip_session = _build_session(username, password, trans_label) #construct the payload payload = {} payload['name'] = name payload['address'] = address #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node', data=salt.utils.json.dumps(payload)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_node(hostname, username, password, name, connection_limit=None, description=None, dynamic_ratio=None, logging=None, monitor=None, rate_limit=None, ratio=None, session=None, state=None, trans_label=None): ''' A function to connect to a bigip device and modify an existing node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to modify connection_limit [integer] description [string] dynamic_ratio [integer] logging [enabled | disabled] monitor [[name] | none | default] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [user-down | user-up ] trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.modify_node bigip admin admin 10.1.1.2 ratio=2 logging=enabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'logging': logging, 'monitor': monitor, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state, } #build session bigip_session = _build_session(username, password, trans_label) #build payload payload = _loop_payload(params) payload['name'] = name #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_node(hostname, username, password, name, trans_label=None): ''' A function to connect to a bigip device and delete a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node which will be deleted. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_node bigip admin admin my-node ''' #build session bigip_session = _build_session(username, password, trans_label) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_pool(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all pools or a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to list. If no name is specified then all pools will be listed. CLI Example:: salt '*' bigip.list_pool bigip admin admin my-pool ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_pool(hostname, username, password, name, members=None, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and create a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to create. members List of comma delimited pool members to add to the pool. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [enabled | disabled] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_depth_limit [integer] queue_on_connection_limit [enabled | disabled] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.create_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 monitor=http ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up-members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify members if provided if members is not None: payload['members'] = _build_list(members, 'ltm:pool:members') #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool(hostname, username, password, name, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and modify an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify. allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [yes | no] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_on_connection_limit [enabled | disabled] queue_depth_limit [integer] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.modify_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 min_active_members=1 ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up_members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool which will be deleted CLI Example:: salt '*' bigip.delete_node bigip admin admin my-pool ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def add_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and add a new member to an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to add i.e. 10.1.1.2:80 CLI Example: .. code-block:: bash salt '*' bigip.add_pool_members bigip admin admin my-pool 10.2.2.1:80 ''' # for states if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) payload = member # for execution else: payload = {'name': member, 'address': member.split(':')[0]} #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool_member(hostname, username, password, name, member, connection_limit=None, description=None, dynamic_ratio=None, inherit_profile=None, logging=None, monitor=None, priority_group=None, profiles=None, rate_limit=None, ratio=None, session=None, state=None): ''' A function to connect to a bigip device and modify an existing member of a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to modify i.e. 10.1.1.2:80 connection_limit [integer] description [string] dynamic_ratio [integer] inherit_profile [enabled | disabled] logging [enabled | disabled] monitor [name] priority_group [integer] profiles [none | profile_name] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [ user-up | user-down ] CLI Example:: salt '*' bigip.modify_pool_member bigip admin admin my-pool 10.2.2.1:80 state=use-down session=user-disabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'inherit-profile': inherit_profile, 'logging': logging, 'monitor': monitor, 'priority-group': priority_group, 'profiles': profiles, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members/{member}'.format(name=name, member=member), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the pool member to delete CLI Example:: salt '*' bigip.delete_pool_member bigip admin admin my-pool 10.2.2.2:80 ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/members/{member}'.format(name=name, member=member)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_virtual(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all virtuals or a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to list. If no name is specified than all virtuals will be listed. CLI Example:: salt '*' bigip.list_virtual bigip admin admin my-virtual ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_virtual(hostname, username, password, name, destination, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): r''' A function to connect to a bigip device and create a virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to create destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no] connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limit_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limitçsrc [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disabled] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Examples:: salt '*' bigip.create_virtual bigip admin admin my-virtual-3 26.2.2.5:80 \ pool=my-http-pool-http profiles=http,tcp salt '*' bigip.create_virtual bigip admin admin my-virtual-3 43.2.2.5:80 \ pool=test-http-pool-http profiles=http,websecurity persist=cookie,hash \ policies=asm_auto_l7_policy__http-virtual \ rules=_sys_APM_ExchangeSupport_helper,_sys_https_redirect \ related_rules=_sys_APM_activesync,_sys_APM_ExchangeSupport_helper \ source_address_translation=snat:my-snat-pool \ translate_address=enabled translate_port=enabled \ traffic_classes=my-class,other-class \ vlans=enabled:external,internal ''' params = { 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name payload['destination'] = destination #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: #check to see if this is already a dictionary first if isinstance(source_address_translation, dict): payload['source-address-translation'] = source_address_translation elif source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif isinstance(vlans, six.string_types) and (vlans.startswith('enabled') or vlans.startswith('disabled')): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) else: return 'Error: vlans must be a dictionary or string.' #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_virtual(hostname, username, password, name, destination=None, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): ''' A function to connect to a bigip device and modify an existing virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to modify destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no} connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limitr_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limit_src [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disable] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Example:: salt '*' bigip.modify_virtual bigip admin admin my-virtual source_address_translation=none salt '*' bigip.modify_virtual bigip admin admin my-virtual rules=my-rule,my-other-rule ''' params = { 'destination': destination, 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: if source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif vlans.startswith('enabled') or vlans.startswith('disabled'): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_virtual(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to delete CLI Example:: salt '*' bigip.delete_virtual bigip admin admin my-virtual ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_monitor(hostname, username, password, monitor_type, name=None, ): ''' A function to connect to a bigip device and list an existing monitor. If no name is provided than all monitors of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor(s) to list name The name of the monitor to list CLI Example:: salt '*' bigip.list_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}?expandSubcollections=true'.format(type=monitor_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}'.format(type=monitor_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and create a monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to create name The name of the monitor to create kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.create_monitor bigip admin admin http my-http-monitor timeout=10 interval=5 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type']: key = key.replace('_', '-') payload[key] = value #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}'.format(type=monitor_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and modify an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to modify name The name of the monitor to modify kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.modify_monitor bigip admin admin http my-http-monitor timout=16 interval=6 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type', 'name']: key = key.replace('_', '-') payload[key] = value #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_monitor(hostname, username, password, monitor_type, name): ''' A function to connect to a bigip device and delete an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to delete name The name of the monitor to delete CLI Example:: salt '*' bigip.delete_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_profile(hostname, username, password, profile_type, name=None, ): ''' A function to connect to a bigip device and list an existing profile. If no name is provided than all profiles of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile(s) to list name The name of the profile to list CLI Example:: salt '*' bigip.list_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}?expandSubcollections=true'.format(type=profile_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}'.format(type=profile_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}'.format(type=profile_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 salt '*' bigip.modify_profile bigip admin admin client-ssl my-client-ssl-1 retainCertificate=false \ ciphers='DEFAULT\:!SSLv3' cert_key_chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j' ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}/{name}'.format(type=profile_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_profile(hostname, username, password, profile_type, name): ''' A function to connect to a bigip device and delete an existing profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to delete name The name of the profile to delete CLI Example:: salt '*' bigip.delete_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}'.format(type=profile_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response)
saltstack/salt
salt/modules/bigip.py
add_pool_member
python
def add_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and add a new member to an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to add i.e. 10.1.1.2:80 CLI Example: .. code-block:: bash salt '*' bigip.add_pool_members bigip admin admin my-pool 10.2.2.1:80 ''' # for states if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) payload = member # for execution else: payload = {'name': member, 'address': member.split(':')[0]} #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response)
A function to connect to a bigip device and add a new member to an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to add i.e. 10.1.1.2:80 CLI Example: .. code-block:: bash salt '*' bigip.add_pool_members bigip admin admin my-pool 10.2.2.1:80
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L1023-L1076
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def _build_session(username, password, trans_label=None):\n '''\n Create a session to be used when connecting to iControl REST.\n '''\n\n bigip = requests.session()\n bigip.auth = (username, password)\n bigip.verify = False\n bigip.headers.update({'Content-Type': 'application/json'})\n\n if trans_label:\n #pull the trans id from the grain\n trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label))\n\n if trans_id:\n bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id})\n else:\n bigip.headers.update({'X-F5-REST-Coordination-Id': None})\n\n return bigip\n", "def _load_response(response):\n '''\n Load the response from json data, return the dictionary or raw text\n '''\n\n try:\n data = salt.utils.json.loads(response.text)\n except ValueError:\n data = response.text\n\n ret = {'code': response.status_code, 'content': data}\n\n return ret\n", "def _load_connection_error(hostname, error):\n '''\n Format and Return a connection error\n '''\n\n ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\\n{error}'.format(host=hostname, error=error)}\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' An execution module which can manipulate an f5 bigip via iControl REST :maturity: develop :platform: f5_bigip_11.6 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import salt.utils.json # Import third party libs try: import requests import requests.exceptions HAS_LIBS = True except ImportError: HAS_LIBS = False # Import 3rd-party libs from salt.ext import six # Import salt libs import salt.exceptions # Define the module's virtual name __virtualname__ = 'bigip' def __virtual__(): ''' Only return if requests is installed ''' if HAS_LIBS: return __virtualname__ return (False, 'The bigip execution module cannot be loaded: ' 'python requests library not available.') BIG_IP_URL_BASE = 'https://{host}/mgmt/tm' def _build_session(username, password, trans_label=None): ''' Create a session to be used when connecting to iControl REST. ''' bigip = requests.session() bigip.auth = (username, password) bigip.verify = False bigip.headers.update({'Content-Type': 'application/json'}) if trans_label: #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=trans_label)) if trans_id: bigip.headers.update({'X-F5-REST-Coordination-Id': trans_id}) else: bigip.headers.update({'X-F5-REST-Coordination-Id': None}) return bigip def _load_response(response): ''' Load the response from json data, return the dictionary or raw text ''' try: data = salt.utils.json.loads(response.text) except ValueError: data = response.text ret = {'code': response.status_code, 'content': data} return ret def _load_connection_error(hostname, error): ''' Format and Return a connection error ''' ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\n{error}'.format(host=hostname, error=error)} return ret def _loop_payload(params): ''' Pass in a dictionary of parameters, loop through them and build a payload containing, parameters who's values are not None. ''' #construct the payload payload = {} #set the payload for param, value in six.iteritems(params): if value is not None: payload[param] = value return payload def _build_list(option_value, item_kind): ''' pass in an option to check for a list of items, create a list of dictionary of items to set for this option ''' #specify profiles if provided if option_value is not None: items = [] #if user specified none, return an empty list if option_value == 'none': return items #was a list already passed in? if not isinstance(option_value, list): values = option_value.split(',') else: values = option_value for value in values: # sometimes the bigip just likes a plain ol list of items if item_kind is None: items.append(value) # other times it's picky and likes key value pairs... else: items.append({'kind': item_kind, 'name': value}) return items return None def _determine_toggles(payload, toggles): ''' BigIP can't make up its mind if it likes yes / no or true or false. Figure out what it likes to hear without confusing the user. ''' for toggle, definition in six.iteritems(toggles): #did the user specify anything? if definition['value'] is not None: #test for yes_no toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'yes_no': payload[toggle] = 'yes' elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'yes_no': payload[toggle] = 'no' #test for true_false toggle if (definition['value'] is True or definition['value'] == 'yes') and definition['type'] == 'true_false': payload[toggle] = True elif (definition['value'] is False or definition['value'] == 'no') and definition['type'] == 'true_false': payload[toggle] = False return payload def _set_value(value): ''' A function to detect if user is trying to pass a dictionary or list. parse it and return a dictionary list or a string ''' #don't continue if already an acceptable data-type if isinstance(value, bool) or isinstance(value, dict) or isinstance(value, list): return value #check if json if value.startswith('j{') and value.endswith('}j'): value = value.replace('j{', '{') value = value.replace('}j', '}') try: return salt.utils.json.loads(value) except Exception: raise salt.exceptions.CommandExecutionError #detect list of dictionaries if '|' in value and r'\|' not in value: values = value.split('|') items = [] for value in values: items.append(_set_value(value)) return items #parse out dictionary if detected if ':' in value and r'\:' not in value: options = {} #split out pairs key_pairs = value.split(',') for key_pair in key_pairs: k = key_pair.split(':')[0] v = key_pair.split(':')[1] options[k] = v return options #try making a list elif ',' in value and r'\,' not in value: value_items = value.split(',') return value_items #just return a string else: #remove escape chars if added if r'\|' in value: value = value.replace(r'\|', '|') if r'\:' in value: value = value.replace(r'\:', ':') if r'\,' in value: value = value.replace(r'\,', ',') return value def start_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and start a new transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The name / alias for this transaction. The actual transaction id will be stored within a grain called ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.start_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) payload = {} #post to REST to get trans id try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/transaction', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) #extract the trans_id data = _load_response(response) if data['code'] == 200: trans_id = data['content']['transId'] __salt__['grains.setval']('bigip_f5_trans', {label: trans_id}) return 'Transaction: {trans_id} - has successfully been stored in the grain: bigip_f5_trans:{label}'.format(trans_id=trans_id, label=label) else: return data def list_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and list an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #post to REST to get trans id try: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}/commands'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def commit_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and commit an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label the label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.commit_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: payload = {} payload['state'] = 'VALIDATING' #patch to REST to get trans id try: response = bigip_session.patch( BIG_IP_URL_BASE.format(host=hostname) + '/transaction/{trans_id}'.format(trans_id=trans_id), data=salt.utils.json.dumps(payload) ) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def delete_transaction(hostname, username, password, label): ''' A function to connect to a bigip device and delete an existing transaction. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password label The label of this transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_transaction bigip admin admin my_transaction ''' #build the session bigip_session = _build_session(username, password) #pull the trans id from the grain trans_id = __salt__['grains.get']('bigip_f5_trans:{label}'.format(label=label)) if trans_id: #patch to REST to get trans id try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/transaction/{trans_id}'.format(trans_id=trans_id)) return _load_response(response) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) else: return 'Error: the label for this transaction was not defined as a grain. Begin a new transaction using the' \ ' bigip.start_transaction function' def list_node(hostname, username, password, name=None, trans_label=None): ''' A function to connect to a bigip device and list all nodes or a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to list. If no name is specified than all nodes will be listed. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.list_node bigip admin admin my-node ''' #build sessions bigip_session = _build_session(username, password, trans_label) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_node(hostname, username, password, name, address, trans_label=None): ''' A function to connect to a bigip device and create a node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node address The address of the node trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.create_node bigip admin admin 10.1.1.2 ''' #build session bigip_session = _build_session(username, password, trans_label) #construct the payload payload = {} payload['name'] = name payload['address'] = address #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node', data=salt.utils.json.dumps(payload)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_node(hostname, username, password, name, connection_limit=None, description=None, dynamic_ratio=None, logging=None, monitor=None, rate_limit=None, ratio=None, session=None, state=None, trans_label=None): ''' A function to connect to a bigip device and modify an existing node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to modify connection_limit [integer] description [string] dynamic_ratio [integer] logging [enabled | disabled] monitor [[name] | none | default] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [user-down | user-up ] trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.modify_node bigip admin admin 10.1.1.2 ratio=2 logging=enabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'logging': logging, 'monitor': monitor, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state, } #build session bigip_session = _build_session(username, password, trans_label) #build payload payload = _loop_payload(params) payload['name'] = name #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_node(hostname, username, password, name, trans_label=None): ''' A function to connect to a bigip device and delete a specific node. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node which will be deleted. trans_label The label of the transaction stored within the grain: ``bigip_f5_trans:<label>`` CLI Example:: salt '*' bigip.delete_node bigip admin admin my-node ''' #build session bigip_session = _build_session(username, password, trans_label) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/node/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_pool(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all pools or a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to list. If no name is specified then all pools will be listed. CLI Example:: salt '*' bigip.list_pool bigip admin admin my-pool ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_pool(hostname, username, password, name, members=None, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and create a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to create. members List of comma delimited pool members to add to the pool. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [enabled | disabled] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_depth_limit [integer] queue_on_connection_limit [enabled | disabled] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.create_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 monitor=http ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up-members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify members if provided if members is not None: payload['members'] = _build_list(members, 'ltm:pool:members') #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool(hostname, username, password, name, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None, link_qos_to_client=None, link_qos_to_server=None, load_balancing_mode=None, min_active_members=None, min_up_members=None, min_up_members_action=None, min_up_members_checking=None, monitor=None, profiles=None, queue_depth_limit=None, queue_on_connection_limit=None, queue_time_limit=None, reselect_tries=None, service_down_action=None, slow_ramp_time=None): ''' A function to connect to a bigip device and modify an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify. allow_nat [yes | no] allow_snat [yes | no] description [string] gateway_failsafe_device [string] ignore_persisted_weight [yes | no] ip_tos_to_client [pass-through | [integer]] ip_tos_to_server [pass-through | [integer]] link_qos_to_client [pass-through | [integer]] link_qos_to_server [pass-through | [integer]] load_balancing_mode [dynamic-ratio-member | dynamic-ratio-node | fastest-app-response | fastest-node | least-connections-members | least-connections-node | least-sessions | observed-member | observed-node | predictive-member | predictive-node | ratio-least-connections-member | ratio-least-connections-node | ratio-member | ratio-node | ratio-session | round-robin | weighted-least-connections-member | weighted-least-connections-node] min_active_members [integer] min_up_members [integer] min_up_members_action [failover | reboot | restart-all] min_up_members_checking [enabled | disabled] monitor [name] profiles [none | profile_name] queue_on_connection_limit [enabled | disabled] queue_depth_limit [integer] queue_time_limit [integer] reselect_tries [integer] service_down_action [drop | none | reselect | reset] slow_ramp_time [integer] CLI Example:: salt '*' bigip.modify_pool bigip admin admin my-pool 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 min_active_members=1 ''' params = { 'description': description, 'gateway-failsafe-device': gateway_failsafe_device, 'ignore-persisted-weight': ignore_persisted_weight, 'ip-tos-to-client': ip_tos_to_client, 'ip-tos-to-server': ip_tos_to_server, 'link-qos-to-client': link_qos_to_client, 'link-qos-to-server': link_qos_to_server, 'load-balancing-mode': load_balancing_mode, 'min-active-members': min_active_members, 'min-up-members': min_up_members, 'min-up_members-action': min_up_members_action, 'min-up-members-checking': min_up_members_checking, 'monitor': monitor, 'profiles': profiles, 'queue-on-connection-limit': queue_on_connection_limit, 'queue-depth-limit': queue_depth_limit, 'queue-time-limit': queue_time_limit, 'reselect-tries': reselect_tries, 'service-down-action': service_down_action, 'slow-ramp-time': slow_ramp_time } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'allow-nat': {'type': 'yes_no', 'value': allow_nat}, 'allow-snat': {'type': 'yes_no', 'value': allow_snat} } #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #build session bigip_session = _build_session(username, password) #post to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool which will be deleted CLI Example:: salt '*' bigip.delete_node bigip admin admin my-pool ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def replace_pool_members(hostname, username, password, name, members): ''' A function to connect to a bigip device and replace members of an existing pool with new members. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify members List of comma delimited pool members to replace existing members with. i.e. 10.1.1.1:80,10.1.1.2:80,10.1.1.3:80 CLI Example:: salt '*' bigip.replace_pool_members bigip admin admin my-pool 10.2.2.1:80,10.2.2.2:80,10.2.2.3:80 ''' payload = {} payload['name'] = name #specify members if provided if members is not None: if isinstance(members, six.string_types): members = members.split(',') pool_members = [] for member in members: #check to see if already a dictionary ( for states) if isinstance(member, dict): #check for state alternative name 'member_state', replace with state if 'member_state' in member.keys(): member['state'] = member.pop('member_state') #replace underscore with dash for key in member: new_key = key.replace('_', '-') member[new_key] = member.pop(key) pool_members.append(member) #parse string passed via execution command (for executions) else: pool_members.append({'name': member, 'address': member.split(':')[0]}) payload['members'] = pool_members #build session bigip_session = _build_session(username, password) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_pool_member(hostname, username, password, name, member, connection_limit=None, description=None, dynamic_ratio=None, inherit_profile=None, logging=None, monitor=None, priority_group=None, profiles=None, rate_limit=None, ratio=None, session=None, state=None): ''' A function to connect to a bigip device and modify an existing member of a pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the member to modify i.e. 10.1.1.2:80 connection_limit [integer] description [string] dynamic_ratio [integer] inherit_profile [enabled | disabled] logging [enabled | disabled] monitor [name] priority_group [integer] profiles [none | profile_name] rate_limit [integer] ratio [integer] session [user-enabled | user-disabled] state [ user-up | user-down ] CLI Example:: salt '*' bigip.modify_pool_member bigip admin admin my-pool 10.2.2.1:80 state=use-down session=user-disabled ''' params = { 'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'inherit-profile': inherit_profile, 'logging': logging, 'monitor': monitor, 'priority-group': priority_group, 'profiles': profiles, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/pool/{name}/members/{member}'.format(name=name, member=member), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and delete a specific pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The name of the pool member to delete CLI Example:: salt '*' bigip.delete_pool_member bigip admin admin my-pool 10.2.2.2:80 ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/pool/{name}/members/{member}'.format(name=name, member=member)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_virtual(hostname, username, password, name=None): ''' A function to connect to a bigip device and list all virtuals or a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to list. If no name is specified than all virtuals will be listed. CLI Example:: salt '*' bigip.list_virtual bigip admin admin my-virtual ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}/?expandSubcollections=true'.format(name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual') except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_virtual(hostname, username, password, name, destination, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): r''' A function to connect to a bigip device and create a virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to create destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no] connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limit_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limitçsrc [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disabled] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Examples:: salt '*' bigip.create_virtual bigip admin admin my-virtual-3 26.2.2.5:80 \ pool=my-http-pool-http profiles=http,tcp salt '*' bigip.create_virtual bigip admin admin my-virtual-3 43.2.2.5:80 \ pool=test-http-pool-http profiles=http,websecurity persist=cookie,hash \ policies=asm_auto_l7_policy__http-virtual \ rules=_sys_APM_ExchangeSupport_helper,_sys_https_redirect \ related_rules=_sys_APM_activesync,_sys_APM_ExchangeSupport_helper \ source_address_translation=snat:my-snat-pool \ translate_address=enabled translate_port=enabled \ traffic_classes=my-class,other-class \ vlans=enabled:external,internal ''' params = { 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name payload['destination'] = destination #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: #check to see if this is already a dictionary first if isinstance(source_address_translation, dict): payload['source-address-translation'] = source_address_translation elif source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif isinstance(vlans, six.string_types) and (vlans.startswith('enabled') or vlans.startswith('disabled')): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) else: return 'Error: vlans must be a dictionary or string.' #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual', data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_virtual(hostname, username, password, name, destination=None, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay=None, description=None, fallback_persistence=None, flow_eviction_policy=None, gtm_score=None, ip_forward=None, ip_protocol=None, internal=None, twelve_forward=None, last_hop_pool=None, mask=None, mirror=None, nat64=None, persist=None, profiles=None, policies=None, rate_class=None, rate_limit=None, rate_limit_mode=None, rate_limit_dst=None, rate_limit_src=None, rules=None, related_rules=None, reject=None, source=None, source_address_translation=None, source_port=None, state=None, traffic_classes=None, translate_address=None, translate_port=None, vlans=None): ''' A function to connect to a bigip device and modify an existing virtual server. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to modify destination [ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ] pool [ [pool_name] | none] address_status [yes | no] auto_lasthop [default | enabled | disabled ] bwc_policy [none] | string] cmp_enabled [yes | no] dhcp_relay [yes | no} connection_limit [integer] description [string] state [disabled | enabled] fallback_persistence [none | [profile name] ] flow_eviction_policy [none | [eviction policy name] ] gtm_score [integer] ip_forward [yes | no] ip_protocol [any | protocol] internal [yes | no] twelve_forward (12-forward) [yes | no] last_hop-pool [ [pool_name] | none] mask { [ipv4] | [ipv6] } mirror { [disabled | enabled | none] } nat64 [enabled | disabled] persist [none | profile1,profile2,profile3 ... ] profiles [none | default | profile1,profile2,profile3 ... ] policies [none | default | policy1,policy2,policy3 ... ] rate_class [name] rate_limit [integer] rate_limitr_mode [destination | object | object-destination | object-source | object-source-destination | source | source-destination] rate_limit_dst [integer] rate_limit_src [integer] rules [none | [rule_one,rule_two ...] ] related_rules [none | [rule_one,rule_two ...] ] reject [yes | no] source { [ipv4[/prefixlen]] | [ipv6[/prefixlen]] } source_address_translation [none | snat:pool_name | lsn | automap ] source_port [change | preserve | preserve-strict] state [enabled | disable] traffic_classes [none | default | class_one,class_two ... ] translate_address [enabled | disabled] translate_port [enabled | disabled] vlans [none | default | [enabled|disabled]:vlan1,vlan2,vlan3 ... ] CLI Example:: salt '*' bigip.modify_virtual bigip admin admin my-virtual source_address_translation=none salt '*' bigip.modify_virtual bigip admin admin my-virtual rules=my-rule,my-other-rule ''' params = { 'destination': destination, 'pool': pool, 'auto-lasthop': auto_lasthop, 'bwc-policy': bwc_policy, 'connection-limit': connection_limit, 'description': description, 'fallback-persistence': fallback_persistence, 'flow-eviction-policy': flow_eviction_policy, 'gtm-score': gtm_score, 'ip-protocol': ip_protocol, 'last-hop-pool': last_hop_pool, 'mask': mask, 'mirror': mirror, 'nat64': nat64, 'persist': persist, 'rate-class': rate_class, 'rate-limit': rate_limit, 'rate-limit-mode': rate_limit_mode, 'rate-limit-dst': rate_limit_dst, 'rate-limit-src': rate_limit_src, 'source': source, 'source-port': source_port, 'translate-address': translate_address, 'translate-port': translate_port } # some options take yes no others take true false. Figure out when to use which without # confusing the end user toggles = { 'address-status': {'type': 'yes_no', 'value': address_status}, 'cmp-enabled': {'type': 'yes_no', 'value': cmp_enabled}, 'dhcp-relay': {'type': 'true_false', 'value': dhcp_relay}, 'reject': {'type': 'true_false', 'value': reject}, '12-forward': {'type': 'true_false', 'value': twelve_forward}, 'internal': {'type': 'true_false', 'value': internal}, 'ip-forward': {'type': 'true_false', 'value': ip_forward} } #build session bigip_session = _build_session(username, password) #build payload payload = _loop_payload(params) payload['name'] = name #determine toggles payload = _determine_toggles(payload, toggles) #specify profiles if provided if profiles is not None: payload['profiles'] = _build_list(profiles, 'ltm:virtual:profile') #specify persist if provided if persist is not None: payload['persist'] = _build_list(persist, 'ltm:virtual:persist') #specify policies if provided if policies is not None: payload['policies'] = _build_list(policies, 'ltm:virtual:policy') #specify rules if provided if rules is not None: payload['rules'] = _build_list(rules, None) #specify related-rules if provided if related_rules is not None: payload['related-rules'] = _build_list(related_rules, None) #handle source-address-translation if source_address_translation is not None: if source_address_translation == 'none': payload['source-address-translation'] = {'pool': 'none', 'type': 'none'} elif source_address_translation == 'automap': payload['source-address-translation'] = {'pool': 'none', 'type': 'automap'} elif source_address_translation == 'lsn': payload['source-address-translation'] = {'pool': 'none', 'type': 'lsn'} elif source_address_translation.startswith('snat'): snat_pool = source_address_translation.split(':')[1] payload['source-address-translation'] = {'pool': snat_pool, 'type': 'snat'} #specify related-rules if provided if traffic_classes is not None: payload['traffic-classes'] = _build_list(traffic_classes, None) #handle vlans if vlans is not None: #ceck to see if vlans is a dictionary (used when state makes use of function) if isinstance(vlans, dict): try: payload['vlans'] = vlans['vlan_ids'] if vlans['enabled']: payload['vlans-enabled'] = True elif vlans['disabled']: payload['vlans-disabled'] = True except Exception: return 'Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}'.format(vlans=vlans) elif vlans == 'none': payload['vlans'] = 'none' elif vlans == 'default': payload['vlans'] = 'default' elif vlans.startswith('enabled') or vlans.startswith('disabled'): try: vlans_setting = vlans.split(':')[0] payload['vlans'] = vlans.split(':')[1].split(',') if vlans_setting == 'disabled': payload['vlans-disabled'] = True elif vlans_setting == 'enabled': payload['vlans-enabled'] = True except Exception: return 'Error: Unable to Parse vlans option: \n\tvlans={vlans}'.format(vlans=vlans) #determine state if state is not None: if state == 'enabled': payload['enabled'] = True elif state == 'disabled': payload['disabled'] = True #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/virtual/{name}'.format(name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_virtual(hostname, username, password, name): ''' A function to connect to a bigip device and delete a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to delete CLI Example:: salt '*' bigip.delete_virtual bigip admin admin my-virtual ''' #build session bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/virtual/{name}'.format(name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_monitor(hostname, username, password, monitor_type, name=None, ): ''' A function to connect to a bigip device and list an existing monitor. If no name is provided than all monitors of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor(s) to list name The name of the monitor to list CLI Example:: salt '*' bigip.list_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}?expandSubcollections=true'.format(type=monitor_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}'.format(type=monitor_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and create a monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to create name The name of the monitor to create kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.create_monitor bigip admin admin http my-http-monitor timeout=10 interval=5 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type']: key = key.replace('_', '-') payload[key] = value #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}'.format(type=monitor_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_monitor(hostname, username, password, monitor_type, name, **kwargs): ''' A function to connect to a bigip device and modify an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to modify name The name of the monitor to modify kwargs Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. CLI Example:: salt '*' bigip.modify_monitor bigip admin admin http my-http-monitor timout=16 interval=6 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} #there's a ton of different monitors and a ton of options for each type of monitor. #this logic relies that the end user knows which options are meant for which monitor types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'type', 'name']: key = key.replace('_', '-') payload[key] = value #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_monitor(hostname, username, password, monitor_type, name): ''' A function to connect to a bigip device and delete an existing monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to delete name The name of the monitor to delete CLI Example:: salt '*' bigip.delete_monitor bigip admin admin http my-http-monitor ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/monitor/{type}/{name}'.format(type=monitor_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response) def list_profile(hostname, username, password, profile_type, name=None, ): ''' A function to connect to a bigip device and list an existing profile. If no name is provided than all profiles of the specified type will be listed. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile(s) to list name The name of the profile to list CLI Example:: salt '*' bigip.list_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #get to REST try: if name: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}?expandSubcollections=true'.format(type=profile_type, name=name)) else: response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}'.format(type=profile_type)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def create_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.create_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #post to REST try: response = bigip_session.post( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}'.format(type=profile_type), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def modify_profile(hostname, username, password, profile_type, name, **kwargs): r''' A function to connect to a bigip device and create a profile. A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profile to create kwargs ``[ arg=val ] ... [arg=key1:val1,key2:val2] ...`` Consult F5 BIGIP user guide for specific options for each monitor type. Typically, tmsh arg names are used. Creating Complex Args Profiles can get pretty complicated in terms of the amount of possible config options. Use the following shorthand to create complex arguments such as lists, dictionaries, and lists of dictionaries. An option is also provided to pass raw json as well. lists ``[i,i,i]``: ``param='item1,item2,item3'`` Dictionary ``[k:v,k:v,k,v]``: ``param='key-1:val-1,key-2:val2,key-3:va-3'`` List of Dictionaries ``[k:v,k:v|k:v,k:v|k:v,k:v]``: ``param='key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2|key-1:val-1,key-2:val-2'`` JSON: ``'j{ ... }j'``: ``cert-key-chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j'`` Escaping Delimiters: Use ``\,`` or ``\:`` or ``\|`` to escape characters which shouldn't be treated as delimiters i.e. ``ciphers='DEFAULT\:!SSLv3'`` CLI Examples:: salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' salt '*' bigip.modify_profile bigip admin admin http my-http-profile defaultsFrom='/Common/http' \ enforcement=maxHeaderCount:3200,maxRequests:10 salt '*' bigip.modify_profile bigip admin admin client-ssl my-client-ssl-1 retainCertificate=false \ ciphers='DEFAULT\:!SSLv3' cert_key_chain='j{ "default": { "cert": "default.crt", "chain": "default.crt", "key": "default.key" } }j' ''' #build session bigip_session = _build_session(username, password) #construct the payload payload = {} payload['name'] = name #there's a ton of different profiles and a ton of options for each type of profile. #this logic relies that the end user knows which options are meant for which profile types for key, value in six.iteritems(kwargs): if not key.startswith('__'): if key not in ['hostname', 'username', 'password', 'profile_type']: key = key.replace('_', '-') try: payload[key] = _set_value(value) except salt.exceptions.CommandExecutionError: return 'Error: Unable to Parse JSON data for parameter: {key}\n{value}'.format(key=key, value=value) #put to REST try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) + '/ltm/profile/{type}/{name}'.format(type=profile_type, name=name), data=salt.utils.json.dumps(payload) ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) return _load_response(response) def delete_profile(hostname, username, password, profile_type, name): ''' A function to connect to a bigip device and delete an existing profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to delete name The name of the profile to delete CLI Example:: salt '*' bigip.delete_profile bigip admin admin http my-http-profile ''' #build sessions bigip_session = _build_session(username, password) #delete to REST try: response = bigip_session.delete(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}'.format(type=profile_type, name=name)) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) if _load_response(response) == '': return True else: return _load_response(response)