repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
saltstack/salt
salt/modules/cassandra_cql.py
list_users
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
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
[ "def", "list_users", "(", "contact_points", "=", "None", ",", "port", "=", "None", ",", "cql_user", "=", "None", ",", "cql_pass", "=", "None", ")", ":", "query", "=", "\"list users;\"", "ret", "=", "{", "}", "try", ":", "ret", "=", "cql_query", "(", ...
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
[ "List", "existing", "users", "in", "this", "Cassandra", "cluster", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cassandra_cql.py#L797-L833
train
saltstack/salt
salt/modules/cassandra_cql.py
create_user
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
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
[ "def", "create_user", "(", "username", ",", "password", ",", "superuser", "=", "False", ",", "contact_points", "=", "None", ",", "port", "=", "None", ",", "cql_user", "=", "None", ",", "cql_pass", "=", "None", ")", ":", "superuser_cql", "=", "'superuser'",...
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
[ "Create", "a", "new", "cassandra", "user", "with", "credentials", "and", "superuser", "status", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cassandra_cql.py#L836-L882
train
saltstack/salt
salt/modules/cassandra_cql.py
list_permissions
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
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
[ "def", "list_permissions", "(", "username", "=", "None", ",", "resource", "=", "None", ",", "resource_type", "=", "'keyspace'", ",", "permission", "=", "None", ",", "contact_points", "=", "None", ",", "port", "=", "None", ",", "cql_user", "=", "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
[ "List", "permissions", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cassandra_cql.py#L939-L994
train
saltstack/salt
salt/modules/cassandra_cql.py
grant_permission
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
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
[ "def", "grant_permission", "(", "username", ",", "resource", "=", "None", ",", "resource_type", "=", "'keyspace'", ",", "permission", "=", "None", ",", "contact_points", "=", "None", ",", "port", "=", "None", ",", "cql_user", "=", "None", ",", "cql_pass", ...
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
[ "Grant", "permissions", "to", "a", "user", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cassandra_cql.py#L997-L1046
train
saltstack/salt
salt/beacons/journald.py
_get_journal
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']
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']
[ "def", "_get_journal", "(", ")", ":", "if", "'systemd.journald'", "in", "__context__", ":", "return", "__context__", "[", "'systemd.journald'", "]", "__context__", "[", "'systemd.journald'", "]", "=", "systemd", ".", "journal", ".", "Reader", "(", ")", "# get to...
Return the active running journal object
[ "Return", "the", "active", "running", "journal", "object" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/journald.py#L33-L43
train
saltstack/salt
salt/beacons/journald.py
beacon
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
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
[ "def", "beacon", "(", "config", ")", ":", "ret", "=", "[", "]", "journal", "=", "_get_journal", "(", ")", "_config", "=", "{", "}", "list", "(", "map", "(", "_config", ".", "update", ",", "config", ")", ")", "while", "True", ":", "cur", "=", "jou...
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
[ "The", "journald", "beacon", "allows", "for", "the", "systemd", "journal", "to", "be", "parsed", "and", "linked", "objects", "to", "be", "turned", "into", "events", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/journald.py#L64-L104
train
saltstack/salt
salt/returners/couchdb_return.py
_get_options
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
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
[ "def", "_get_options", "(", "ret", "=", "None", ")", ":", "attrs", "=", "{", "'url'", ":", "'url'", ",", "'db'", ":", "'db'", ",", "'user'", ":", "'user'", ",", "'passwd'", ":", "'passwd'", ",", "'redact_pws'", ":", "'redact_pws'", ",", "'minimum_return'...
Get the couchdb options from salt.
[ "Get", "the", "couchdb", "options", "from", "salt", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L96-L136
train
saltstack/salt
salt/returners/couchdb_return.py
_generate_doc
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
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
[ "def", "_generate_doc", "(", "ret", ")", ":", "# 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 timesta...
Create a object that will be saved into the database based on options.
[ "Create", "a", "object", "that", "will", "be", "saved", "into", "the", "database", "based", "on", "options", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L151-L166
train
saltstack/salt
salt/returners/couchdb_return.py
_request
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())
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())
[ "def", "_request", "(", "method", ",", "url", ",", "content_type", "=", "None", ",", "_data", "=", "None", ",", "user", "=", "None", ",", "passwd", "=", "None", ")", ":", "opener", "=", "_build_opener", "(", "_HTTPHandler", ")", "request", "=", "_Reque...
Makes a HTTP request. Returns the JSON parse, or an obj with an error.
[ "Makes", "a", "HTTP", "request", ".", "Returns", "the", "JSON", "parse", "or", "an", "obj", "with", "an", "error", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L169-L187
train
saltstack/salt
salt/returners/couchdb_return.py
_generate_event_doc
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
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
[ "def", "_generate_event_doc", "(", "event", ")", ":", "# 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", "(", ...
Create a object that will be saved into the database based in options.
[ "Create", "a", "object", "that", "will", "be", "saved", "into", "the", "database", "based", "in", "options", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L190-L212
train
saltstack/salt
salt/returners/couchdb_return.py
returner
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)
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)
[ "def", "returner", "(", "ret", ")", ":", "options", "=", "_get_options", "(", "ret", ")", "# Check to see if the database exists.", "_response", "=", "_request", "(", "\"GET\"", ",", "options", "[", "'url'", "]", "+", "\"_all_dbs\"", ",", "user", "=", "options...
Take in the return and shove it into the couchdb database.
[ "Take", "in", "the", "return", "and", "shove", "it", "into", "the", "couchdb", "database", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L215-L269
train
saltstack/salt
salt/returners/couchdb_return.py
event_return
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)
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)
[ "def", "event_return", "(", "events", ")", ":", "log", ".", "debug", "(", "'events data is: %s'", ",", "events", ")", "options", "=", "_get_options", "(", ")", "# Check to see if the database exists.", "_response", "=", "_request", "(", "\"GET\"", ",", "options", ...
Return event to CouchDB server Requires that configuration be enabled via 'event_return' option in master config. Example: event_return: - couchdb
[ "Return", "event", "to", "CouchDB", "server", "Requires", "that", "configuration", "be", "enabled", "via", "event_return", "option", "in", "master", "config", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L272-L318
train
saltstack/salt
salt/returners/couchdb_return.py
get_jids
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
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
[ "def", "get_jids", "(", ")", ":", "options", "=", "_get_options", "(", "ret", "=", "None", ")", "_response", "=", "_request", "(", "\"GET\"", ",", "options", "[", "'url'", "]", "+", "options", "[", "'db'", "]", "+", "\"/_all_docs?include_docs=true\"", ")",...
List all the jobs that we have..
[ "List", "all", "the", "jobs", "that", "we", "have", ".." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L333-L356
train
saltstack/salt
salt/returners/couchdb_return.py
get_fun
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
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
[ "def", "get_fun", "(", "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", ...
Return a dict with key being minion and value being the job details of the last run of function 'fun'.
[ "Return", "a", "dict", "with", "key", "being", "minion", "and", "value", "being", "the", "job", "details", "of", "the", "last", "run", "of", "function", "fun", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L359-L399
train
saltstack/salt
salt/returners/couchdb_return.py
get_minions
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
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
[ "def", "get_minions", "(", ")", ":", "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..", "_r...
Return a list of minion identifiers from a request of the view.
[ "Return", "a", "list", "of", "minion", "identifiers", "from", "a", "request", "of", "the", "view", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L402-L427
train
saltstack/salt
salt/returners/couchdb_return.py
ensure_views
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
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
[ "def", "ensure_views", "(", ")", ":", "# 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", "...
This function makes sure that all the views that should exist in the design document do exist.
[ "This", "function", "makes", "sure", "that", "all", "the", "views", "that", "should", "exist", "in", "the", "design", "document", "do", "exist", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L430-L456
train
saltstack/salt
salt/returners/couchdb_return.py
set_salt_view
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
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
[ "def", "set_salt_view", "(", ")", ":", "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", "(", ")", ...
Helper function that sets the salt design document. Uses get_valid_salt_views and some hardcoded values.
[ "Helper", "function", "that", "sets", "the", "salt", "design", "document", ".", "Uses", "get_valid_salt_views", "and", "some", "hardcoded", "values", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L477-L497
train
saltstack/salt
salt/returners/couchdb_return.py
get_load
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}
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}
[ "def", "get_load", "(", "jid", ")", ":", "options", "=", "_get_options", "(", "ret", "=", "None", ")", "_response", "=", "_request", "(", "\"GET\"", ",", "options", "[", "'url'", "]", "+", "options", "[", "'db'", "]", "+", "'/'", "+", "jid", ")", "...
Included for API consistency
[ "Included", "for", "API", "consistency" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L521-L530
train
saltstack/salt
salt/modules/heat.py
_auth
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)
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)
[ "def", "_auth", "(", "profile", "=", "None", ",", "api_version", "=", "1", ",", "*", "*", "connection_args", ")", ":", "if", "profile", ":", "prefix", "=", "profile", "+", "':keystone.'", "else", ":", "prefix", "=", "'keystone.'", "def", "get", "(", "k...
Set up heat credentials, returns `heatclient.client.Client`. Optional parameter "api_version" defaults to 1. Only intended to be used within heat-enabled modules
[ "Set", "up", "heat", "credentials", "returns", "heatclient", ".", "client", ".", "Client", ".", "Optional", "parameter", "api_version", "defaults", "to", "1", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/heat.py#L102-L171
train
saltstack/salt
salt/modules/heat.py
_parse_environment
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
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
[ "def", "_parse_environment", "(", "env_str", ")", ":", "try", ":", "env", "=", "salt", ".", "utils", ".", "yaml", ".", "safe_load", "(", "env_str", ")", "except", "salt", ".", "utils", ".", "yaml", ".", "YAMLError", "as", "exc", ":", "raise", "ValueErr...
Parsing template
[ "Parsing", "template" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/heat.py#L196-L216
train
saltstack/salt
salt/modules/heat.py
_get_stack_events
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
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
[ "def", "_get_stack_events", "(", "h_client", ",", "stack_id", ",", "event_args", ")", ":", "event_args", "[", "'stack_id'", "]", "=", "stack_id", "event_args", "[", "'resource_name'", "]", "=", "None", "try", ":", "events", "=", "h_client", ".", "events", "....
Get event for stack
[ "Get", "event", "for", "stack" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/heat.py#L219-L232
train
saltstack/salt
salt/modules/heat.py
_poll_for_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
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
[ "def", "_poll_for_events", "(", "h_client", ",", "stack_name", ",", "action", "=", "None", ",", "poll_period", "=", "5", ",", "timeout", "=", "60", ",", "marker", "=", "None", ")", ":", "if", "action", ":", "stop_status", "=", "(", "'{0}_FAILED'", ".", ...
Polling stack events
[ "Polling", "stack", "events" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/heat.py#L235-L283
train
saltstack/salt
salt/modules/heat.py
list_stack
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
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
[ "def", "list_stack", "(", "profile", "=", "None", ")", ":", "ret", "=", "{", "}", "h_client", "=", "_auth", "(", "profile", ")", "for", "stack", "in", "h_client", ".", "stacks", ".", "list", "(", ")", ":", "links", "=", "{", "}", "for", "link", "...
Return a list of available stack (heat stack-list) profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.list_stack profile=openstack1
[ "Return", "a", "list", "of", "available", "stack", "(", "heat", "stack", "-", "list", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/heat.py#L286-L314
train
saltstack/salt
salt/modules/heat.py
show_stack
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
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
[ "def", "show_stack", "(", "name", "=", "None", ",", "profile", "=", "None", ")", ":", "h_client", "=", "_auth", "(", "profile", ")", "if", "not", "name", ":", "return", "{", "'result'", ":", "False", ",", "'comment'", ":", "'Parameter name missing or 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
[ "Return", "details", "about", "a", "specific", "stack", "(", "heat", "stack", "-", "show", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/heat.py#L317-L362
train
saltstack/salt
salt/modules/heat.py
delete_stack
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
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
[ "def", "delete_stack", "(", "name", "=", "None", ",", "poll", "=", "0", ",", "timeout", "=", "60", ",", "profile", "=", "None", ")", ":", "h_client", "=", "_auth", "(", "profile", ")", "ret", "=", "{", "'result'", ":", "True", ",", "'comment'", ":"...
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
[ "Delete", "a", "stack", "(", "heat", "stack", "-", "delete", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/heat.py#L365-L428
train
saltstack/salt
salt/modules/heat.py
create_stack
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
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
[ "def", "create_stack", "(", "name", "=", "None", ",", "template_file", "=", "None", ",", "environment", "=", "None", ",", "parameters", "=", "None", ",", "poll", "=", "0", ",", "rollback", "=", "False", ",", "timeout", "=", "60", ",", "profile", "=", ...
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.
[ "Create", "a", "stack", "(", "heat", "stack", "-", "create", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/heat.py#L431-L623
train
saltstack/salt
salt/modules/heat.py
template_stack
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
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
[ "def", "template_stack", "(", "name", "=", "None", ",", "profile", "=", "None", ")", ":", "h_client", "=", "_auth", "(", "profile", ")", "if", "not", "name", ":", "return", "{", "'result'", ":", "False", ",", "'comment'", ":", "'Parameter name missing or N...
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
[ "Return", "template", "a", "specific", "stack", "(", "heat", "stack", "-", "template", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/heat.py#L824-L871
train
saltstack/salt
salt/states/uptime.py
monitored
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
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
[ "def", "monitored", "(", "name", ",", "*", "*", "params", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", "}", "if", "__salt__", "[", "'uptime.check_exists'...
Makes sure an URL is monitored by uptime. Checks if URL is already monitored, and if not, adds it.
[ "Makes", "sure", "an", "URL", "is", "monitored", "by", "uptime", ".", "Checks", "if", "URL", "is", "already", "monitored", "and", "if", "not", "adds", "it", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/uptime.py#L47-L75
train
saltstack/salt
salt/modules/zk_concurrency.py
lock_holders
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()
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()
[ "def", "lock_holders", "(", "path", ",", "zk_hosts", "=", "None", ",", "identifier", "=", "None", ",", "max_concurrency", "=", "1", ",", "timeout", "=", "None", ",", "ephemeral_lease", "=", "False", ",", "profile", "=", "None", ",", "scheme", "=", "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
[ "Return", "an", "un", "-", "ordered", "list", "of", "lock", "holders" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zk_concurrency.py#L154-L198
train
saltstack/salt
salt/modules/zk_concurrency.py
lock
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
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
[ "def", "lock", "(", "path", ",", "zk_hosts", "=", "None", ",", "identifier", "=", "None", ",", "max_concurrency", "=", "1", ",", "timeout", "=", "None", ",", "ephemeral_lease", "=", "False", ",", "force", "=", "False", ",", "# foricble get the lock regardles...
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
[ "Get", "lock", "(", "with", "optional", "timeout", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zk_concurrency.py#L201-L264
train
saltstack/salt
salt/modules/zk_concurrency.py
unlock
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
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
[ "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", "=",...
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
[ "Remove", "lease", "from", "semaphore" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zk_concurrency.py#L267-L320
train
saltstack/salt
salt/modules/zk_concurrency.py
party_members
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)
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)
[ "def", "party_members", "(", "path", ",", "zk_hosts", "=", "None", ",", "min_nodes", "=", "1", ",", "blocking", "=", "False", ",", "profile", "=", "None", ",", "scheme", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ",", "d...
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
[ "Get", "the", "List", "of", "identifiers", "in", "a", "particular", "party", "optionally", "waiting", "for", "the", "specified", "minimum", "number", "of", "nodes", "(", "min_nodes", ")", "to", "appear" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zk_concurrency.py#L323-L364
train
saltstack/salt
salt/modules/chef.py
_default_logfile
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
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
[ "def", "_default_logfile", "(", "exe_name", ")", ":", "if", "salt", ".", "utils", ".", "platform", ".", "is_windows", "(", ")", ":", "tmp_dir", "=", "os", ".", "path", ".", "join", "(", "__opts__", "[", "'cachedir'", "]", ",", "'tmp'", ")", "if", "no...
Retrieve the logfile name
[ "Retrieve", "the", "logfile", "name" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chef.py#L32-L52
train
saltstack/salt
salt/modules/chef.py
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)
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)
[ "def", "client", "(", "whyrun", "=", "False", ",", "localmode", "=", "False", ",", "logfile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "logfile", "is", "None", ":", "logfile", "=", "_default_logfile", "(", "'chef-client'", ")", "args", "="...
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
[ "Execute", "a", "chef", "client", "run", "and", "return", "a", "dict", "with", "the", "stderr", "stdout", "return", "code", "and", "pid", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chef.py#L56-L141
train
saltstack/salt
salt/modules/chef.py
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)
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)
[ "def", "solo", "(", "whyrun", "=", "False", ",", "logfile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "logfile", "is", "None", ":", "logfile", "=", "_default_logfile", "(", "'chef-solo'", ")", "args", "=", "[", "'chef-solo'", ",", "'--no-co...
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
[ "Execute", "a", "chef", "solo", "run", "and", "return", "a", "dict", "with", "the", "stderr", "stdout", "return", "code", "and", "pid", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chef.py#L145-L206
train
saltstack/salt
salt/transport/frame.py
frame_msg
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)
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)
[ "def", "frame_msg", "(", "body", ",", "header", "=", "None", ",", "raw_body", "=", "False", ")", ":", "# pylint: disable=unused-argument", "framed_msg", "=", "{", "}", "if", "header", "is", "None", ":", "header", "=", "{", "}", "framed_msg", "[", "'head'",...
Frame the given message with our wire protocol
[ "Frame", "the", "given", "message", "with", "our", "wire", "protocol" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/frame.py#L11-L21
train
saltstack/salt
salt/transport/frame.py
frame_msg_ipc
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)
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)
[ "def", "frame_msg_ipc", "(", "body", ",", "header", "=", "None", ",", "raw_body", "=", "False", ")", ":", "# pylint: disable=unused-argument", "framed_msg", "=", "{", "}", "if", "header", "is", "None", ":", "header", "=", "{", "}", "framed_msg", "[", "'hea...
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.
[ "Frame", "the", "given", "message", "with", "our", "wire", "protocol", "for", "IPC" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/frame.py#L24-L40
train
saltstack/salt
salt/transport/frame.py
_decode_embedded_list
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
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
[ "def", "_decode_embedded_list", "(", "src", ")", ":", "output", "=", "[", "]", "for", "elem", "in", "src", ":", "if", "isinstance", "(", "elem", ",", "dict", ")", ":", "elem", "=", "_decode_embedded_dict", "(", "elem", ")", "elif", "isinstance", "(", "...
Convert enbedded bytes to strings if possible. List helper.
[ "Convert", "enbedded", "bytes", "to", "strings", "if", "possible", ".", "List", "helper", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/frame.py#L43-L60
train
saltstack/salt
salt/transport/frame.py
_decode_embedded_dict
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
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
[ "def", "_decode_embedded_dict", "(", "src", ")", ":", "output", "=", "{", "}", "for", "key", ",", "val", "in", "six", ".", "iteritems", "(", "src", ")", ":", "if", "isinstance", "(", "val", ",", "dict", ")", ":", "val", "=", "_decode_embedded_dict", ...
Convert enbedded bytes to strings if possible. Dict helper.
[ "Convert", "enbedded", "bytes", "to", "strings", "if", "possible", ".", "Dict", "helper", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/frame.py#L63-L85
train
saltstack/salt
salt/transport/frame.py
decode_embedded_strs
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
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
[ "def", "decode_embedded_strs", "(", "src", ")", ":", "if", "not", "six", ".", "PY3", ":", "return", "src", "if", "isinstance", "(", "src", ",", "dict", ")", ":", "return", "_decode_embedded_dict", "(", "src", ")", "elif", "isinstance", "(", "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.
[ "Convert", "enbedded", "bytes", "to", "strings", "if", "possible", ".", "This", "is", "necessary", "because", "Python", "3", "makes", "a", "distinction", "between", "these", "types", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/frame.py#L88-L112
train
saltstack/salt
salt/states/disk.py
_validate_int
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
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
[ "def", "_validate_int", "(", "name", ",", "value", ",", "limits", "=", "(", ")", ",", "strip", "=", "'%'", ")", ":", "comment", "=", "''", "# Must be integral", "try", ":", "if", "isinstance", "(", "value", ",", "string_types", ")", ":", "value", "=", ...
Validate the named integer within the supplied limits inclusive and strip supplied unit characters
[ "Validate", "the", "named", "integer", "within", "the", "supplied", "limits", "inclusive", "and", "strip", "supplied", "unit", "characters" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/disk.py#L57-L75
train
saltstack/salt
salt/states/disk.py
status
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)
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)
[ "def", "status", "(", "name", ",", "maximum", "=", "None", ",", "minimum", "=", "None", ",", "absolute", "=", "False", ",", "free", "=", "False", ")", ":", "# Monitoring state, no changes will be made so no test interface needed", "ret", "=", "{", "'name'", ":",...
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.
[ "Return", "the", "current", "disk", "usage", "stats", "for", "the", "named", "mount", "point" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/disk.py#L154-L210
train
saltstack/salt
salt/states/ssh_known_hosts.py
present
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))
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))
[ "def", "present", "(", "name", ",", "user", "=", "None", ",", "fingerprint", "=", "None", ",", "key", "=", "None", ",", "port", "=", "None", ",", "enc", "=", "None", ",", "config", "=", "None", ",", "hash_known_hosts", "=", "True", ",", "timeout", ...
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``
[ "Verifies", "that", "the", "specified", "host", "is", "known", "by", "the", "specified", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ssh_known_hosts.py#L45-L191
train
saltstack/salt
salt/states/ssh_known_hosts.py
absent
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'])
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'])
[ "def", "absent", "(", "name", ",", "user", "=", "None", ",", "config", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "if", "not", ...
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.
[ "Verifies", "that", "the", "specified", "host", "is", "not", "known", "by", "the", "given", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ssh_known_hosts.py#L194-L245
train
saltstack/salt
salt/engines/__init__.py
start_engines
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 )
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 )
[ "def", "start_engines", "(", "opts", ",", "proc_mgr", ",", "proxy", "=", "None", ")", ":", "utils", "=", "salt", ".", "loader", ".", "utils", "(", "opts", ",", "proxy", "=", "proxy", ")", "if", "opts", "[", "'__role'", "]", "==", "'master'", ":", "...
Fire up the configured engines!
[ "Fire", "up", "the", "configured", "engines!" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/__init__.py#L20-L77
train
saltstack/salt
salt/engines/__init__.py
Engine.run
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 )
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 )
[ "def", "run", "(", "self", ")", ":", "self", ".", "utils", "=", "salt", ".", "loader", ".", "utils", "(", "self", ".", "opts", ",", "proxy", "=", "self", ".", "proxy", ")", "if", "salt", ".", "utils", ".", "platform", ".", "is_windows", "(", ")",...
Run the master service!
[ "Run", "the", "master", "service!" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/__init__.py#L124-L149
train
saltstack/salt
salt/roster/range.py
targets
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
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
[ "def", "targets", "(", "tgt", ",", "tgt_type", "=", "'range'", ",", "*", "*", "kwargs", ")", ":", "r", "=", "seco", ".", "range", ".", "Range", "(", "__opts__", "[", "'range_server'", "]", ")", "log", ".", "debug", "(", "'Range connection to \\'%s\\' est...
Return the targets from a range query
[ "Return", "the", "targets", "from", "a", "range", "query" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/range.py#L35-L66
train
saltstack/salt
salt/modules/modjk.py
_auth
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)
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)
[ "def", "_auth", "(", "url", ",", "user", ",", "passwd", ",", "realm", ")", ":", "basic", "=", "_HTTPBasicAuthHandler", "(", ")", "basic", ".", "add_password", "(", "realm", "=", "realm", ",", "uri", "=", "url", ",", "user", "=", "user", ",", "passwd"...
returns a authentication handler.
[ "returns", "a", "authentication", "handler", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L56-L65
train
saltstack/salt
salt/modules/modjk.py
_do_http
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
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
[ "def", "_do_http", "(", "opts", ",", "profile", "=", "'default'", ")", ":", "ret", "=", "{", "}", "url", "=", "__salt__", "[", "'config.get'", "]", "(", "'modjk:{0}:url'", ".", "format", "(", "profile", ")", ",", "''", ")", "user", "=", "__salt__", "...
Make the http request and return the data
[ "Make", "the", "http", "request", "and", "return", "the", "data" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L68-L97
train
saltstack/salt
salt/modules/modjk.py
_worker_ctl
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'
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'
[ "def", "_worker_ctl", "(", "worker", ",", "lbn", ",", "vwa", ",", "profile", "=", "'default'", ")", ":", "cmd", "=", "{", "'cmd'", ":", "'update'", ",", "'mime'", ":", "'prop'", ",", "'w'", ":", "lbn", ",", "'sw'", ":", "worker", ",", "'vwa'", ":",...
enable/disable/stop a worker
[ "enable", "/", "disable", "/", "stop", "a", "worker" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L100-L112
train
saltstack/salt
salt/modules/modjk.py
list_configured_members
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]
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]
[ "def", "list_configured_members", "(", "lbn", ",", "profile", "=", "'default'", ")", ":", "config", "=", "dump_config", "(", "profile", ")", "try", ":", "ret", "=", "config", "[", "'worker.{0}.balance_workers'", ".", "format", "(", "lbn", ")", "]", "except",...
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
[ "Return", "a", "list", "of", "member", "workers", "from", "the", "configuration", "files" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L172-L191
train
saltstack/salt
salt/modules/modjk.py
workers
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
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
[ "def", "workers", "(", "profile", "=", "'default'", ")", ":", "config", "=", "get_running", "(", "profile", ")", "lbn", "=", "config", "[", "'worker.list'", "]", ".", "split", "(", "','", ")", "worker_list", "=", "[", "]", "ret", "=", "{", "}", "for"...
Return a list of member workers and their status CLI Examples: .. code-block:: bash salt '*' modjk.workers salt '*' modjk.workers other-profile
[ "Return", "a", "list", "of", "member", "workers", "and", "their", "status" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L194-L227
train
saltstack/salt
salt/modules/modjk.py
recover_all
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
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
[ "def", "recover_all", "(", "lbn", ",", "profile", "=", "'default'", ")", ":", "ret", "=", "{", "}", "config", "=", "get_running", "(", "profile", ")", "try", ":", "workers_", "=", "config", "[", "'worker.{0}.balance_workers'", ".", "format", "(", "lbn", ...
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
[ "Set", "the", "all", "the", "workers", "in", "lbn", "to", "recover", "and", "activate", "them", "if", "they", "are", "not" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L230-L257
train
saltstack/salt
salt/modules/modjk.py
lb_edit
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'
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'
[ "def", "lb_edit", "(", "lbn", ",", "settings", ",", "profile", "=", "'default'", ")", ":", "settings", "[", "'cmd'", "]", "=", "'update'", "settings", "[", "'mime'", "]", "=", "'prop'", "settings", "[", "'w'", "]", "=", "lbn", "return", "_do_http", "("...
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
[ "Edit", "the", "loadbalancer", "settings" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L280-L299
train
saltstack/salt
salt/modules/modjk.py
bulk_stop
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
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
[ "def", "bulk_stop", "(", "workers", ",", "lbn", ",", "profile", "=", "'default'", ")", ":", "ret", "=", "{", "}", "if", "isinstance", "(", "workers", ",", "six", ".", "string_types", ")", ":", "workers", "=", "workers", ".", "split", "(", "','", ")",...
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
[ "Stop", "all", "the", "given", "workers", "in", "the", "specific", "load", "balancer" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L302-L328
train
saltstack/salt
salt/modules/modjk.py
bulk_activate
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
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
[ "def", "bulk_activate", "(", "workers", ",", "lbn", ",", "profile", "=", "'default'", ")", ":", "ret", "=", "{", "}", "if", "isinstance", "(", "workers", ",", "six", ".", "string_types", ")", ":", "workers", "=", "workers", ".", "split", "(", "','", ...
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
[ "Activate", "all", "the", "given", "workers", "in", "the", "specific", "load", "balancer" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L331-L357
train
saltstack/salt
salt/modules/modjk.py
bulk_disable
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
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
[ "def", "bulk_disable", "(", "workers", ",", "lbn", ",", "profile", "=", "'default'", ")", ":", "ret", "=", "{", "}", "if", "isinstance", "(", "workers", ",", "six", ".", "string_types", ")", ":", "workers", "=", "workers", ".", "split", "(", "','", "...
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
[ "Disable", "all", "the", "given", "workers", "in", "the", "specific", "load", "balancer" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L360-L386
train
saltstack/salt
salt/modules/modjk.py
bulk_recover
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
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
[ "def", "bulk_recover", "(", "workers", ",", "lbn", ",", "profile", "=", "'default'", ")", ":", "ret", "=", "{", "}", "if", "isinstance", "(", "workers", ",", "six", ".", "string_types", ")", ":", "workers", "=", "workers", ".", "split", "(", "','", "...
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
[ "Recover", "all", "the", "given", "workers", "in", "the", "specific", "load", "balancer" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L389-L415
train
saltstack/salt
salt/modules/modjk.py
worker_status
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
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
[ "def", "worker_status", "(", "worker", ",", "profile", "=", "'default'", ")", ":", "config", "=", "get_running", "(", "profile", ")", "try", ":", "return", "{", "'activation'", ":", "config", "[", "'worker.{0}.activation'", ".", "format", "(", "worker", ")",...
Return the state of the worker CLI Examples: .. code-block:: bash salt '*' modjk.worker_status node1 salt '*' modjk.worker_status node1 other-profile
[ "Return", "the", "state", "of", "the", "worker" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L418-L437
train
saltstack/salt
salt/modules/modjk.py
worker_recover
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)
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)
[ "def", "worker_recover", "(", "worker", ",", "lbn", ",", "profile", "=", "'default'", ")", ":", "cmd", "=", "{", "'cmd'", ":", "'recover'", ",", "'mime'", ":", "'prop'", ",", "'w'", ":", "lbn", ",", "'sw'", ":", "worker", ",", "}", "return", "_do_htt...
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
[ "Set", "the", "worker", "to", "recover", "this", "module", "will", "fail", "if", "it", "is", "in", "OK", "state" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L440-L459
train
saltstack/salt
salt/modules/modjk.py
worker_edit
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'
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'
[ "def", "worker_edit", "(", "worker", ",", "lbn", ",", "settings", ",", "profile", "=", "'default'", ")", ":", "settings", "[", "'cmd'", "]", "=", "'update'", "settings", "[", "'mime'", "]", "=", "'prop'", "settings", "[", "'w'", "]", "=", "lbn", "setti...
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
[ "Edit", "the", "worker", "settings" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/modjk.py#L507-L527
train
saltstack/salt
salt/modules/nginx.py
build_info
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
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
[ "def", "build_info", "(", ")", ":", "ret", "=", "{", "'info'", ":", "[", "]", "}", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "'{0} -V'", ".", "format", "(", "__detect_os", "(", ")", ")", ")", "for", "i", "in", "out", ".", "splitlines", ...
Return server and build arguments CLI Example: .. code-block:: bash salt '*' nginx.build_info
[ "Return", "server", "and", "build", "arguments" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nginx.py#L50-L70
train
saltstack/salt
salt/modules/nginx.py
signal
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
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
[ "def", "signal", "(", "signal", "=", "None", ")", ":", "valid_signals", "=", "(", "'start'", ",", "'reopen'", ",", "'stop'", ",", "'quit'", ",", "'reload'", ")", "if", "signal", "not", "in", "valid_signals", ":", "return", "# Make sure you use the right argume...
Signals nginx to start, reload, reopen or stop. CLI Example: .. code-block:: bash salt '*' nginx.signal reload
[ "Signals", "nginx", "to", "start", "reload", "reopen", "or", "stop", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nginx.py#L102-L136
train
saltstack/salt
salt/modules/nginx.py
status
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), }
python
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), }
[ "def", "status", "(", "url", "=", "\"http://127.0.0.1/status\"", ")", ":", "resp", "=", "_urlopen", "(", "url", ")", "status_data", "=", "resp", ".", "read", "(", ")", "resp", ".", "close", "(", ")", "lines", "=", "status_data", ".", "splitlines", "(", ...
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
[ "Return", "the", "data", "from", "an", "Nginx", "status", "page", "as", "a", "dictionary", ".", "http", ":", "//", "wiki", ".", "nginx", ".", "org", "/", "HttpStubStatusModule" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nginx.py#L139-L175
train
saltstack/salt
salt/proxy/esxi.py
init
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')
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')
[ "def", "init", "(", "opts", ")", ":", "log", ".", "debug", "(", "'Initting esxi proxy module in process %s'", ",", "os", ".", "getpid", "(", ")", ")", "log", ".", "debug", "(", "'Validating esxi proxy input'", ")", "schema", "=", "EsxiProxySchema", ".", "seria...
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.
[ "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", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/esxi.py#L314-L414
train
saltstack/salt
salt/proxy/esxi.py
ping
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
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
[ "def", "ping", "(", ")", ":", "if", "DETAILS", ".", "get", "(", "'esxi_host'", ")", ":", "return", "True", "else", ":", "# TODO Check connection if mechanism is SSPI", "if", "DETAILS", "[", "'mechanism'", "]", "==", "'userpass'", ":", "find_credentials", "(", ...
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
[ "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", "E...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/esxi.py#L436-L461
train
saltstack/salt
salt/proxy/esxi.py
ch_config
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)
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)
[ "def", "ch_config", "(", "cmd", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Strip the __pub_ keys...is there a better way to do this?", "for", "k", "in", "kwargs", ":", "if", "k", ".", "startswith", "(", "'__pub_'", ")", ":", "kwargs", ".", "pop"...
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.
[ "This", "function", "is", "called", "by", "the", ":", "mod", ":", "salt", ".", "modules", ".", "esxi", ".", "cmd", "<salt", ".", "modules", ".", "esxi", ".", "cmd", ">", "shim", ".", "It", "then", "calls", "whatever", "is", "passed", "in", "cmd", "...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/esxi.py#L472-L505
train
saltstack/salt
salt/proxy/esxi.py
find_credentials
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.')
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.')
[ "def", "find_credentials", "(", "host", ")", ":", "user_names", "=", "[", "__pillar__", "[", "'proxy'", "]", ".", "get", "(", "'username'", ",", "'root'", ")", "]", "passwords", "=", "__pillar__", "[", "'proxy'", "]", "[", "'passwords'", "]", "for", "use...
Cycle through all the possible credentials and return the first one that works.
[ "Cycle", "through", "all", "the", "possible", "credentials", "and", "return", "the", "first", "one", "that", "works", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/esxi.py#L508-L531
train
saltstack/salt
salt/proxy/esxi.py
_grains
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
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
[ "def", "_grains", "(", "host", ",", "protocol", "=", "None", ",", "port", "=", "None", ")", ":", "username", ",", "password", "=", "find_credentials", "(", "DETAILS", "[", "'host'", "]", ")", "ret", "=", "__salt__", "[", "'vsphere.system_info'", "]", "("...
Helper function to the grains from the proxied device.
[ "Helper", "function", "to", "the", "grains", "from", "the", "proxied", "device", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/esxi.py#L534-L545
train
saltstack/salt
salt/modules/telegram.py
post_message
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)
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)
[ "def", "post_message", "(", "message", ",", "chat_id", "=", "None", ",", "token", "=", "None", ")", ":", "if", "not", "chat_id", ":", "chat_id", "=", "_get_chat_id", "(", ")", "if", "not", "token", ":", "token", "=", "_get_token", "(", ")", "if", "no...
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!"
[ "Send", "a", "message", "to", "a", "Telegram", "chat", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/telegram.py#L71-L97
train
saltstack/salt
salt/modules/telegram.py
_post_message
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
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
[ "def", "_post_message", "(", "message", ",", "chat_id", ",", "token", ")", ":", "url", "=", "'https://api.telegram.org/bot{0}/sendMessage'", ".", "format", "(", "token", ")", "parameters", "=", "dict", "(", ")", "if", "chat_id", ":", "parameters", "[", "'chat_...
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.
[ "Send", "a", "message", "to", "a", "Telegram", "chat", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/telegram.py#L100-L140
train
saltstack/salt
salt/roster/ansible.py
targets
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}
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}
[ "def", "targets", "(", "tgt", ",", "tgt_type", "=", "'glob'", ",", "*", "*", "kwargs", ")", ":", "inventory", "=", "__runner__", "[", "'salt.cmd'", "]", "(", "'cmd.run'", ",", "'ansible-inventory -i {0} --list'", ".", "format", "(", "get_roster_file", "(", "...
Return the targets from the ansible inventory_file Default: /etc/salt/roster
[ "Return", "the", "targets", "from", "the", "ansible", "inventory_file", "Default", ":", "/", "etc", "/", "salt", "/", "roster" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/ansible.py#L115-L127
train
saltstack/salt
salt/sdb/cache.py
set_
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)
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)
[ "def", "set_", "(", "key", ",", "value", ",", "service", "=", "None", ",", "profile", "=", "None", ")", ":", "# pylint: disable=W0613", "key", ",", "profile", "=", "_parse_key", "(", "key", ",", "profile", ")", "cache", "=", "salt", ".", "cache", ".", ...
Set a key/value pair in the cache service
[ "Set", "a", "key", "/", "value", "pair", "in", "the", "cache", "service" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/cache.py#L66-L73
train
saltstack/salt
salt/sdb/cache.py
get
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)
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)
[ "def", "get", "(", "key", ",", "service", "=", "None", ",", "profile", "=", "None", ")", ":", "# pylint: disable=W0613", "key", ",", "profile", "=", "_parse_key", "(", "key", ",", "profile", ")", "cache", "=", "salt", ".", "cache", ".", "Cache", "(", ...
Get a value from the cache service
[ "Get", "a", "value", "from", "the", "cache", "service" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/cache.py#L76-L82
train
saltstack/salt
salt/sdb/cache.py
delete
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
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
[ "def", "delete", "(", "key", ",", "service", "=", "None", ",", "profile", "=", "None", ")", ":", "# pylint: disable=W0613", "key", ",", "profile", "=", "_parse_key", "(", "key", ",", "profile", ")", "cache", "=", "salt", ".", "cache", ".", "Cache", "("...
Get a value from the cache service
[ "Get", "a", "value", "from", "the", "cache", "service" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/cache.py#L85-L95
train
saltstack/salt
salt/sdb/cache.py
_parse_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
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
[ "def", "_parse_key", "(", "key", ",", "profile", ")", ":", "comps", "=", "key", ".", "split", "(", "'?'", ")", "if", "len", "(", "comps", ")", ">", "1", ":", "for", "item", "in", "comps", "[", "1", "]", ".", "split", "(", "'&'", ")", ":", "ne...
Parse out a key and update the opts with any override data
[ "Parse", "out", "a", "key", "and", "update", "the", "opts", "with", "any", "override", "data" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/cache.py#L98-L109
train
saltstack/salt
salt/tokens/rediscluster.py
_redis_client
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
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
[ "def", "_redis_client", "(", "opts", ")", ":", "redis_host", "=", "opts", ".", "get", "(", "\"eauth_redis_host\"", ",", "\"localhost\"", ")", "redis_port", "=", "opts", ".", "get", "(", "\"eauth_redis_port\"", ",", "6379", ")", "try", ":", "return", "rediscl...
Connect to the redis host and return a StrictRedisCluster client object. If connection fails then return None.
[ "Connect", "to", "the", "redis", "host", "and", "return", "a", "StrictRedisCluster", "client", "object", ".", "If", "connection", "fails", "then", "return", "None", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tokens/rediscluster.py#L48-L62
train
saltstack/salt
salt/tokens/rediscluster.py
mk_token
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
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
[ "def", "mk_token", "(", "opts", ",", "tdata", ")", ":", "redis_client", "=", "_redis_client", "(", "opts", ")", "if", "not", "redis_client", ":", "return", "{", "}", "hash_type", "=", "getattr", "(", "hashlib", ",", "opts", ".", "get", "(", "'hash_type'"...
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.
[ "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", "to...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tokens/rediscluster.py#L65-L99
train
saltstack/salt
salt/tokens/rediscluster.py
get_token
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 {}
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 {}
[ "def", "get_token", "(", "opts", ",", "tok", ")", ":", "redis_client", "=", "_redis_client", "(", "opts", ")", "if", "not", "redis_client", ":", "return", "{", "}", "serial", "=", "salt", ".", "payload", ".", "Serial", "(", "opts", ")", "try", ":", "...
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.
[ "Fetch", "the", "token", "data", "from", "the", "store", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tokens/rediscluster.py#L102-L122
train
saltstack/salt
salt/tokens/rediscluster.py
rm_token
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)
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)
[ "def", "rm_token", "(", "opts", ",", "tok", ")", ":", "redis_client", "=", "_redis_client", "(", "opts", ")", "if", "not", "redis_client", ":", "return", "try", ":", "redis_client", ".", "delete", "(", "tok", ")", "return", "{", "}", "except", "Exception...
Remove token from the store. :param opts: Salt master config options :param tok: Token to remove :returns: Empty dict if successful. None if failed.
[ "Remove", "token", "from", "the", "store", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tokens/rediscluster.py#L125-L140
train
saltstack/salt
salt/tokens/rediscluster.py
list_tokens
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 []
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 []
[ "def", "list_tokens", "(", "opts", ")", ":", "ret", "=", "[", "]", "redis_client", "=", "_redis_client", "(", "opts", ")", "if", "not", "redis_client", ":", "return", "[", "]", "serial", "=", "salt", ".", "payload", ".", "Serial", "(", "opts", ")", "...
List all tokens in the store. :param opts: Salt master config options :returns: List of dicts (token_data)
[ "List", "all", "tokens", "in", "the", "store", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tokens/rediscluster.py#L143-L159
train
saltstack/salt
salt/states/wordpress.py
installed
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
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
[ "def", "installed", "(", "name", ",", "user", ",", "admin_user", ",", "admin_password", ",", "admin_email", ",", "title", ",", "url", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", ",",...
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
[ "Run", "the", "initial", "setup", "of", "wordpress" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/wordpress.py#L16-L78
train
saltstack/salt
salt/states/wordpress.py
activated
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
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
[ "def", "activated", "(", "name", ",", "path", ",", "user", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", ",", "'result'", ":", "False", "}", "check", "=", "__salt__", "[", "'wordpres...
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
[ "Activate", "wordpress", "plugins" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/wordpress.py#L81-L135
train
saltstack/salt
salt/modules/scp_mod.py
_prepare_connection
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
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
[ "def", "_prepare_connection", "(", "*", "*", "kwargs", ")", ":", "paramiko_kwargs", ",", "scp_kwargs", "=", "_select_kwargs", "(", "*", "*", "kwargs", ")", "ssh", "=", "paramiko", ".", "SSHClient", "(", ")", "if", "paramiko_kwargs", ".", "pop", "(", "'auto...
Prepare the underlying SSH connection with the remote target.
[ "Prepare", "the", "underlying", "SSH", "connection", "with", "the", "remote", "target", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/scp_mod.py#L55-L66
train
saltstack/salt
salt/modules/scp_mod.py
get
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)
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)
[ "def", "get", "(", "remote_path", ",", "local_path", "=", "''", ",", "recursive", "=", "False", ",", "preserve_times", "=", "False", ",", "*", "*", "kwargs", ")", ":", "scp_client", "=", "_prepare_connection", "(", "*", "*", "kwargs", ")", "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
[ "Transfer", "files", "and", "directories", "from", "remote", "host", "to", "the", "localhost", "of", "the", "Minion", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/scp_mod.py#L69-L151
train
saltstack/salt
salt/modules/scp_mod.py
put
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)
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)
[ "def", "put", "(", "files", ",", "remote_path", "=", "None", ",", "recursive", "=", "False", ",", "preserve_times", "=", "False", ",", "saltenv", "=", "'base'", ",", "*", "*", "kwargs", ")", ":", "scp_client", "=", "_prepare_connection", "(", "*", "*", ...
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
[ "Transfer", "files", "and", "directories", "to", "remote", "host", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/scp_mod.py#L154-L244
train
saltstack/salt
salt/modules/bigip.py
_build_session
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
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
[ "def", "_build_session", "(", "username", ",", "password", ",", "trans_label", "=", "None", ")", ":", "bigip", "=", "requests", ".", "session", "(", ")", "bigip", ".", "auth", "=", "(", "username", ",", "password", ")", "bigip", ".", "verify", "=", "Fa...
Create a session to be used when connecting to iControl REST.
[ "Create", "a", "session", "to", "be", "used", "when", "connecting", "to", "iControl", "REST", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L43-L62
train
saltstack/salt
salt/modules/bigip.py
_load_response
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
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
[ "def", "_load_response", "(", "response", ")", ":", "try", ":", "data", "=", "salt", ".", "utils", ".", "json", ".", "loads", "(", "response", ".", "text", ")", "except", "ValueError", ":", "data", "=", "response", ".", "text", "ret", "=", "{", "'cod...
Load the response from json data, return the dictionary or raw text
[ "Load", "the", "response", "from", "json", "data", "return", "the", "dictionary", "or", "raw", "text" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L65-L77
train
saltstack/salt
salt/modules/bigip.py
_load_connection_error
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
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
[ "def", "_load_connection_error", "(", "hostname", ",", "error", ")", ":", "ret", "=", "{", "'code'", ":", "None", ",", "'content'", ":", "'Error: Unable to connect to the bigip device: {host}\\n{error}'", ".", "format", "(", "host", "=", "hostname", ",", "error", ...
Format and Return a connection error
[ "Format", "and", "Return", "a", "connection", "error" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L80-L87
train
saltstack/salt
salt/modules/bigip.py
_loop_payload
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
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
[ "def", "_loop_payload", "(", "params", ")", ":", "#construct the payload", "payload", "=", "{", "}", "#set the payload", "for", "param", ",", "value", "in", "six", ".", "iteritems", "(", "params", ")", ":", "if", "value", "is", "not", "None", ":", "payload...
Pass in a dictionary of parameters, loop through them and build a payload containing, parameters who's values are not None.
[ "Pass", "in", "a", "dictionary", "of", "parameters", "loop", "through", "them", "and", "build", "a", "payload", "containing", "parameters", "who", "s", "values", "are", "not", "None", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L90-L104
train
saltstack/salt
salt/modules/bigip.py
_build_list
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
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
[ "def", "_build_list", "(", "option_value", ",", "item_kind", ")", ":", "#specify profiles if provided", "if", "option_value", "is", "not", "None", ":", "items", "=", "[", "]", "#if user specified none, return an empty list", "if", "option_value", "==", "'none'", ":", ...
pass in an option to check for a list of items, create a list of dictionary of items to set for this option
[ "pass", "in", "an", "option", "to", "check", "for", "a", "list", "of", "items", "create", "a", "list", "of", "dictionary", "of", "items", "to", "set", "for", "this", "option" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L107-L135
train
saltstack/salt
salt/modules/bigip.py
_determine_toggles
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
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
[ "def", "_determine_toggles", "(", "payload", ",", "toggles", ")", ":", "for", "toggle", ",", "definition", "in", "six", ".", "iteritems", "(", "toggles", ")", ":", "#did the user specify anything?", "if", "definition", "[", "'value'", "]", "is", "not", "None",...
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.
[ "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", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L138-L159
train
saltstack/salt
salt/modules/bigip.py
_set_value
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
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
[ "def", "_set_value", "(", "value", ")", ":", "#don't continue if already an acceptable data-type", "if", "isinstance", "(", "value", ",", "bool", ")", "or", "isinstance", "(", "value", ",", "dict", ")", "or", "isinstance", "(", "value", ",", "list", ")", ":", ...
A function to detect if user is trying to pass a dictionary or list. parse it and return a dictionary list or a string
[ "A", "function", "to", "detect", "if", "user", "is", "trying", "to", "pass", "a", "dictionary", "or", "list", ".", "parse", "it", "and", "return", "a", "dictionary", "list", "or", "a", "string" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L162-L219
train
saltstack/salt
salt/modules/bigip.py
start_transaction
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
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
[ "def", "start_transaction", "(", "hostname", ",", "username", ",", "password", ",", "label", ")", ":", "#build the session", "bigip_session", "=", "_build_session", "(", "username", ",", "password", ")", "payload", "=", "{", "}", "#post to REST to get trans id", "...
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
[ "A", "function", "to", "connect", "to", "a", "bigip", "device", "and", "start", "a", "new", "transaction", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L222-L268
train
saltstack/salt
salt/modules/bigip.py
list_transaction
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'
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'
[ "def", "list_transaction", "(", "hostname", ",", "username", ",", "password", ",", "label", ")", ":", "#build the session", "bigip_session", "=", "_build_session", "(", "username", ",", "password", ")", "#pull the trans id from the grain", "trans_id", "=", "__salt__",...
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
[ "A", "function", "to", "connect", "to", "a", "bigip", "device", "and", "list", "an", "existing", "transaction", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L271-L307
train
saltstack/salt
salt/modules/bigip.py
create_node
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)
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)
[ "def", "create_node", "(", "hostname", ",", "username", ",", "password", ",", "name", ",", "address", ",", "trans_label", "=", "None", ")", ":", "#build session", "bigip_session", "=", "_build_session", "(", "username", ",", "password", ",", "trans_label", ")"...
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
[ "A", "function", "to", "connect", "to", "a", "bigip", "device", "and", "create", "a", "node", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L430-L469
train
saltstack/salt
salt/modules/bigip.py
modify_node
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)
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)
[ "def", "modify_node", "(", "hostname", ",", "username", ",", "password", ",", "name", ",", "connection_limit", "=", "None", ",", "description", "=", "None", ",", "dynamic_ratio", "=", "None", ",", "logging", "=", "None", ",", "monitor", "=", "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
[ "A", "function", "to", "connect", "to", "a", "bigip", "device", "and", "modify", "an", "existing", "node", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L472-L549
train
saltstack/salt
salt/modules/bigip.py
create_pool
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)
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)
[ "def", "create_pool", "(", "hostname", ",", "username", ",", "password", ",", "name", ",", "members", "=", "None", ",", "allow_nat", "=", "None", ",", "allow_snat", "=", "None", ",", "description", "=", "None", ",", "gateway_failsafe_device", "=", "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
[ "A", "function", "to", "connect", "to", "a", "bigip", "device", "and", "create", "a", "pool", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L622-L773
train
saltstack/salt
salt/modules/bigip.py
replace_pool_members
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)
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)
[ "def", "replace_pool_members", "(", "hostname", ",", "username", ",", "password", ",", "name", ",", "members", ")", ":", "payload", "=", "{", "}", "payload", "[", "'name'", "]", "=", "name", "#specify members if provided", "if", "members", "is", "not", "None...
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
[ "A", "function", "to", "connect", "to", "a", "bigip", "device", "and", "replace", "members", "of", "an", "existing", "pool", "with", "new", "members", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L956-L1020
train
saltstack/salt
salt/modules/bigip.py
add_pool_member
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)
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)
[ "def", "add_pool_member", "(", "hostname", ",", "username", ",", "password", ",", "name", ",", "member", ")", ":", "# for states", "if", "isinstance", "(", "member", ",", "dict", ")", ":", "#check for state alternative name 'member_state', replace with state", "if", ...
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
[ "A", "function", "to", "connect", "to", "a", "bigip", "device", "and", "add", "a", "new", "member", "to", "an", "existing", "pool", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L1023-L1076
train